Leaderboard1

Leaderboard2

Friday, May 30, 2014

How to use shutdown command under Ubuntu Linux

I this post i have listed out some commands to shutdown Ubuntu Linux using a commnd.

Open your terminal with CTRL+ALT+T and do these following commands

Shutdown command

shutdown arranges for the system to be brought down in a safe way. All logged-in users are notified that the system is going down and, within the last five minutes of TIME, new logins are prevented. The shutdown utility provides an automated shutdown procedure for supersers to nicely notify users when the system is shutting down, saving them from system administrators, hackers, and gurus, who would otherwise not bother with such niceties.

How do I use shutdown command?

The shutdown command can be used to turn off or reboot a computer. Type the command as follows to shutdown server / computer immediately:
$ sudo shutdown -h nowOR
$ sudo shutdown -h 0

How do I shutdown compute at specific time?

To shutdown computer at 6:45pm, enter:
$ sudo shutdown -h 18:45 "Server is going down for maintenance"At 6:30pm message will go out to all user and 6:45 system will shutdown.
Please note that you can also use halt or poweroff or reboot command for stopping and restarting the system:
$ sudo haltOR
$ sudo poweroff

How do I reboot computer?

Simply use reboot command:
$ sudo rebootOR
$ sudo shutdown -r 0
Post Comments !
Share this article..

How To Generate Hibernate Mapping Files & Annotation With Hibernate Tools In Eclipse (Reverse Engineering)

In this article, we show you how to use Hibernate / JBoss Tools to generate Hibernate mapping files (hbm) and annotation code from database automatically.

Tools required:

Eclipse v3.6 (Helios)
JBoss / Hibernate Tools v3.2
Oracle 11g
JDK 1.6

1. Open Hibernate Perspective

Open your “Hibernate Perspective“. In Eclipse IDE, select “Windows” >> “Open Perspective” >> “Others…” , choose “Hibernate“.




Note:
 As i have used Maven to build project structure, so Maven already created 3 package for me:

src/test/java
src/main/java
src/main/resources

If you haven't used Maven, then you can create these folders manually.
"src/main/resources" folder is required mostly for keeping hibernate file or other files which help in project configuration.


2. New Hibernate Configuration

In Hibernate Perspective, right click and select “Add Configuration”

In “Edit Configuration” dialog box,

In “Project” box, click on the “Browse..” button to select your project.
In “Database Connection” box, click “New..” button to create your database settings.
In “Configuration File” box, click “Setup” button to create a new or use existing “Hibernate configuration file”, hibernate.cfg.xml.






















Select your project. Click on new for creating database connection, You need mysql-coonector-java-5.1.30.jar for this, so download it from mysql website.






















Test Connection.. and click finish.

Now creating configurtion file, click on setup











































Click on Apply and OK..


3. Hibernate Code Generation

Now, you are ready to generate the Hibernate mapping files and annotation codes.

- In “Hibernate Perspective”, click "Run As.." - > “Hibernate code generation” icon (see below figure) and select “Hibernate Code Generation Configuration”.



- Create a new configuration, select your “console configuration” (configured in step 2), puts your “Output directory” and checked option “Reverse engineer from JDBC Connection“.





















- In “Exporter” tab, select what you want to generate, Model , mapping file (hbm) , DAO, annotation code and etc.



















In my database 3 tables were present, here 3 hibernate mapping have been created. So finally we have created Hibernate Mapping files by using Eclipse reverse engineering.

Please post comments !

Follow Me on Pinterest

Wednesday, May 28, 2014

Difference between String s = "java" and String s = new String("java")

We all known the equals() check the content of the string , but '= =' checks the object reference.

Strings are immutable and final in Java
Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method,  It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality. Now if you are puzzled why String is immutable or final in Java.

Strings are maintained in String Pool
Advanced Java String tutorial and example programmers As I Said earlier String is special class in Java and all String literal e.g. "abc"  (anything which is inside double quotes are String literal in Java) are maintained in a separate String pool, special memory location inside Java memory, more precisely inside PermGen Space. Any time you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator.


String str = "John"; //1st String object
String str1 = "John"; //same Sring object assigned
String str2 = new String("John") //forcing JVM to create a new String object

//this will return true
if(str == str1){
System.out.println("both str and str1 are pointing to same string object");
}

//this will return false
if(str == str2){
System.out.println("both str and str2 are pointing to different string objects");
}

Please post comments !

Why String is Immutable in Java ?

As Java developer, we all know that String is an immutable class. But very few knows that why String is immutable. As String is used vastly in Java application, as parameter in network connection, database url, serialization etc, so for security reasons, memory saving, it's made immutable.

1. String Pool

String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

The following code will create only one string object in the heap.

String string1 = "abcd";
String string2 = "abcd";

2. Cashing String hash code


Being immutable, String provides a constant hashCode. As String is widely used as a key in HashMap, so being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes. That means, there is no need to calculate hashcode every time it is used. This is more efficient.

3. Security

String us used as a parameter in many places, database connections, file opening etc, so mutable Strings cam create huge problems. To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded.

Please post comments !

Importance of equals() and hashCode() methods in Java objects

equals() and hashCode() methods are required when you insert objects in s collection. Both play a very important role for Java objects. Both methods are defined in Object class. As Object class is the parent of all classes by default, so we override these methods in our objects and give our own definitions. 

equals()

equals() is required to compare the properties of one object with other. equals() method uses identity operator(= =)to determine whether object are equal. In equals()we compare only those properties on the basis of them objects are compared. For primitive data types like int, double identity operator is sufficient but in case on objects we need more functionality for comparing. For example:

class Employee{
private String name;
private int age;
public Employee(String name, int age){
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj){
if(obj != null && obj instanceof Employee){
if(((Employee) obj).name.equals(this.name) && ((Employee) obj).age == this.age){
return true;
} else
return false;
} else
return false;
}
}

Comparing Employee class objects.

Employee e1 = new Employee("john", 25);
Employee e2 = new Employee("Dev", 26);
System.out.println(e1.equals(e2)); // false


hashcode()

hashCode() method is used when object are inserted in HashMap, HashTable, HashSet. When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object. 

The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.

Here are two rules that are good to know about implementing the hashCode() method in your own classes, if the hashtables in the Java Collections API are to work correctly:

  1. If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
  2. If object1 and object2 have the same hash code, they do NOT have to be equal too.

In shorter words:
  1. If equal, then same hash codes too.
  2. Same hash codes no guarantee of being equal.

class Employee{
private String name;
private int age;
public Employee(String name, int age){
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj){
if(obj != null && obj instanceof Employee){
if(((Employee) obj).name.equals(this.name) && ((Employee) obj).age == this.age){
return true;
} else
return false;
} else
return false;
}
@Override
public int hashCode(){
return this.name.hashCode() * this.age; // calculating hashCode using Employee properties   
}
}


Please post comments !

Saturday, May 24, 2014

How To Install Hibernate / JBoss Tools In Eclipse IDE

As creating Hibernate mapping files manually can causes some issues so it's better to use Hibernate/Jboss tools for generating hibernate mapping files automatically.

1. Download Hibernate/JBoss tool

Go to Eclipse: help->Intall New Software, and copy this url:

For Eclipse Indigo





2. Restart Eclipse

Restart Eclipse to take effect.



Please like us !

How to Take Screenshot in Ubuntu Linux

In this post i'll show you how to take ScreenShot in Ubuntu Linux.

1. Use Print Screen key

Use PrintScreen key to take ScreenShot of whole desktop or Alt+PrintScreen to take ScreenShot of current active window.

2. Use gnome-screenshot

go to Applications and find "Screenshot", it's provided by Ubuntu.



click "Take ScreenShot" key and save it to desktop. Open image with image editor and crop it if required.

3. Use terminal to take ScreenShot

For entire screen screenshot type:

  gnome-screenshot

For current active windows screenshot type:

  gnome-screenshot -w

4. Take Screenshot after some delay


  $ gnome-screenshot -w -d 2

5. Capture a particular area

This is very easy way to capture a particular area by using terminal.

  $ gnome-screenshot -a


Please like this post !


Wednesday, May 21, 2014

Create a Java Project with Maven

Tools used:

  1. Maven 3.0.5
  2. Eclipse 4.2
  3. JDK 6

Steps:

1. Create a Project from Maven Template

Go to a folder where you want to create Maven project, and run this command on command prompt.

mvn archetype:generate -DgroupId=com.akash -DartifactId=MavenTest -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

This will download artifacts, dependencies and create a project structure.


Project Structure:


MavenTest

   |-src

   |---main

   |-----java

   |-------com

   |---------akash

   |-----------App.java

   |---test

   |-----java

   |-------com

   |---------akash

   |-----------AppTest.java

   |-pom.xml

Note: Keep source code in folder /src/main/java/project-package, all unit test code puts in /src/test/java/project-package.

Now a POM.xml file has been generated.

What is POM?

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this is the build directory, which is target; the source directory, which issrc/main/java; the test source directory, which is src/main/test; and so on.

Update POM.xml



















3. Make Maven project compatible with Eclipse

Run this commandmvn eclipse:eclipse

4. Update AppTest.java


package com.akash;

import org.junit.Assert;
import org.junit.Test;

public class AppTest {

@Test
public void testLengthOfTheUniqueKey() {

App obj = new App();

}

}



5. Compile Project and create jar

run mvn package on cmd

It will compile Maven project and create a jar.

Create A Web Application Project With Maven

In this post we will learn to create Web Application using Maven. If Maven is not configured in your system, please refer this link; Configure Maven on Windows

Tools required:
  1. Eclipse IDE for Java EE Developers
  2. M2E plugin for Eclipse
  3. Maven
Steps:

1. Install Maven eclipse plugin

http://download.eclipse.org/technology/m2e/releases

You can install Maven plugin for Eclipse via update site, simply copy the above update site link address and paste it into Eclipse’s “Update” or “Install New Software” manager as explained below.


Restart Eclipse.

2. Create Dynamic Web project in eclipse

click next.

--> Create the following directory structure (please pay attention to the directory structure. It’s an important detail in the creation of Dynamic Web Project):


click next, and generate deployment descriptor, web.xml 

Press Finish.

Directory structure:


3. Convert to Maven project

Now right click on project, go to configure and click on "convert to Maven project".


  • Select “Packaging” as a WAR;
  • Click on the “Finish” button;
  • After that, pom.xml will appear in the project’s structure;
  • Move all stuff from the WebContent folder to src/main/webapp;
  • WebContent folder can be deleted after that.
4. Configuration for Eclipse
  • Go to projects root folder in cmd and run this: mvn eclipse:eclipse -Dwtpversion=2.0
  • This command will generate a configuration for eclipse (.classpath, .project, etc.).
  • Expand src > main and make a right click on the webapp folder: Build Path > Use as Source Folder (This point is actual only if src/main/webapp disappeared from the source folders).
Share this !

How To Install Maven On Windows

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, and dependency management.

Steps:

1. Download Apache Maven

Download Apache Maven from here. Extract zip contents. Before configuring Maven make sure Java_Home( jdk path) must be set in Environment variables.

2. Add MAVEN_HOME

As you run Maven from command prompt, so it's path should be present in Environment variables.

Set MAVEN_HOME = E:\apache-maven-3.2.1 , make sure path should be the extracted maven folder.

3. Add Path

Add Maven bin path so that you can run it from anywhere.











4. Verify

Run this command on command prompt:

mvn -version

You will get following:

Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9; 2014-02-14T23:07:52+05:30)
Maven home: D:\apache-maven-3.2.1\bin\..
Java version: 1.7.0_40, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_40\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

RESTful Web Service with Java: Tutorial

RESTful Web Services

This post will demonstrate how to create a RESTful Web Service and client using Jersey framework which extends JAX-RS API.

REST fundamentals
  • Everything in REST is considered as a resource.
  • Every resource is identified by an URI.
  • Uses uniform interfaces. Resources are handled using POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
  • Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
  • Communications are done via representations. E.g. XML, JSON.

Download Jersey zip bundle from here.

You will need these jars:







  • asm-3.1.jar
  • jersey-client-1.17.1.jar
  • jersey-core-1.17.1.jar
  • jersey-server-1.17.1.jar
  • jersey-servlet-1.17.1.jar
  • jsr311-api-1.1.1.jar

  • Now create a new class UserInfo.java.



    package com.restws;

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;

    @Path("UserInfoService")
    public class UserInfo {

     @GET
     @Path("/name/{i}")
     @Produces(MediaType.TEXT_XML)
     public String userName(@PathParam("i") String i){
      
      String name = i;
      return "" + "" + name + "" + "";
      
     }

     @GET
     @Path("/age/{j}")
     @Produces(MediaType.TEXT_XML)
     public String userAge(@PathParam("j") int j){
      
      int age = j;
      return "" + "" + age + "" + "";
      
     }

    Now create web.xml file in WEb-INF folder.

    }
      To run the project, right click on it and click on run as ->run on server.
    http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Akash

    Now create MyClient.java:

    package com.restclient;

    import javax.ws.rs.core.MediaType;
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;
    import com.sun.jersey.api.client.config.ClientConfig;
    import com.sun.jersey.api.client.config.DefaultClientConfig;

    public class MyClient {

      public static final String BaseURI = "http://localhost:8080/RESTfulWS";
     public static final String PATH_NAME = "/MyService/name/";
     public static final String PATH_AGE = "/MyService/age/";

      public static void main(String... args) {

       String name = "Akash";
      int age = 26;

       ClientConfig config = new DefaultClientConfig();
      Client client = Client.create(config);
      WebResource resource = client.resource(BaseURI);

       WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
      System.out.println("Client Response \n"
        + getClientResponse(nameResource));
      System.out.println("Response \n" + getResponse(nameResource) + "\n\n");

       WebResource ageResource = resource.path("rest").path(PATH_AGE + age);
      System.out.println("Client Response \n"
        + getClientResponse(ageResource));
      System.out.println("Response \n" + getResponse(ageResource));
     }

      /* Returns client response */
     private static String getClientResponse(WebResource resource) {
      return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
        .toString();
     }

      /* Returns the response as XML */
     private static String getResponse(WebResource resource) {
      return resource.accept(MediaType.TEXT_XML).get(String.class);
     }
    }


    Run MyClient.java as Java applicaiton, you will get following output:

    Client Response
    GET http://localhost:8080/RESTfulWS/rest/MyService/name/Akash returned a response status of 200 OK
    Response
    Akash

    Client Response
    GET http://localhost:8080/RESTfulWS/rest/MyService/age/26 returned a response status of 200 OK
    Response
    26