Add Google Code Style Templates

Add Google Style for Java

Download xml file using this url–> eclipse-java-google-style

Instructions,

  • Open eclipse->window->preference->Java->Code Style->Formatter.
  • Import the downloaded xml file.
  • Press Apply and Ok.

How to Use,

  • You can use Ctrl+Shift+F short cut key in your java code.

Tips,

You can use auto formatting action on save (Open eclipse->window->preference->Java->Editor->Save Actions->check Perform the selected actions on save->check Format source code)

 

Add Google Style for JavaScript

Download xml file using this url–>google-style-guide-javascript-eclipse

Instructions,

  • Open eclipse->window->preference->JavaScript->Code Style->Formatter.
  • Import the downloaded xml file.
  • Press Apply and Ok.

How to Use,

  • You can use Ctrl+Shift+F short cut key in your java script code.

Tips,

You can use auto formatting action on save (Open eclipse->window->preference->JavaScript->Editor->Save Actions->check Perform the selected actions on save->check Format source code)

 

Add Google Style for HTML

Instructions,

  • Open eclipse->window->preference->Web->HTML Files->Editor.
  • Enter 140 as Line width
  • Press Apply and Ok.

 

Eclipse Short Cut Keys

1. Manage Files and Projects

Ctrl+N Create new project using the Wizard
Ctrl+Alt+N Create new project, file, class, etc.
Alt+F, then . Open project, file, etc.
Ctrl+Shift+R Open Resource (file, folder or project)
Alt+Enter Show and access file properties
Ctrl+S Save current file
Ctrl+Shift+S Save all files
Ctrl+W Close current file
Ctrl+Shift+W Close all files
F5 Refresh content of selected element with local file system

minus2. Editor Window

Focus/ cursor must be in Editor Window for these to work.
F12 Jump to Editor Window
Ctrl+Page Down/Ctrl+Page Up Switch to next editor / switch to previous editor
Ctrl+M Maximize or un-maximize current Editor Window (also works for other Windows)
Ctrl+F6/Ctrl+Shift+F6 Show list of open Editors. Similar to ctrl+e but switches immediately upon release of ctrl
Alt+Arrow Left/Alt+Arrow Right Go to previous / go to next Editor Window
Ctrl+F10 Show view menu (features available on left vertical bar: breakpoints, bookmarks, line numbers, …)
Ctrl+F10, then n Show or hide line numbers

minus3. Navigate in Editor

Home/End Jump to beginning / jump to end of indention. Press home twice to jump to beginning of line
Ctrl+Home/End Jump to beginning / jump to end of source
Ctrl+Arrow Right/Arrow Left Jump one word to the left / one word to the right
Ctrl+Shift+Arrow Down/Arrow Up Jump to previous / jump to next method
Ctrl+L Jump to Line Number. To hide/show line numbers, press ctrl+F10 and select ‘Show Line Numbers’
Ctrl+Q Jump to last location edited
Ctrl+./Ctrl+, Jump to next / jump to previous compiler syntax warning or error
Ctrl+Shift+P With a bracket selected: jump to the matching closing or opening bracket
Ctrl+[+]/Ctrl+ on numeric keyboard Collapse / Expand current method or class
Ctrl+[/]/Ctrl+* on numeric keyboard Collapse / Expand all methods or classes
Ctrl+Arrow Down/Ctrl+Arrow Up Scroll Editor without changing cursor position
Alt+Page Up/Alt+Page Down Next Sub-Tab / Previous Sub-Tab

minus4. Select Text

Shift+Arrow Right/Arrow Left Expand selection by one character to the left / to the right
Ctrl+Shift+Arrow Right/Arrow Left Expand selection to next / previous word
Shift+Arrow Down/Arrow Up Expand selection by one line down / one line up
Shift+End/Home Expand selection to end / to beginning of line
Ctrl+A Select all
Alt+Shift+Arrow Up Expand selection to current element (e.g. current one-line expression or content within brackets)
Alt+Shift+Arrow Left/Arrow Right Expand selection to next / previous element
Alt+Shift+Arrow Down Reduce previously expanded selection by one step

minus5. Edit Text

Ctrl+C/Ctrl+X/Ctrl+V Cut, copy and paste
Ctrl+Z Undo last action
Ctrl+Y Redo last (undone) action
Ctrl+D Delete Line
Alt+Arrow Up/Arrow Down Move current line or selection up or down
Ctrl+Alt+Arrow Up/Ctrl+Alt+Arrow Down/ Duplicate current line or selection up or down
Ctrl+Delete Delete next word
Ctrl+Backspace Delete previous word
Shift+Enter Enter line below current line
Shift+Ctrl+Enter Enter line above current line
Insert Switch between insert and overwrite mode
Shift+Ctrl+Y Change selection to all lower case
Shift+Ctrl+X Change selection to all upper case

minus6. Search and Replace

Ctrl+F Open find and replace dialog
Ctrl+K/Ctrl+Shift+K Find previous / find next occurrence of search term (close find window first)
Ctrl+H Search Workspace (Java Search, Task Search, and File Search)

minus7. Indentions and Comments

Tab/Shift+Tab Increase / decrease indent of selected text
Ctrl+I Correct indention of selected text or of current line
Ctrl+Shift+F Autoformat all code in Editor using code formatter
Ctrl+/ Comment / uncomment line or selection ( adds ‘//’ )
Ctrl+Shift+/ Add Block Comment around selection ( adds ‘/… */’ )
Ctrl+Shift+\ Remove Block Comment
Alt+Shift+J Add Element Comment ( adds ‘/** … */’)

minus8. Editing Source Code

Ctrl+Space Opens Content Assist (e.g. show available methods or field names)
Ctrl+1 Open Quick Fix and Quick Assist
Alt+/ Propose word completion (after typing at least one letter). Repeatedly press alt+/ until reaching correct name
Ctrl+Shift+Insert Deactivate or activate Smart Insert Mode (automatic indention, automatic brackets, etc.)

minus9. Code Information

Ctrl+O Show code outline / structure
F2 Open class, method, or variable information (tooltip text)
F3 Open Declaration: Jump to Declaration of selected class, method, or parameter
F4 Open Type Hierarchy window for selected item
Ctrl+T Show / open Quick Type Hierarchy for selected item
Ctrl+Shift+T Open Type in Hierarchy
Ctrl+Alt+H Open Call Hierarchy
Ctrl+Shift+U Find occurrences of expression in current file
Ctrl+move over method Open Declaration or Implementation

minus10. Refactoring

Alt+Shift+R Rename selected element and all references
Alt+Shift+V Move selected element to other class or file (With complete method or class selected)
Alt+Shift+C Change method signature (with method name selected)
Alt+Shift+M Extract selection to method
Alt+Shift+L Extract local variable: Create and assigns a variable from a selected expression
Alt+Shift+I Inline selected local variables, methods, or constants if possible (replaces variable with its declarations/ assignment and puts it directly into the statements)

minus11. Run and Debug

Ctrl+F11 Save and launch application (run)
F11 Debug
F5 Step Into function
F6 Next step (line by line)
F7 Step out
F8 Skip to next Breakpoint

minus12. The Rest

Ctrl+F7/Ctrl+Shift+F7 Switch forward / backward between views (panels). Useful for switching back and forth between Package Explorer and Editor.
Ctrl+F8/Ctrl+Shift+F8 Switch forward / backward between perspectives
Ctrl+P Print
F1 Open Eclipse Help
Shift+F10 Show Context Menu right click with mouse

NSSM – Windows Services

NSSM
We always need to add windows services in our deployments(client site and in office). “NSSM” is the easiest way to add windows services.

Download the NSSM file to your hard disk (no need to install / use this link to download – nssm-2.24).

Open command promt and go to the NSSM folder using “cd” command.

Use the command “nssm install” to open the nssm window.

Now you can add the executable and create windows services.

install_application

For More information – http://nssm.cc/

Install JAVA in Linux

download .bin file from oracle site.


chmod a+x [bin file name].bin

./[bin file name].bin

mv jdk1.6.0_30 java-6-oracle

sudo mkdir /usr/lib/jvm

sudo mv java-6-oracle /usr/lib/jvm

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/java-6-oracle/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/java-6-oracle/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/java-6-oracle/bin/javaws" 1

sudo chmod a+x /usr/bin/java
sudo chmod a+x /usr/bin/javac
sudo chmod a+x /usr/bin/javaws
sudo chown -R java6admin:java6admin /usr/lib/jvm/java-6-oracle

Hibernate Performance Configuration Tips

Practical

We can check the hibernate behavior via different methods,

  1. Profiler on DAO/Session.query() methods.
  2. VisualVM for heap usage.
  3. Hibernate JMX.
  4. RDBMS monitoring tools.

Analyzing Hibernate

  1. Using properties like show_sql and format_sql.
  2. Log4J configurations,
    1. hibernate.SQL->DEBUG
    2. hibernate.type->TRACE
  3. Use P6Spy/Log4JDBC on JDBC connection.

Large Collections

  1. Using @BatchSize(size=100) on entities and attributes.
  2. Use fetch join
  3. Extra lazy collection fetching
    1. @OneToMany(fetch=FetchType.Lazy)
    2. @LazyCollection(LazyCollectionOption.EXTRA)
  4. Use “hibernate.jdbc.batch_size” / “hibernate.order_inserts” / “hibernate.order_updates”
  5. Use StatelessSession
    1. StatelessSession stateless = session.getSessionFactory().openStatelessSession();

Query Hints

  1. Speed up read-only service calls
    • Query query = session.createQuery(“——-”);
    • setReadOnly(true);
  2. Query Set Hints
    • setHint(“org.hibernate.fetchSize”, 50);
    • setHint(“org.hibernate.cacheable”, true);
  3. Never use second level cache.

Large Updates

  1. Use VERSION keyword for optimistic concurrency.
  2. Entities are not always necessary,
    1. createQuery(“UPDATE User SET active=false”).executeUpdate();
  3. Consider use of stored procedures.

General

  • Data and schema outlive your application
  • Good indexes makes huge differences
  • Stored procedures are not evil
  • Do not let hibernate to dictate your schema

Create JSON Response in Spring MVC Project

If you finding trouble making json response in your spring project, Please find below simple steps to do that,

Step 01

Add below code snippets in your pom.xml file
<!-- Jackson JSON Mapper -->
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 <version>1.9.13</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.4.1</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.4.1.1</version>
 </dependency>

Step 02

Add below code in you spring configuration xml file

 
<!-- Configure to plugin JSON as request and response in method handler --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 
<property name="messageConverters"> 
<list> 
<ref bean="jsonMessageConverter"/> 
</list> 
</property> 
</bean> 

<!-- Configure bean to convert JSON to POJO and vice versa --> 
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> 

Step 03:

Below is the simple example of a controller methode which convert SystemUser Java entity class map returns as a json.

@RequestMapping(value="getSystemUser", method=RequestMethod.GET)
 public @ResponseBody Map<String, Object> getSystemUser(@RequestParam("userId") long userId, HttpServletRequest request){
 SystemUser systemUser = systemUserService.getSystemUser(userId);
 return systemUser.toMap();
 }

If you want to refer my SystemUser object , please find it below.

package com.isd.sappu.savari.domains;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name="users")
public class SystemUser implements Serializable{

 private static final long serialVersionUID = 5489679679570043539L;

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private long userId;
 
 private String username;
 
 private String password;
 
 private String firstName;
 
 private String lastName;
 
 private String address;
 
 private String profilePic;
 
 private Date dateOfBirth;
 
 private String mobileNo;
 
 private String workNo;
 
 private String homeNo;
 
 private double latitude;
 
 private double longtitude;
 
 private int accuracy;
 
 private int activeStatus;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Favorite> favoriteList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Comment> commentList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Rating> ratingList;
 
 @OneToMany(mappedBy="sender")
 @Cascade(CascadeType.ALL)
 private List<Message> messageSentList;
 
 @OneToMany(mappedBy="receiver")
 @Cascade(CascadeType.ALL)
 private List<Message> messageRecievedList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Product> productList;

 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<SystemUserRole> systemUserRoleList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<SearchRequest> searchRequestList;
 
 
 
 public long getUserId() {
 return userId;
 }

 public void setUserId(long userId) {
 this.userId = userId;
 }

 public String getUsername() {
 return username;
 }

 public void setUsername(String username) {
 this.username = username;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastName() {
 return lastName;
 }

 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 public String getAddress() {
 return address;
 }

 public void setAddress(String address) {
 this.address = address;
 }

 public String getProfilePic() {
 return profilePic;
 }

 public void setProfilePic(String profilePic) {
 this.profilePic = profilePic;
 }

 public Date getDateOfBirth() {
 return dateOfBirth;
 }

 public void setDateOfBirth(Date dateOfBirth) {
 this.dateOfBirth = dateOfBirth;
 }

 public String getMobileNo() {
 return mobileNo;
 }

 public void setMobileNo(String mobileNo) {
 this.mobileNo = mobileNo;
 }

 public String getWorkNo() {
 return workNo;
 }

 public void setWorkNo(String workNo) {
 this.workNo = workNo;
 }

 public String getHomeNo() {
 return homeNo;
 }

 public void setHomeNo(String homeNo) {
 this.homeNo = homeNo;
 }

 public List<Favorite> getFavoriteList() {
 return favoriteList;
 }

 public void setFavoriteList(List<Favorite> favoriteList) {
 this.favoriteList = favoriteList;
 }

 public List<Comment> getCommentList() {
 return commentList;
 }

 public void setCommentList(List<Comment> commentList) {
 this.commentList = commentList;
 }

 public List<Rating> getRatingList() {
 return ratingList;
 }

 public void setRatingList(List<Rating> ratingList) {
 this.ratingList = ratingList;
 }

 public List<Message> getMessageSentList() {
 return messageSentList;
 }

 public void setMessageSentList(List<Message> messageSentList) {
 this.messageSentList = messageSentList;
 }

 public List<Message> getMessageRecievedList() {
 return messageRecievedList;
 }

 public void setMessageRecievedList(List<Message> messageRecievedList) {
 this.messageRecievedList = messageRecievedList;
 }

 public List<Product> getProductList() {
 return productList;
 }

 public void setProductList(List<Product> productList) {
 this.productList = productList;
 }

 public List<SystemUserRole> getSystemUserRoleList() {
 return systemUserRoleList;
 }

 public void setSystemUserRoleList(List<SystemUserRole> systemUserRoleList) {
 this.systemUserRoleList = systemUserRoleList;
 }

 public int getActiveStatus() {
 return activeStatus;
 }

 public void setActiveStatus(int activeStatus) {
 this.activeStatus = activeStatus;
 }

 public List<SearchRequest> getSearchRequestList() {
 return searchRequestList;
 }

 public void setSearchRequestList(List<SearchRequest> searchRequestList) {
 this.searchRequestList = searchRequestList;
 }

 public double getLatitude() {
 return latitude;
 }

 public void setLatitude(double latitude) {
 this.latitude = latitude;
 }

 public double getLongtitude() {
 return longtitude;
 }

 public void setLongtitude(double longtitude) {
 this.longtitude = longtitude;
 }

 public int getAccuracy() {
 return accuracy;
 }

 public void setAccuracy(int accuracy) {
 this.accuracy = accuracy;
 }
 
 public Map<String, Object> toMap() {
 Map<String, Object> map = new HashMap<String, Object>();
 map.put("userId", userId);
 map.put("username", username);
 map.put("address", address);
 map.put("mobileNo", mobileNo);
 map.put("latitude", latitude);
 map.put("longtitude", longtitude);
 map.put("accuracy", accuracy);
 map.put("activeStatus", activeStatus);
 return map;
 }
 
}

That’s all, Enjoy your json experience.

Thank you…!!!

Enable File uploading in your Spring application

If you are struggling make file uploading in your spring application, most of the time this may be the cause. We always forgot small things when we configure and setup our project.

Add below code in your application context xml file. This will do the magic you want



<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />


Now you can use CommonsMultipartFile in your controller just like below,


@RequestMapping(value="userprofile", method=RequestMethod.POST)
public String getUserProfile(@RequestParam("inputProfilePic") @Null CommonsMultipartFile profilePicture, HttpServletRequest request){

return "profilepage";

}

That’s all, Enjoy file uploading.

Thanks

Retrieve Geo Location from Your browser

If you web application needs location of the user this is the code you want. But remember this is HTML 5 and won’t work with your old web browsers.

In most cases this gives the correct location of the user depends on the device capabilities. If user uses a mobile device GPS enabled this gives the exact location, but if it’s not it uses ip addresses and other signalling details to detect the location which not be very accurate.



<script type="text/javascript">

function success(pos) {
var crd = pos.coords;

console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
};

function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};

var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};

navigator.geolocation.getCurrentPosition(success, error, options);

</script>


Any way that’s all folks, have fun with you location enabled web applications.

Thanks