Welcome to my blog, hope you enjoy reading
RSS
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, 1 November 2014

How to Install Oracle Java 8 In Ubuntu

Step 1: Install Java 8 (JDK 8)


Add the webupd8team java PPA repository in our system and install Oracle java8 using following set of commands.

$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer


Step 2: Verify JAVA Version


After successfully installing oracle java using above step verify installed version using following command.

$ java -version

java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

Step 3: Setup JAVA Environment


Webupd8team is providing a package to set environment variables, Install this package using following command.

$ sudo apt-get install oracle-java8-set-default
Share

How To Install Java on Ubuntu

Installing default JRE/JDK

This is the recommended and easiest option. This will install OpenJDK 6 on Ubuntu 12.04 and earlier and on 12.10+ it will install OpenJDK 7.

Installing Java with apt-get is easy. First, update the package index:
sudo apt-get update

Then, check if Java is not already installed:
java -version

If it returns "The program java can be found in the following packages", Java hasn't been installed yet, so execute the following command:
sudo apt-get install default-jre

This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), which is usually needed to compile Java applications (for example Apache Ant, Apache Maven, Eclipse and IntelliJ IDEA execute the following command:
sudo apt-get install default-jdk

That is everything that is needed to install Java.
All other steps are optional and must only be executed when needed.

Installing OpenJDK 7 (optional)

To install OpenJDK 7, execute the following command:
sudo apt-get install openjdk-7-jre

This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), execute the following command:
sudo apt-get install openjdk-7-jdk

Installing Oracle JDK (optional)
The Oracle JDK is the official JDK; however, it is no longer provided by Oracle as a default installation for Ubuntu.

You can still install it using apt-get. To install any version, first execute the following commands:
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

Then, depending on the version you want to install, execute one of the following commands:

Oracle JDK 6
This is an old version but still in use.
sudo apt-get install oracle-java6-installer

Oracle JDK 7
This is the latest stable version.
sudo apt-get install oracle-java7-installer

Oracle JDK 8
This is a developer preview, the general release is scheduled for March 2014. This external article about Java 8 may help you to understand what it's all about.
sudo apt-get install oracle-java8-installer

Managing Java (optional)

When there are multiple Java installations on your Droplet, the Java version to use as default can be chosen. To do this, execute the following command:
sudo update-alternatives --config java

It will usually return something like this if you have 2 installations (if you have more, it will of course return more):

There are 2 choices for the alternative java (providing /usr/bin/java).

Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-7-oracle/jre/bin/java          1062      auto mode
  1            /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java   1061      manual mode
  2            /usr/lib/jvm/java-7-oracle/jre/bin/java          1062      manual mode

Press enter to keep the current choice[*], or type selection number:
You can now choose the number to use as default. This can also be done for the Java compiler (javac):
sudo update-alternatives --config javac

It is the same selection screen as the previous command and should be used in the same way. This command can be executed for all other commands which have different installations. In Java, this includes but is not limited to: keytool, javadoc and jarsigner.

Setting the "JAVA_HOME" environment variable
To set the JAVA_HOME environment variable, which is needed for some programs, first find out the path of your Java installation:
sudo update-alternatives --config java

It returns something like:

There are 2 choices for the alternative java (providing /usr/bin/java).

Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-7-oracle/jre/bin/java          1062      auto mode
  1            /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java   1061      manual mode
  2            /usr/lib/jvm/java-7-oracle/jre/bin/java          1062      manual mode

Press enter to keep the current choice[*], or type selection number:
The path of the installation is for each:

/usr/lib/jvm/java-7-oracle

/usr/lib/jvm/java-6-openjdk-amd64

/usr/lib/jvm/java-7-oracle

Copy the path from your preferred installation and then edit the file /etc/environment:

sudo nano /etc/environment
In this file, add the following line (replacing YOUR_PATH by the just copied path):

JAVA_HOME="YOUR_PATH"
That should be enough to set the environment variable. Now reload this file:

source /etc/environment
Test it by executing:

echo $JAVA_HOME
If it returns the just set path, the environment variable has been set successfully. If it doesn't, please make sure you followed all steps correctly.
Share

Tuesday, 9 September 2014

Switching between installed Java versions in ubuntu


Switching between installed Java versions can be accomplished using the update alternatives command.

  •     To get a list of your installed Java platforms, run the following command from the terminal:

    sudo update-alternatives --config java
 
  This will give you a list output similar to this:
    There are 2 choices for the alternative java (providing /usr/bin/java).
       Selection    Path                                           Priority   Status
      ------------------------------------------------------------
      0            /usr/lib/jvm/java-6-oracle/jre/bin/java         1070      auto mode
      1            /usr/lib/jvm/java-7-openjdk-i386/jre/bin/java   1051      manual mode
    * 2            /usr/lib/jvm/java-6-openjdk-i386/jre/bin/java   1069      manual mode
    Press enter to keep the current choice[*], or type selection number:

In this case, the Open JDK 6 version is running. To switch to the Open JDK version 7, you would select option 1 at the prompt and press the Enter key.

You will now be running the OpenJDK 7 version. No other changes will be needed to switch your Java versions.
Share

Tuesday, 20 May 2014

replace() vs replaceAll()

Both replace() and replaceAll() replaces all the occurrence found. However, there is difference in the type of arguments they accept.

Share

Thursday, 15 May 2014

What is the size of ” null ” Operator in Java ?

When you write

String st1 = null;
You create a reference “str1″ to an object that still does not exist in the heap, but when you type :

Share

Monday, 24 February 2014

Project facet Java version 1.7 is not supported

Project facet Java version 1.7 is not supported 

When i update my java I found the issue "Project facet Java version 1.7 is not supported" To resolve this issue follow the steps.
  1. Go to Ecllipse , right click on your project folder
  2. select the properties
  3. now select Project Facets ,here you will see java, click on the version and change the higher version to lower or as per your requirement .

Share

Saturday, 1 February 2014

How to swap keys and values in a Map

How to swap keys and values in a Map 



package com.javanotes2all.java.collectionfw;

import java.util.HashMap;
import java.util.Map;

public class SwapKeysAndValuesinMap {

 public static void main(String[] args) {
  HashMap map=new HashMap();
  map.put("1", "a");
  map.put("2", "b");
  map.put("3", "c");
  map.put("4", "d");
  map.put("5", "e");
  map.put("6", "f");
  map.put("7", "g");
  System.out.println("before swap"+map);
  map=reverse(map);
  System.out.println("after swap"+map);
 }
 public static  HashMap reverse(Map map) {
     HashMap rev = new HashMap();
     for(Map.Entry entry : map.entrySet())
         rev.put(entry.getValue(), entry.getKey());
     return rev;
 }
}


Share

Wednesday, 2 October 2013

Get all Request Parameters in Servlet

Get all Request Parameters in Servlet


  • Use HttpServletRequest.getParameterNames to get an Enumeration of parameter names.
  • Use HttpServletRequest.getParameterValues(paramName) to get the parameters values.

package com.javanotes2all.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetAllRequestParametersInServlet extends HttpServlet {

private static final long serialVersionUID = -2128122335811219481L;

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
handleRequest(req, res);
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
handleRequest(req, res);
}

public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {

PrintWriter out = res.getWriter();
res.setContentType("text/plain");

Enumeration<String> parameterNames = req.getParameterNames();

while (parameterNames.hasMoreElements()) {

String paramName = parameterNames.nextElement();
out.write(paramName);
out.write("n");

String[] paramValues = req.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++) {
String paramValue = paramValues[i];
out.write("t" + paramValue);
out.write("n");
}

}

out.close();

}

}
Share

Thursday, 19 September 2013

Setting the PATH and CLASSPATH on Windows

For VERSION 1.5.0_02 of Java (new version)

 1.      Click on START (lower left)

2.      Under "Settings" click on "Control Panel"

3.      Switch to "classic view" (upper left) -- not "category view"

4.      Click on the "System" icon.

5.      Click on the "Advanced" tab.

6.      Click on the "Environment Variables" button (bottom).

7.      Highlight "PATH" (in the top window) and click the "edit" button.

NOTE:  DON'T EDIT OR MODIFY AND OF THE "SYSTEM VARIABLES" -- you could render your entire computer unusable! --

8.      Edit the "PATH" so it begins C:\Program Files\Java\jdk1.5.0_02\bin; (note: if you install Java into a different directory, you may need to change the directory from that listed above)

9.  After you have finished editing the PATH, click "OK".  You are done setting your PATH.  Now you have to create a new variable, called your CLASSPATH.

10.  Click on the "NEW" button below the top window.

11.  Under 'variable name' type CLASSPATH

12.  Under 'variable value' type . (yes, type a single period).

13.  Click OK.

14.  EXIT the control panel.

15.  Restart your computer.

16.  Test your installation by opening up a DOS window and verifying that both the commands "java" and "javac" are recognized.
Share

Monday, 26 August 2013

Data Types in java

Data Types in java


Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java:
  • Primitive Data Types
  • Reference/Object Data Types
Share

Monday, 29 July 2013

Short form for Java If statement

Short form for Java If statement

problem:
if (city.getName() != null) {
    name = city.getName();
} else {
    name="N/A";
}

Solution:
name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());
Share

Friday, 19 July 2013

How to call URL from JAVA

How to call URL from JAVA



package com.javanotes2all.java.reqRes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class CallUrl 
{
  public static void main(String[] args) 
  {
         URL url;
         try 
         {
             // get URL content
             String a="http://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html";
             url = new URL(a);
             URLConnection conn = url.openConnection();
             // open the stream and put it into BufferedReader
             BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
             String inputLine;
             while ((inputLine = br.readLine()) != null) {
                     System.out.println(inputLine);
             }
             br.close();

             System.out.println("Done");

         } catch (MalformedURLException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }

     }

}


Share

Wednesday, 17 July 2013

case sensitive and insensitive condition in String replace function

case sensitive and insensitive condition in String replace function

            String target = "FooBar";
   target = target.replaceAll("foo", "");
   System.out.println(target); 
In java the above statements output is 'FooBar'
Share

Monday, 8 July 2013

Java beep sound example

Java beep sound example

There are different ways to generate a beep sound in java. The general basic way to generate is to use java.awt.Toolkit class which has a default method to generate the beep sound. The other implementation is also shown below on how to generate beep sound in java.
Share

Tuesday, 25 June 2013

create the executable jar file using java

create the executable jar file using java

To create the executable jar file using java do following steps
  1. create the swing based UI in java and generate the .class file 
  2. after creating the mainfast file your choice (.txt ) and you will give the java class name like           Main-Class: TestApp  
  3. the above step2 ,you have write the Main-Class: after given one space and press two times enter button in keyboard
  4. C:/>jar cmf test.txt myjarfilename.jar *
  5. you have generate the executable jar file
    1. for ubuntu os you can give the permistions
    2. chmod +x myjarfilename.jar.

Creating an Executable Jar Files in Eclipse

  1. Highlight the appropriate file/project
  2. File -> Export
  3.  Choose "Runnable JAR file" -> Next
  4. Make sure the right project is selected under the "Launch Configuration" dropdown and select "Package required libraries into generated JAR file" under the "Library Handling" section and make sure it's going to the correct export destination. 
  5. click Finish

Now you should have the jar file in the destination you told it to export to. Double click it and it should run. 
**HOWEVER** If this is a command line program it will not run. To run a command line program, after doing the above steps, open the command prompt, cd to the correct directory, and execute it by typing
  java -jar name_of_file.jar 

Share

Monday, 24 June 2013

Control your keyboard with Java

Control your keyboard with Java

You may control your keyboard using this simple program.Please dont run this program directly, its just for reference

import java.awt.Robot; 
import java.awt.event.InputEvent; 
import java.awt.event.KeyEvent; 

/* 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
/** 
 * 
 * @author Anurag 
 */ 
public class ControlKeyboard { 

    public static void main(String args[]) { 
        new ControlKeyboard().control_keyboard(); 
    } 

    public void control_keyboard() { 
        try { 
            Robot robot = new Robot(); 

            //Perform ALT+TAB which will switch your window 
            robot.keyPress(KeyEvent.VK_ALT); 
            robot.keyPress(KeyEvent.VK_TAB); 

            Thread.sleep(100); 

            robot.keyRelease(KeyEvent.VK_ALT); 
            robot.keyRelease(KeyEvent.VK_TAB); 

            //Press Key A 
            robot.keyPress(KeyEvent.VK_A); 
            Thread.sleep(100); 
            robot.keyRelease(KeyEvent.VK_A); 
            //Similarly to press key Z use  
            robot.keyPress(KeyEvent.VK_Z); 
            Thread.sleep(100); 
            robot.keyRelease(KeyEvent.VK_Z); 

            //Press ALT key 
            robot.keyPress(KeyEvent.VK_ALT); 
            Thread.sleep(100); 
            robot.keyRelease(KeyEvent.VK_ALT); 

            //Press Control Key 
            robot.keyPress(KeyEvent.VK_CONTROL); 
            Thread.sleep(100); 
            robot.keyRelease(KeyEvent.VK_CONTROL); 




        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
} 

Explaination :

First we make an object of Robot class.

If we want to press a keyboard key then we use the keyPress and keyRelease method.

Always make sure there is a delay of some small seconds before key press and key release events

Suppose if we want to click A then we use KeyEvent.VK_A, for B we use VK_B ...., for Z VK_Z.

To perform Control key use VK_CONTROL, ALT key we use VK_ALT and likewise there are other combinations.

To perform multiple key event we perform the key press for both keys and after that give a small delay. After that we perform the release operation.

For eg: In above example we perform keypress for both VK_ALT and VK_TAB together. Then we give small delay and then perform the keyrelease for VK_ALT and VK_TAB together
Share

Thursday, 20 June 2013

How To Validate Date With Regular Expression

How To Validate Date With Regular Expression

Date Format (dd/mm/yyyy hh:mm:ss) Regular Expression Pattern


(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d) ([01][0-9]|2[0-3]):([012345][0-9]):([012345][0-9])


Share

Wednesday, 19 June 2013

How To Get Installed Printer name using Java

How To Get Installed Printer name using Java

Get Installed printers in Java

  •     You can get installed printers by using both javax.print.PrintService and javax.print.PrintServiceLookup 
  •     PrintServiceLookup.lookupDefaultPrintService().getName(); will gives default printer name;

package com.javanotes2all.java.printers;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;

public class ShowPrinters {

String defaultPrinter;
    public void SearchPrinter() {
        PrintService[] ser = PrintServiceLookup.lookupPrintServices(null, null);
 
        System.out.println("**************** All Printers ******************");
        for (int i = 0; i < ser.length; ++i) {
            String p_name = ser[i].getName();
            System.out.println(p_name);
        }
        System.out.println("***********************************************\n");
        defaultPrinter  =   PrintServiceLookup.lookupDefaultPrintService().getName();
        System.out.println("Default Printer  : "+defaultPrinter );
    }
 
    public static void main(String[] args) {
        new ShowPrinters().SearchPrinter();
    }
}


Share

Tuesday, 11 June 2013

How To Add Password Protection To PDF Using IText In Java

How To Add Password Protection To PDF Using IText In Java

iText is very powerful library. It is used extensively to create PDF files in Java applications. Although not free, iText is the de-fecto Java library for working with PDF files. It has been extensively used in different Java related products for generating and manipulating PDF files.
Let us see how iText can be used to set password protection (encryption) to a PDF file. Also how to read an encrypted PDF file in Java.
Share

How to create random string with random characters?

How to create random string with random characters?



package com.javanotes2all.java.randomgenerator;

import java.util.Date;
import java.util.Random;

public class RandomGenerator 
{
private static Random random = new Random((new Date()).getTime());
public static String generateRandomString(int length) 
  {
      char[] values = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};

      String out = "";

      for (int i=0;i<length;i++) {
          int idx=random.nextInt(values.length);
        out += values[idx];
      }

      return out;
    }
    public static void main(String[] args) 
     {
      RandomGenerator generator=new RandomGenerator();
      System.out.println(generator.generateRandomString(10));
      System.out.println(generator.generateRandomString(10));
      System.out.println(generator.generateRandomString(10));
      System.out.println(generator.generateRandomString(10));
      System.out.println(generator.generateRandomString(10));
    }
}

OUTPUT:
qmpebje5dw
zxvpoeq59l
6y57vehsyk
j0g89kd4pa

3uz82j5gkp
Share