Tuesday, October 14, 2008

XML Tag Generator

Java Developers sometimes forced/asked to create XML document using any of the available implementations may be from IBM, Oracle, BEA, or SUN reference implementations. Relying on particular implementation which will stop improving the performance by including unwanted classes also in our classpath.

If your requirement is just to create XML document not doing any manipulation below is the sample code which will helps you to created easily the XML document with fully formattedXML.

TWO Java files: - Tag.java, XMLGenerator.java

Tag.java
- which holds the details of how the architecture looks like and how the attribute and elements will be hold and generated the XML string object out of it.
XMLGenerator.java
- Sample program which utilize this Tag generator and creates XML for you.

Tag.java:


package javax;

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

public class Tag implements Serializable {

private static final long serialVersionUID = -7676167530337603084L;

private String tagName;
private Map<String, String> attrList = new HashMap<String, String>();
private List<Tag> childList = new ArrayList<Tag>();

private static final String LT = "<";
private static final String GT = ">";
private static final String BACK_SLASH = "/";
private static final String WHITE_SPACE = " ";
private static final String NEWLINE = "\n";
private static final String EQUAL = "=";
private static final String DOUBLE_QUOTE = "\"";
private static final String FORWARD_SLASH = "\\";
private static final String UNDEFINED = "Undefined";

public Tag() {
setTagName(UNDEFINED);
}

public Tag(String tagName) {
setTagName(tagName);
}

/**
* @return the tagName
*/
public String getTagName() {
return tagName;
}

/**
* @param tagName
* the tagName to set
*/
public void setTagName(String tagName) {
this.tagName = tagName;
}

/**
* @return the attrList
*/
public Map<String, String> getAttrList() {
if (null == attrList)
attrList = new HashMap<String, String>();
return attrList;
}

/**
* @param attrList
* the attrList to set
*/
public void setAttrList(Map<String, String> attrList) {
this.attrList = attrList;
}

/**
* @return the childList
*/
public List<Tag> getChildList() {
if (null == childList)
childList = new ArrayList<Tag>();
return childList;
}

/**
* @param childList
* the childList to set
*/
public void setChildList(List<Tag> childList) {
this.childList = childList;
}

/* Business methods -start */
public StringBuilder generatewithProcessTag() {
StringBuilder str = new StringBuilder();
str.append("").append(NEWLINE).append(
generateTag());
return str;
}

public StringBuilder generateTag() {
StringBuilder str = new StringBuilder();
str.append(LT).append(getTagName());
if (!getAttrList().isEmpty()) {
str.append(generateAtribute(getAttrList()));
}
if (!getChildList().isEmpty()) {
str.append(GT);
for (Tag childTag : getChildList()) {
str.append(NEWLINE).append(childTag.generateTag());
}
str.append(NEWLINE).append(LT).append(BACK_SLASH).append(
getTagName()).append(GT);
} else {
str.append(WHITE_SPACE).append(BACK_SLASH).append(GT);
}
return str;
}

private StringBuilder generateAtribute(Map<String, String> attrMap) {
StringBuilder str = new StringBuilder();
for (Map.Entry<String, String> attribute : attrMap.entrySet()) {
str.append(WHITE_SPACE).append(attribute.getKey()).append(EQUAL)
.append(DOUBLE_QUOTE).append(attribute.getValue()).append(DOUBLE_QUOTE);
}

return str;
}
/* Business methods -end */
}

Here you go with testing

XMLGenerator.java:


package javax;

public class XMLGenerator {

public static void main(String[] args) {
Tag tag = new Tag("documentprotocol");
tag.getAttrList().put("docversion","1.0");
tag.getAttrList().put("docprotocol","custom");

Tag doctypetag=new Tag("DocumentType");
tag.getChildList().add(doctypetag);

System.out.println(tag.generatewithProcessTag());
}
}

Java Archive

The Java Archive (JAR) file format enables you to bundle multiple files into a single archive file.

To process/manipulate/create/extract jar file use

jar[option] jar-file command

Name
The name of the specification.
Specification-Title
The title of the specification.
Specification-Version
The version of the specification.
Specification-Vendor
The vendor of the specification.
Implementation-Title
The title of the implementation.
Implementation-Version
The build number of the implementation.
Implementation-Vendor
The vendor of the implementation
Main-class
helps us to refer the class name of the executable jar
Sealed
If you want to guarantee that all classes in a package come from the same code source, use JAR sealing.
Class-Path
The value of this attribute specifies the relative URLs of the extensions or libraries that this application or extension needs

 #MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.5
Created-By: 1.5.0_04-b05 (Sun Microsystems Inc.)
Main-class: abc.xyz.yourclass

#ADVANCED

Name: java/util/
Specification-Title: Java Utility Classes
Specification-Version: 1.2
Specification-Vendor: Sun Microsystems, Inc.
Implementation-Title: java.util
Implementation-Version: build57
Implementation-Vendor: Sun Microsystems, Inc.
Sealed: true
How to add jars into manifest classpath?.
Class-Path: jar1-name jar2-name directory-name/jar3-name
How to set executable class in jar file ?.
Main-Class: abc.xyz.yourclass
Why am getting NoClassDefFoundError ?
Check classpath included in manifest.mf file and jvm classpath included jar
Am I loading all the classes from the correct code base ?.
To confirm this we have to seal our package.

Example:
Name: myCompany/myPackage/
Sealed: true

References:
JAR Tutorial | Manifest file

Wednesday, October 1, 2008

JNDI access outside OC4J container

How to connect Standalone Application with DataSource / EJB Beans / any Container Resources ?.
Java Naming and Directory Interface (JNDI)

An application client helps to connect to container resources by referring resources in config xmls. We really not interested in doing all this magic. We know the resource(DataSource/Beans/JMS QUeue/topic) type and the location where it is located.

A JNDI(Java Naming and Directory Interface) name is the reference name specified in container to refer the resource from local and remote.

A J2EE application client is a standalone program launched from the command line or desktop, and typically accesses Enterprise JavaBean programs running on the J2EE application server. In Application client, we have to bundle an application such a way that to access the beans. Please refer for more info J2EE Application Client.

Again this is hectic way of accessing the resources from Application container, then what will I do ?.

yeah, we have the answer for this. Using RMI protocol, we can access any of the Beans/DataSource/Topic/Queue from server.

The following four properties and requesting object executables(classes) in your class path is enough to communicate with server.

java.naming.factory.initial=oracle.j2ee.rmi.RMIInitialContextFactory
java.naming.provider.url=ormi://localhost:23791/
java.naming.security.principal=oc4jadmin
java.naming.security.credentials=welcome1

The above mentioned properties will vary based on what kind of Application server, we are using. Here, I have taken Oracle 10.1.3 Application server OC4J to explain.

we can specify these properties in either of three approaches

1. Programmatically including these attributes

In this Approach, we have to always pass a Hashtable to create a Initialcontext. That HashTable has to store all these properties and values. Most of the time this approach is not suggested, because of the reason we have to modify these values(hard coded values) or we have to pick from external environment and given to Hash table

Hashtable env = new Hashtable();
env.put("java.naming.factory.initial","oracle.j2ee.rmi.RMIInitialContextFactory");
env.put(java.naming.provider.url","ormi://localhost:23791/");
env.put(java.naming.security.principal","oc4jadmin");
env.put(java.naming.security.credentials","welcome1");

2. Specifying in Java Command

Other way is directly specifying in Java command using -D option.

java -Djava.naming.factory.initial=oracle.j2ee.rmi.RMIInitialContextFactory \
-Djava.naming.provider.url=ormi://localhost:23791/ \
-Djava.naming.security.principal=oc4jadmin \
-Djava.naming.security.credentials=welcome1 \ <javaprogram>

3. Specifying in jndi.properties file

Best way of segregating configuration and application is specify these configuration details separately in a proprty file and name it as jndi.properties. This file containing folder has to be included in classpath.

java -cp .;%cp% yourapplication

Note:
This %cp% should load all of your application required classes containing jar files.


I am not able to access some of my beans, what to do ?.

Check java.naming.provider.url is correct or not. If you are accessing beans/topic/queue then you have to specify EJB Application also in this URL. Example, If your EJB Application name is Bank then specify like java.naming.provider.url=ormi://localhost:23791/Bank

Refer Specifying Environment Properties


Weblogic

Weblogic uses t3 protocol to make RMI connection:

java.naming.provider.url=t3://<hostname>:7001
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.security.principal=weblogic
java.naming.security.credentials=weblogic1

Free/Sample HTTP Server

In this software world, everything has to be built our own or it has to be opensource code which helps us to tune the performance our application. I was in the need of testing my product which makes more than 100 HTTP request per minute. I initially thought of installing freely available any of the HTTP server. But, none of the HTTPServer comes with the flavour of light weight, everything starts minimum of 10 MB and it needs separate installation which will not be started just like that.

Building a HTTP Server:

We have to have little bit of knowledge about the HTTP protocol. This protocol is nothing but built on top of TCP with specific headers, which leads us to important details easily using some kind of getter method.

To build HTTPServer, we have to know the threading concept with socket programming knowledge. Don't worry, I won't ask you to write the HTTPServer code here, I will share with you full code which is ready to use.

No configuration is required for this server. Just add this class in your classpath and create instance of this Class by passing port number.

Here you go with HTTPServer implementation code.

HTTPServer has two inner classes - one is HTTPRequest, HTTPWorker.


import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Properties;

public class HTTPServer implements Runnable {

 public static final String CONTENT_LENGTH = "Content-length";
 public static final String CONTENT_TYPE = "Content-type";
 private static char NEW_LINE = '\n';
 private static final String EOL = "\r\n";
 private static final String SUCCESS_HDR_MESSAGE = "HTTP/1.1 200 OK";
 private static final String SC_NO_CONTENT = 
 "HTTP/1.1 204 No Content" + EOL
   + "Content-Type: text/plain" 
   + EOL + "Cache-Control: private" + EOL
   + EOL;

 private static final String 
 INTERNAL_ERROR = "HTTP/1.1 500 Internal " +
   "Krishna's Server Error"
   + EOL
   + "Content-Type: text/html"
   + EOL
   + EOL
   + "<html><head>BLite Internal Error</head><body>";

 private static int DEFAULT_PORT = 7777;
 private static String SOAP_ACTION = "SOAPAction";

 private int port;

 private boolean isShutdown = false;

 private static HTTPServer httpServer = null;

 public static HTTPServer newInstance(int port) {

  if (null == httpServer) {
   httpServer = new HTTPServer();
   if (port > 0)
    httpServer.port = port;
  }

  return httpServer;
 }

 private HTTPServer() {
  this.port = DEFAULT_PORT;
 }

 public void run() {

  System.out.println(" STARTING HTTP SERVER ");
  System.out.println("HTTP Server Listens on port " + httpServer.port);

  try {
   // ServerSocket
   // ss=ServerSocketFactory.getDefault().createServerSocket(port,1500);
   // ss.setReceiveBufferSize(2048);
   // ss.setReuseAddress(true);
   ServerSocket ss = new ServerSocket(port, 1500);
   long startTime = System.currentTimeMillis();

   while (!isShutdown) {
    try {
     System.out
       .println("SocketTime :"
         + ((startTime = System.currentTimeMillis()) - startTime)
         + "s");
     HTTPWorker httpWorker = new HTTPWorker(ss.accept());
     Thread thread = new Thread(httpWorker);
     thread.start();
     thread = null;
    } catch (Throwable e) {
     System.out.println(e);
    }
   }

  } catch (Throwable e) {
   System.out.println(e);
  }
  // finally
  // {
  // tpe.shutdown();
  // }
 }

 public static String getPropertyIgnoreCase(Properties props, 
   String key) {
  String value = null;

  Enumeration enum0 = props.propertyNames();
  while (enum0.hasMoreElements()) {
   String name = (String) enum0.nextElement();
   if (key.equalsIgnoreCase(name)) {
    value = props.getProperty(name);
    break;
   }
  }

  return value;
 }

 
 public void shutdown() {

  this.isShutdown = true;
 }

 private class HTTPRequest {

  private byte[] request;
  private int headerIndex = 0;
  private Properties headers;
  private byte[] bodyContent;

  public HTTPRequest(byte[] request) {
   this.request = request;
   init();
  }

  private void init() {

   if (request == null)
    return;

   for (int i = 0; i < request.length; i++) {
    if ((NEW_LINE == (char) request[i])
       && (13 == request[i + 1])) {
     headerIndex = i;
     break;
    }
   }

   initHeaders();
   initBodyContent();
  }

  private void initHeaders() {
   String httpMethod;
   String httpVersion;
   String path;
   String headerContent = new String(request, 0, headerIndex);

   String[] availbleHeaders = headerContent.split("\n");

   if (availbleHeaders != null && 
   availbleHeaders.length > 0) {
    String[] typeContainer = availbleHeaders[0].split(" ");

    if (typeContainer != null && 
       typeContainer.length > 2) {
     httpMethod = typeContainer[0];
     path = typeContainer[1];
     httpVersion = typeContainer[2];
    }
   }

   if (availbleHeaders.length > 1) {
    this.headers = new Properties();

    for (int index = 1; index < availbleHeaders.length; index++) {
     String key = availbleHeaders[index].substring(0,
       availbleHeaders[index].indexOf(':'));
     String value = availbleHeaders[index].substring(
       availbleHeaders[index].indexOf(':') + 1,
       availbleHeaders[index].length() - 1);
     this.headers.put(key, value);
    }
   }
  }

  private void initBodyContent() {

   int bodyIndex = headerIndex + 3;
   bodyContent = new byte[request.length - bodyIndex];
   for (int i = (bodyIndex), j = 0; 
   i < request.length; i++, j++) {
    bodyContent[j] = request[i];
   }

  }

  public Properties getHeaders() {
   return headers;
  }

  public byte[] getBodyContent() {
   return bodyContent;
  }

 }

 private class HTTPWorker implements Runnable {

  private String ret = null;
  private BufferedInputStream is;
  private DataOutputStream os;
  private Socket socket = null;
  
  public HTTPWorker(Socket socket) {
   this.socket = socket;
   try {
    this.socket.setTcpNoDelay(true);
    // this.socket.setSoLinger(true, 60);

    is = new BufferedInputStream(socket.getInputStream());
    os = new DataOutputStream(socket.getOutputStream());

   } catch (Exception e) {
   }
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Runnable#run()
   */
  public void run() {

   try {
    readwrite();
   } catch (Throwable e) {
    System.out.println("\n\n***\n" + ret + "\n****\n\n");
    System.out.println(e);
   }

  }

  private void readwrite() throws Throwable {

   try {
    ret = readHTTPMessage();

    //Here HTTP request string is 
 ready to do your business magic 
 
 
    
    
    StringBuffer strbuffer = new StringBuffer();
    strbuffer.append(SC_NO_CONTENT);
    writebytes(socket, strbuffer.toString());

   } catch (Throwable e) {
    System.out.println(e);
   } finally {

    // Following code has no use, However to make double check
    // whether socket is closed
    if (!socket.isClosed())
     socket.close();
   }
  }

  public String readHTTPMessage() throws IOException {
   String result = null;
   StringBuffer strb = new StringBuffer();
   int bufferSize = 1024; // is.available()==0 ? 1024:is.available();
   int contentLength = 0;
   int headerLength = 0;
   int bodyLength = 0;
   try {
    byte[] buf = new byte[bufferSize];
    int nread = 0;
    while ((nread = is.read(buf)) != -1) {
     if (nread == 0)
      continue;
     strb.append(new String(buf, 0, nread));
     // System.out.println(strb);
     result = strb.toString();

     if (contentLength == 0) {

      // atleast 50 bytes required to identify content length
      if (result.length() < 50)
       continue;

      HTTPRequest request = new HTTPRequest(result.getBytes());
      String contentStr = getPropertyIgnoreCase(request
        .getHeaders(), CONTENT_LENGTH);

      // if length specified
      if (null == contentStr || "".equals(contentStr))
       break;

      contentLength = Integer
        .parseInt("" + contentStr.trim());
      bodyLength = request.getBodyContent().length;
      headerLength = result.length() - bodyLength;
     } else {
      bodyLength = result.length() - headerLength;
     }

     if (bodyLength < contentLength) {
      bufferSize = contentLength - bodyLength;
      buf = new byte[bufferSize];
     } else {

      if (bodyLength >= contentLength 
        || result.endsWith(EOL)) {

       // try{socket.shutdownInput();}catch(Exception e){}
       break;
      }

     }
    }
   } catch (Exception e) {
    System.out.println(e);
   } finally {
    // try{is.close();}catch(Exception e){}

   }
   return result;
  }

  private void writebytes(Socket socket, String data) {
   try {
    //
    os.write(data.getBytes());
    os.flush();
    if (!socket.isClosed())
     is.close();
    if (!socket.isClosed())
     os.close();

   } catch (Throwable e) {
    System.out.println(e);
   }

   try {
    if (!socket.isClosed())
     socket.close();
   } catch (Throwable e) {
    System.out.println("Problem in data writing in channel");
    System.out.println(e);
   }
  }

  @Override
  protected void finalize() throws Throwable {
   // TODO Auto-generated method stub
   super.finalize();
   socket = null;
   ret = null;
  }
 }
}

If you like this blog and posting, please feel free to leave your comments, which will help me to post more useful blogs.. :)

Tuesday, July 8, 2008

URLHandler for ZIP stream

Accessing file from ZIP using URL

In our usual life, we may need to access particular content from ZIP file often and often. We may not be interested in retrieving complete content from ZIP. It would be good idea to have a URL Handler, which will help us to access only the content of ZIP directly and/or seamlessly.

We have a built-in facility of accessing content from JAR file directly. Why should not we form the similar approach to access the content from ZIP ?.

Aim of this post is not only to explain the code which will help us to retrieve the particular content, we do get to know the way how URL handler is going to work.


Agenda:

Name the protocol
Name the Java package
Creating Java files required to enable URLHandler for ZIP protocol
Notifying to JVM by setting in environment
Notifying to JVM by setting as part of Main method

1. Name the Protocol

We have to name the protocol i.e we have to prefix a string which will help us to say what we are trying to do. Here, we will create our own protocol and we will name it as “zip”. Hence the URL format will looks like below
zip:http://www.javafundu.com/baz.zip!/afolder/a.txt
where
!/ - Separator
http://www.javafundu.com/baz.zip - points actual zip file
afolder/a.txt – is the content available in baz.zip

2. Name the Java Package

Java files has to be placed in a package and the naming package should looks like below

<anypackagename>.protocol.<nameoftheprotocol>
Example: com.javafundu.protocol.zip

3. Create Java files URLStreamHandler and URLConnection

Handler, which will instruct JVM to call this Class to open the connection when URL.openConnection().

Handler.java

package com.javafundu.protocol;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

@Override
protected URLConnection openConnection(URL url) throws IOException {
// create new instance of URLConnection
return new ZIPURLConnection(url);
}
}

URLConnection does the actual job of unzipping and returning the subelement. URL argument in openConnection method has the URL http://… , when actual url is “zip:http://…”

ZIPURLConnection.java:

package com.javafundu.protocol;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZIPURLConnection extends URLConnection {

protected ZIPURLConnection(URL url)throws MalformedURLException {
super(url);
// TODO Auto-generated constructor stub
}

@Override
public void connect() throws IOException {
// TODO Auto-generated method stub

}

/* (non-Javadoc)
* @see java.net.URLConnection#getInputStream()
*/
public InputStream getInputStream() throws IOException {

InputStream result= null;
URL url = this.url;

String spec = url.getFile();

int separator = spec.indexOf('!');
/*
* REMIND: we don't handle nested JAR URLs
*/
if (separator == -1) {
throw new MalformedURLException("no ! found in url spec:" + spec);
}

long startTime = System.currentTimeMillis();

URL zipFileURL = new URL(spec.substring(0, separator++));

String entryName =spec.substring(separator+1);



ZipInputStream zis = new ZipInputStream(zipFileURL.openStream());
ZipEntry entry = null;

// check inputStream is ZIP or not
if ((entry = zis.getNextEntry()) != null) {
do {
// System.out.println(entry.getName());
if(entryName.equals( entry.getName()))
{
result= zis;
break;
}
} while ((entry = zis.getNextEntry()) != null);
} else {
System.out.println("Given path is not referring ZIP file");
}
System.out.println( "Looking for " +entryName + " " +(System.currentTimeMillis() - startTime) + "ms");
return result;
}
}

Now Java implementation is ready for compilation. Bundle your application with these two class files. Assume bundled as jf.jar.

4.Notifying to JVM by setting in environment

Set the environment variable, which specifies the information of Handlers available location.

Java -Djava.protocol.handler.pkgs=”com.javafundu.protocol”

Now, your JVM will understand “zip:” as a URL authority and start works. If you create a URL with zip: , then Java will call com.javafundu.protocol.Handler to parse this URL.

URL url=new URL(“zip:http://www.javafundu.com/baz.zip!/afolder/a.txt ”)

5.Notifying to JVM by setting as part of Main method

Sometime, this is very difficult to set this value in environment variable due to some restriction. Hence, we have alternate approach, which will help us to set and make use of this facility.

System.setProperty("java.protocol.handler.pkgs","com.javafundu.protocol");

We have to set this property at the earliest possible to before creating URL with zip:
If we wants to specify more than one protocol then we have to delimit using symbol. For example

System.setProperty("java.protocol.handler.pkgs","com.javafundu.msaccess.protocolcom.javafundu.protocol");


Resource:
URL (Java 2 Platform SE v1.4.2) |
JarURLConnection (Java 2 Platform SE v1.4.2) |
RFC 2373: IP Version 6 Addressing Architecture

Wednesday, May 28, 2008

JAVA

The Sun Developer Network (http://developers.sun.com) is a free service that Sun offers. To join, visit http://developers.sun.com/global/join_sdn.html

For a limited time, SDN members can obtain fully licensed Java IDEs for web and enterprise development. More information is at http://developers.sun.com/prodtech/javatools/free/.

Monday, March 10, 2008

System Property

How to retrieve System properties ?.
What are the properties has to be used while doing cross platform coding ?

We have to make use of almost all the properties comes from System.getProperties method for our development. While doing cross platform coding File.separator and path.separator and encoding are very well useful for us to get to know correct value.

Code Snippets to list out all the properties:


Properties props = System.getProperties();
Iterator it = (props.entrySet().iterator());
while (it.hasNext()) {
Map.Entry property = 
(Map.Entry<String, String>) it.next();
System.out.println(property.getKey() 
+ ": " + property.getValue());
}

In my machine, I got following properties key are set


java.runtime.name
sun.boot.library.path
java.vm.version
java.vm.vendor
java.vendor.url
path.separator
java.vm.name
file.encoding.pkg
sun.java.launcher
user.country
sun.os.patch.level
java.vm.specification.name
user.dir
java.runtime.version
java.awt.graphicsenv
java.endorsed.dirs
os.arch
java.io.tmpdir
line.separator
java.vm.specification.vendor
user.variant
os.name
sun.jnu.encoding
java.library.path
java.specification.name
java.class.version
sun.management.compiler
os.version
user.home
user.timezone
java.awt.printerjob
file.encoding
java.specification.version
java.class.path
user.name
java.vm.specification.version
java.home
sun.arch.data.model
user.language
java.specification.vendor
awt.toolkit
java.vm.info
java.version
java.ext.dirs
sun.boot.class.path
java.vendor
file.separator
java.vendor.url.bug
sun.io.unicode.encoding
sun.cpu.endian
sun.desktop
sun.cpu.isalist

Time Difference Calculator from Long data type

I want to get to know the time difference from two date/time. In JAVA, there is no method available built in to find out the differences between two dates. Hence, we have to getTime in long format of first date and it should be subtracted with another date. Using this long value, we can form the date format.

Here in the below code snippets, start and end time caputed using System.currentTimeMillis(), we have to come to know how long it take to complete our business.


long startTime = System.currentTimeMillis();
//do your business
...
long endTime= System.currentTimeMillis();

//calculate difference
long timeDiff_long = endTime - startTime;

long days = timeDiff_long / (60 * 60 * 24);
long backdays = days * 60 * 60 * 24;

long hour = (timeDiff_long - backdays) / (60 * 60);
long backhour = hour * 60 * 60;

long minute = (timeDiff_long - (backdays + backhour) ) / 60;
long backminute = minute * 60;

long seconds = (timeDiff_long - (backdays + backhour + backminute )) ;
System.out.println("DAYS: " + days);
System.out.println("HOUR: " + hour);
System.out.println("MINUTE: " + minute);
System.out.println("SECOND: " + seconds);

Using the above code, we can format Date object as our wish.

Friday, January 25, 2008

Eclipse Shortcut

Some of the often using Eclipse Shortcuts

Refactoring

SHIFT + ALT + TPopup the refactoring Tab
SHIFT + ALT + RRename
SHIFT + ALT + MExtract Method
SHIFT + ALT + VMove
SHIFT + ALT + LExtract Localvariable
SHIFT + ALT + FConvert local variable toField
SHIFT + ALT + iInline

Search

CTRL + ALT + NQuick search plugin(*)
CTRL + HGeneric search file andJava search box
CTRL + SHIFT + GSearch for reference inthe workspace
F4Open type hierarchy
F3Open declaration
ALT + LEFTNavigate Back
CTRL + JIncremental Find Next

Source

CTRL + 1Quick Fix
F2Show tooltip description
SHIFT + ALT + SPopup the source box
CTRL + ESC + CComment/Uncommentselected code
CTRL + ICorrect Identationonly
CTRL + SHIFT + OOrganize imports
Alt + Shift + PNavigating toMatching braces
Ctrl + ONavigating todifferent parts of the code
Ctrl + , andCtrl + .takes you to theprevious/next error
Ctrl + F7Switching todifferent views
Ctrl + F6Switching todifferent Editors
Ctrl + F8Switch to DifferentPerspectives
Ctrl + shift + Arrow-up/Ctrl + shift + Arrow-downJumping from Methodto Method
CTRL + SHIFT + TOpen Type
CTRL + SHIFT + ROpen Resource
CTRL + BBuild All

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com