Thursday, July 14, 2016

Eclipse shortcuts

Frequently used eclipse shortcuts

OperationShortcut Purpose
Open ResourceCtrl+Shift+R Open Resource (file, folder or project)
Ctrl + Shift + TOpen Resource (file, class file)
Ctrl + TOpen implementation
SaveCtrl+S Save current file
Ctrl+Shift+S Save all files
CloseCtrl+W Close current file
Ctrl+Shift+W Close all files
Navigate through fileCtrl + Home Jump to beginning of file
Ctrl +L Jump to Line Number.
Ctrl + End Jump to end of file
Ctrl+K/Ctrl+Shift+K Find previous / find next occurrence of search term
FormatterCtrl+Shift+F Autoformat all code in Editor using code formatter
Java docAlt+Shift+J Add Element Comment
AssistanceCtrl+Space Opens Content Assist (e.g. show available methods or field names)
Ctrl+1 Open Quick Fix and Quick Assist
Search Ctrl+Alt+H Open Call Hierarchy
Ctrl + H Search
RefactoringAlt+Shift+R Rename selected element and all references
Alt+Shift+M Extract selection to method 

Monday, July 4, 2016

Common operations- Stream Java8

Streams API in Java8 provides good number of Stream operations to operate on input provided. These operationsreduce lot of code to be written and increases readability.Some of the most important functions are described below with examples
  • Collect(toList()) :- is an eager operation which generates list from a given stream
        Example :- Below example describes the use of collect  operation which gets the  list of skills  from employees
/**
package com.test;

import java.util.ArrayList;

/**
 * @author sudheer
 *
 */
public class Tester {

	public Employee createEmployee(int employeeId, float experience, String firstName, String lastName, String skill) {
		Employee emp = new Employee();
		emp.setEmployeeId(employeeId);
		emp.setExperience(experience);
		emp.setFirstName(firstName);
		emp.setLastName(lastName);
		emp.setSkill(skill);
		return emp;

	}

	public static void main(String[] args) {
		Tester test = new Tester();
		List<Employee> employees = new ArrayList<Employee>();
		employees.add(test.createEmployee(1, 5, "Sudheer", "Reddy", "Java"));
		employees.add(test.createEmployee(2, 4, "Keerthi", "Reddy", "Java"));
		employees.add(test.createEmployee(3, 7, "Loknath", "Reddy", ".Net"));
		employees.add(test.createEmployee(4, 5, "Satish", "Reddy", "C++"));

		// Applying eager operation count
		employees.stream().filter(employee -> {
			System.out.println("Employee skill->" + employee.getSkill());
			return "Java".equals(employee.getSkill());
		}).count();

		// Lazy operations .output is not printed on console ,because traversal
		// of the filtered stream is not done until eager operation is called
		employees.stream().filter(employee -> {
			System.out.println("Employee skill->" + employee.getSkill());
			return "Java".equals(employee.getSkill());
		});

	}

}

  • map :- 

    •  used to replace values in a stream with new values like converting stream of lowercase letter array to uppercase letter array
    • Returns a stream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation.
    • its a lazy operation  which will  return output as Stream object.
         Example :- In the above example map is used to get/convert stream of employees into an intermediate stream of Skills
List<String> list = employees.stream().map(Employee::getSkill).collect(Collectors.toList());

  • Filter :- 

    • This operation is used to filter out the result by keeping some elements in  Stream and throwing out the other elements.
    • is used  to get required values from a Stream 
    • This is a lazy operation , traversal of intermediate new Stream will not be started until eager operation is called  .
        Example :- Below example describes the use of collect  operation which gets the  list of skills  from employees



package com.test;

import java.util.ArrayList;

/**
 * @author sudheer
 *
 */
public class Tester {

	public Employee createEmployee(int employeeId, float experience, String firstName, String lastName, String skill) {
		Employee emp = new Employee();
		emp.setEmployeeId(employeeId);
		emp.setExperience(experience);
		emp.setFirstName(firstName);
		emp.setLastName(lastName);
		emp.setSkill(skill);
		return emp;

	}

	public static void main(String[] args) {
		Tester test = new Tester();
		List<Employee> employees = new ArrayList<Employee>();
		employees.add(test.createEmployee(1, 5, "Sudheer", "Reddy", "Java"));
		employees.add(test.createEmployee(2, 4, "Keerthi", "Reddy", "Java"));
		employees.add(test.createEmployee(3, 7, "Loknath", "Reddy", ".Net"));
		employees.add(test.createEmployee(4, 5, "Satish", "Reddy", "C++"));

		// Applying eager operation count
		employees.stream().filter(employee -> {
			System.out.println("Employee skill->" + employee.getSkill());
			return "Java".equals(employee.getSkill());
		}).count();

		// Lazy operations .output is not printed on console ,because traversal
		// of the filtered stream is not done until eager operation is called
		employees.stream().filter(employee -> {
			System.out.println("Employee skill->" + employee.getSkill());
			return "Java".equals(employee.getSkill());
		});

	}

}

Note :- In above example  @ 1 the out put is printed as  below this is due to call of eager function count(...)

Employee skill->Java
Employee skill->Java
Employee skill->.Net
Employee skill->C++

@ 2 there is no eager function called so no output is printed when executed.


In next post we will discuss about flatMap,reduce,sort etc. Stream operations
Happy learning 

Saturday, July 2, 2016

Streams in Java8 -Post1

 Stream :- 
    • Stream is a new addtion to Collection API in Java8 for building  complex operations on collections using functional approach.These are different from input and output streams
    • Stream takes Collections ,Arrays or I/O operations as input build up internal sequence of elements and perform required operations on them and gives the final result
    • Streams allow us  to write collections-processing code at a higher level of abstraction. The Stream interface contains a series of functions that will be used to perform common operations on collection. For example  iterating over a collections, filtering out a list of values based on some criteria      
    • No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.
    • Streams as said are  functional in nature . Streams doesn't modify directly  the  collection/source its working  it just produces the final result  
    • Laziness-seeking :- Many functions[filter,map etc] that are provided by stream perform lazy evaluation, Methods that build up a Stream recipe but donot force a new value to be generated at the end are referred to as lazy.
    •  Intermediate operations  return a new stream which meets the condition of predicate passed, they are always lazily executed.Traversal of pipeline source  will not be started until Terminal operation is called. 
    • Terminal operations are executed eagerly. all the  intermediate operations are executed when they reach a terminal operation.

    •       In below example only filter is used on employees list, as this is a lazy function actual stream result did not build
Lazy operation. out put not printed
           
          Here count method is called which will build  required Stream result . Methods that use the 
      stream recipe generated and produce a final result are called Eager methods
Eager operation count
    • Its easy to find a function Lazy or Eager. If a function  returns a stream then its lazy,if it returns  a value other than stream  or void then its eager function       

       There are two variants of streams available in Java8
  1. Stream :-  Returns a sequential stream
  2. ParllelStream :- Stream executes in parallel i.e Java runtime  divides the stream into multiple sub streams . Aggregate operations iterate over and process the substream in parallel and then combine the result











Sunday, November 17, 2013

Page Refreshing

Hi,

In this post we will discuss about refreshing a web page at regular interval of time.
There are many ways to do this .
  • Using Java script
  • Setting response headers etc.

We would have seen many popular websites like Facebook, GMail etc. where a page will be refreshing automatically and updating the content at regular intervals of time.
Lets see how to refresh a JSP page with an example.

By using response header
Example :-

PageRefresh.jsp
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@page import="java.util.Date" %>
<head>
<title>Page refresh</title>
</head>
<body>
<%response.setHeader("refresh","5");%>
<%Date date=new Date(); %>
<%="Current time " +date %>
</body>
</html>

Here we have used response.setHeader("refresh","5") ,which takes two parameters—refresh attribute and time interval for page refreshing in seconds. PageRefresh.jsp will be refreshing every 5 seconds and displaying the cureent date and time

Output:-

Current time Sun Jun 30 10:21:21 IST 2013

Current time Sun Jun 30 10:21:26 IST 2013

Environment details :-
  • Eclipse Juno
  • Apache Tomcat

                      Happy Learning

Please provide your valuable comments on this article and share it across your network.



Sunday, October 27, 2013

Named and Native Queries in JPA

Named  and Native Queries in JPA :-
  • Named queires are reusable and can be declared at Entity level
  • @NamedQuery annotation is used
  • multiple named queries are declared in @NamedQueries
  • For executing native queries we use @NamedNativeQueries

@NamedQuery :-
@NamedQuery(name = "allCompanyDetails", query = "SELECT c FROM Company c")

Named query is called by using query = em.createNamedQuery("allCompanyDetails");

@NamedQueries :- annotation is used for declaring multiple named queries at entity level
In the below snippet we have two named queries-"allCompanyDetails" and "onlyMailIds"

@NamedQueries({ @NamedQuery(name = "allCompanyDetails", query = "SELECT c FROM Company c"),
@NamedQuery(name="onlyMailIds",query="SELECT c.mail FROM Company c")
})

Native Queries are used to execute SQL statements directly and to call procedures and functions from JPA
@NamedNativeQueries :-
@NamedNativeQuery(name = "nativeQueryEx", query = "select * from company")

entityManager.createNativeQuery("query") is used to execute native queries

Similar to SQL in JPQL we can write join queries etc,instead of Table names we use Entity class names

Query query = em.createQuery("SELECT c from Company c,Department d where c.mail= d.mail and c.name LIKE 'T%'");

Like and Share