Showing posts with label util. Show all posts
Showing posts with label util. Show all posts

Wednesday, June 23, 2010

Cache - Least Recently Used Algorithm

LRU algorithm is heavily used in most of the cache implementation. In general, most of the time we depend on heavy weighted caching implementation and end up paying huge for that softwares.

java.util.LinkedHashMap provides simplest way to do this by overriding a method removeEldestEntry().

Here, I would like to present as an utilit class which will be reused our needs. New class LRUHashMap created from LinkedHashMap and cacheSize limit has to be passed as argument.

LRUHashMap Implementation

LRUHashMap.java 
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * LRUHashMap implements Least Recently Used algorithm to store and retrive the
 * values from {Map}.
 */

public class LRUHashMap<K, V> extends LinkedHashMap<K, V> {

 private static final long serialVersionUID = -6805360112277349979L;
 private final static int DEFAULT_INITIALCAPACITY = 10;
 private final static float LOADFACTOR = 0.75f;

 /**
  * Number of entries possible to keep maximum in given time in this {Map}
  */
 private final int cacheSize;

 public LRUHashMap() {
  super(DEFAULT_INITIALCAPACITY, LOADFACTOR, true);
  cacheSize = -1;
 }

 public LRUHashMap(int cacheSize) {
  super(DEFAULT_INITIALCAPACITY, LOADFACTOR, true);
  this.cacheSize = cacheSize;
 }
 
 /**
  * @param initialCapacity
  */
 public LRUHashMap(int initialCapacity, int cacheSize) {
  super(initialCapacity, LOADFACTOR, true);
  this.cacheSize = cacheSize;
 }

 /**
  * @param m
  */
 public LRUHashMap(Map<K, V> m, int cacheSize) {
  super(DEFAULT_INITIALCAPACITY, LOADFACTOR, true);
  putAll(m);
  this.cacheSize = cacheSize;
 }

 /**
  * @param initialCapacity
  * @param loadFactor
  */
 public LRUHashMap(int initialCapacity, float loadFactor, int cacheSize) {
  super(initialCapacity, loadFactor, true);
  this.cacheSize = cacheSize;
 }



 
 /** To achieve Thread Safe
 * @return
 */
 public Map<K, V> getsynchronizedMap()
 {
  return Collections.synchronizedMap(this);
 }

 @Override
 protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
  return size() > cacheSize;
 }
}

Test

LRUHashMapTest.java

public class LRUHashMapTest {

 public static void main(String[] args) {
  Map<Integer, String> map = new LRUHashMap<Integer, String>(10);
  
  //Enables Thread Safe
  //map = ((LRUHashMap<Integer, String>)map).getsynchronizedMap();
  
  for (int i = 0; i < 100; i++) {
   map.put(i, "valueof :" + i);

   for (int j = i - 5; j >= 0; j--)
    map.get(j);
  }

  System.out.println(map);
 }
}

Here, Cache Size set to 10, hence at any given time only 10 entries will be stored in Map. Additionally, whenever read access happens that object will be removed from actual location and added to rear of Map.

Output:

{95=valueof :95, 96=valueof :96, 97=valueof :97, 98=valueof :98, 99=valueof :99,
 4=valueof :4, 3=valueof :3, 2=valueof :2, 1=valueof :1, 0=valueof :0}

Thread Safe

The above mentioned implementation alone will not achieve thread safe. If our application is multi-threaded then we may need to fall-back to Collections.SynchronizedMap. We can achieve this by calling getsynchronizedMap(); in LRUHashMap.
Map<Integer, String> map = ((LRUHashMap<Integer, String>)map).getsynchronizedMap();

Monday, June 7, 2010

PropertyIgnoreCase

java.util.Properties helps to store and retrieve the key-value pair, where non-null values in key and value. This implementation made on top of java.util.HashTable. We do get all the features and APIs of HashTable additionally, getProperty(...), load() APIs.

In getProperty method, key has to be passed as argument to retrive the value. We can even specify the default value also in it, if no key found in list.

Then, What makes different in this blog posting ?. Here, the key is case-sensitive one. We have to send exact word to get the value. Most of the time, we may need to retrieve value for case-insensitive key. This is where, why don't we extend the functionality to give support to retrieve value with case-insensitive key.

Here, Properties extended to create PropertyIgnoreCase class, and added two APIs - getPropertyIgnoreCase(String key), getPropertyIgnoreCase(String key, String defaultV)


import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

public class PropertyIgnoreCase extends Properties {

 private static final long serialVersionUID = 7511088737858527084L;

 /**
  * get value from {Properties}
  * 
  * @param props
  * @param key
  * @return
  */
 public String getPropertyIgnoreCase(String key) {
  return getPropertyIgnoreCase(key, null);
 }

 /**
  * get value from {Properties}, if no key exist then return default value.
  * 
  * @param props
  * @param key
  * @param defaultV
  * @return
  */
 public String getPropertyIgnoreCase(String key, String defaultV) {
  String value = getProperty(key);
  if (null != value)
   return value;

  // Not matching with the actual key then
  Set<Entry<Object, Object>> s = entrySet();
  Iterator<Entry<Object, Object>> it = s.iterator();
  while (it.hasNext()) {
   Entry<Object, Object> entry = it.next();
   if (key.equalsIgnoreCase((String) entry.getKey())) {
    return (String) entry.getValue();
   }
  }
  return defaultV;
 }

 public static void main(String[] args) {
  PropertyIgnoreCase props = new PropertyIgnoreCase();
  props.put("Abc", "Value of Abc");
  props.put("xYZ", "Value of xYZ");

  System.out.println("get Key 'XYZ' using API from Properties = "
    + props.getProperty("XYZ"));
  System.out.println("get Key 'XYZ' using new API  = "
    + props.getPropertyIgnoreCase("XYZ"));
 }

}
Output:
get Key 'XYZ' using API from Properties = null
get Key 'XYZ' using new API  = Value of xYZ

Wednesday, February 3, 2010

Java Logger with Custom Formatter

In production or development environment, log files are playing major role to identify the nature of the issue and how often it raises. This information reduces the number of question needed to ask customer to understand the issue. Most valuable and precised data has to be captured in log files.

Developers, some time log there native language based log information and product also may shipped with these log information to customer. These kind of non-english or non-locale logs makes customer to panic and get back to vendors ;). Software developers and Quality Assurance folks has to spend considerable effort in stopping these kind of log details.

JAVA logger comes as part of JAVA SE and helps us to easy to configure and store/retrieve log information. Major components in Logger are

Level
specifies levels of information needed to be logged. In production, we may need only SEVERE information. In Development, we may need all information for debugging purpose, we may need to set FINEST or ALL. Possible log levels are OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, and ALL
LogRecord
Log level and message forms log record and it internally keeps time of record creation
Formatter
This component decides, in what format data has to go to log file. In JAVA SE, java.util.logging.XMLFormatter is default one
Handler
this holds the details of where to store and how to rotate and etc.,
Filter
filter decides given logrecord is logable or not
Logger
Exposes factory method to create Logger object for given name
Exposes APIs to log messages in various level.

XMLFormatter and custom formatter used to show how the log records are created in log file in /tmp/ folder.


import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;

public class LoggerTest {

 public static void main(String[] args) throws IOException {
  final Logger log = Logger.getLogger("LoggerTest", null);
  log.setLevel(Level.FINEST);
  log.setUseParentHandlers(false);
  FileHandler handler = new FileHandler("/tmp/log.log", false);
  log.addHandler(handler);

  // XML formatted log
  handler.setFormatter(new XMLFormatter());
  log.log(Level.FINEST, "Hello world");

  // Custom formatted log
  handler.setFormatter(new Formatter() {
   @Override
   public String format(LogRecord record) {
    return " custom log - " + log.getName() + " : "
      + record.getMillis() + ":" + record.getMessage();
   }
  });

  log.log(Level.FINEST, "Hello world");
 }
}

Monday, February 1, 2010

Java Mail

In JAVA Platform Enterprise Edition, javax.activation, and javax.mail packages has APIs to send or receive EMAIL. javax.mail.internet.InternetAddress class helps us to construct Address from String object.

Variety of properties which used to control the flow, monitor the flow, per session based properties and global properties for JAVA Mail. It is very tedious to remember all those properties. However, JAVA Doc is nicely written to list all those properties with brief explanation. Mail Session Properties | MIME properties | sMTP Properties

Mail Send

In the following sample, mail server is running with default port mail.smtp.port:25 in same machine, where this program is get executed. If no Mail server is configured to run in local, then we can configure to point thirdparty mailserver like gmail, hotmail, or rediffmail.


import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailTest {
 private static Session session = null;

 public static void main(String[] args) throws Exception {
  sendMail("krishna.oracleb2b@gmail.com", "abc@abc.com",
    "abc1@abc.com,abc2@abc.com", "Test mail",
    "Hello All, this is test message", true);
 }

 public static void sendMail(String sFrom, String sTo, String sBcc,
   String sSubject, String sBody, boolean sTextBody) throws Exception {
  try {
   Message message = new MimeMessage(getMailSession());
   message.setFrom(new InternetAddress(sFrom));
   InternetAddress to[] = new InternetAddress[1];
   to[0] = new InternetAddress(sTo);
   message.setRecipients(javax.mail.Message.RecipientType.TO, to);

   if (sBcc.length() > 0) {
    message.setRecipients(javax.mail.Message.RecipientType.BCC,
      InternetAddress.parse(sBcc));
   }

   message.setSubject(sSubject);
   if (sTextBody)
    message.setContent(sBody, "text/plain");
   else
    message.setContent(sBody, "text/html");

   Transport.send(message);

  } catch (MessagingException m) {
   m.printStackTrace();
   // throw new ShirtCommonException(m);
  } catch (Exception m) {
   m.printStackTrace();
  }
 }

 /**
  * getMail session
  * 
  * @return
  */
 private static Session getMailSession() {
  if (session == null) {
   // Get system properties
   Properties props = new Properties();

   // Setup mail server
   props.put("mail.smtp.host", "localhost");

   // Get session
   session = Session.getDefaultInstance(props, null);
   session.setDebug(true);
  }
  return session;
 }
}

In the above example, no security details used to send the message. Some server mandates user has to create session with username and password. And even more with SSL enable socket needs to be used to connect. In these cases, Transport has to be instantiated with proper SMTP security properties.Here is the sample for username-password authentication


Transport tr = session.getTransport("smtp");
tr.connect(smtphost, username, password);
msg.saveChanges();
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();

Mail Read

To read mail from MailServer, Mailserver has to support any of the mail reading protocol pop3, imap. Based on this, we have to create instance of javax.mail.Store and get the folder which ever we wants to operate on.


import java.io.InputStream;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;

public class MaieReceivelTest {
 private static Session session = null;

 public static void main(String[] args) throws Exception {
  readMail();
 }

 public static void readMail() throws Exception {
  try {
   Store store = getMailSession().getStore();
   store.connect("localhost", "username", "password");
   
   Folder folder = store.getFolder("Inbox");
   System.out.println(folder.getMessageCount());
   Message[] msgs = folder.getMessages();
   if (null != msgs) {
    for (Message msg : msgs) {

     InputStream is = msg.getDataHandler().getInputStream();
     if (is != null) {
      byte[] bytes = new byte[is.available()];
      is.read(bytes);
      System.out.println(new String(bytes));
     } else {
      Multipart mp = (Multipart) msg.getDataHandler()
        .getContent();
      is = mp.getBodyPart(0).getInputStream();
      byte[] bytes = new byte[is.available()];
      is.read(bytes);
      System.out.println(new String(bytes));
     }

    }
   }

  } catch (MessagingException m) {
   m.printStackTrace();
   // throw new ShirtCommonException(m);
  } catch (Exception m) {
   m.printStackTrace();
  }
 }

 /**
  * getMail session
  * 
  * @return
  */
 private static Session getMailSession() {
  if (session == null) {
   // Get system properties
   Properties props = new Properties();

   // Setup mail server
   props.put("mail.smtp.host", "localhost");
//   mail.smtp.user
      
   // Get session
   session = Session.getDefaultInstance(props, null);
   session.setDebug(true);
  }
  return session;
 }
}

Monday, January 18, 2010

Native payload Parsing

Most of the medium and large organization uses XML format of message to make communication with their customer or vendor. However, still we do fall in native format like EDI, JSON, and etc to transmit data over network. Even in webservice.

XML is the simplest way of transmitting message, however still native format has its own space to popularly used.

Native format defined by Industry standard bodys, and makes organization's life easy by putting hands together to train and develop the community. Specifically, B2B domain runs on top these standards and provisioning to marshall and unmarshalling data from native to xml and xml to native.

Why do we need native format?
Transmitting XML formatted data consumes considerable cost in network than native format.
Large System implemented before XML inventions and found ease of maintenance
Large number of dependencies like customer and vendors system

We may be interested in knowing market share of native and xml payloads. Upto me, I believe still large organizations which transmits very small(less than 1 KB) and very large(100MB) uses native format. XML fits in between of these two extreme.


Scannar


To write converter between native to object/xml or vice versa, we have to write a string parsing program using java.util.StringTokenizer, which will splits the string based on the static delimiters. We do get token only in the form of String, and it is our responsibility of converting into respective primitive format.

java.util.Scanner introduced in Java SE 5.0, in which we can take input either from InputStream, Readable, and String and possible to split using dynamic delimiters. Here, in the below samples, orgScanner used to split Organization name and employee name. Same orgScanner used to split organization name and age.


import java.util.Scanner;

public class ScannerTest {
public static void main(String[] args) {
String input = "Emp Krishna name Dharma Org Oracle " +
  "Age 29 Emp Suresh name Dharma Org Oracle Age 28";
Scanner s = new Scanner(input).useDelimiter("\\s*Emp\\s*");
while (s.hasNext()) {
 processEmployee(s.next());
}
s.close();
}

private static void processEmployee(String empStr) {
Scanner orgScanner = new Scanner(empStr).useDelimiter("\\s*Org\\s*");
if (orgScanner.hasNext()) {
 Scanner nameScanner = new Scanner(orgScanner.next())
   .useDelimiter("\\s*name\\s*");
 System.out.println("FirstName:" + nameScanner.next() + " LastName:"
   + nameScanner.next());
}

if (orgScanner.hasNext()) {
 orgScanner = orgScanner.useDelimiter("\\s*Age\\s*");
 System.out.println("Organization:" + orgScanner.next() + " Age:"
   + orgScanner.nextInt());
} else {
 System.out.println("No Organization specified");
}}
}
 Output:
javac ScannerTest
java ScannerTest

FirstName:Krishna LastName:Dharma
Organization: Org Oracle Age:29
FirstName:Suresh LastName:Dharma
Organization: Org Oracle Age:28

Wednesday, January 6, 2010

DOJO and JSON Toolkit

DOJO

Dojo Toolkit is an open-source JavaScript toolkit, which helps to build nice/rice web applications. Dojo Core comes with Ajax, events, packaging, CSS-based querying, animations, JSON, language utilities, and a lot more in just 26k size(gzip). We can do all magic related to Javascript and DHTML, simply invoking repective API in Dojo script as similaror equal to widget.

Dojo is nice toolkit which completelty makes us not to think of writing cross-platform script, all these environmental botherations are taken care by Dojo. We can download, this javascript and place it in our webapplication to use it, or else we can use any of the Content Delivery Network to refer from our web application.

JSON

JavaScript Object Notation is lightweight data interchange format. Usually, we get use SOAP message to send/receive platform agnostic messages, Whereas we have to use any of the XML parsing technique DOM, SAX, JAXB and StAX. And moreover, the message size will be increased to hold tag names meaningful. If we have client-server application where our software runs in client environment which knows what data is getting transmitted between server and client then JSON is the best option.

JSON provides facility to convert normal string to object and Object to normal string in most of the softwares - JAVA, ASP, PHP and etc.,

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).Read more RFC 4627


Samples and Documentations:
API reference | Dojo QuickStart |Dojo download |JSON

Saturday, October 31, 2009

OW2 Consortium : ASM 3.0

OW2 Consortium : ASM 3.0

ASM is nice tool to decompile the class files and also helps us to manupulate and modify the class files directly without modifying the original JAVA source. This tool usefull for instrumenting jars like,

  • Adding debug statements - on need basis without modifying the original source
  • Correcting particular line of code directly in testing environment where we do not have original source.
  • and lot more...


Even ASM provides plugin which helps seemlessly converts class file and which helps us to compare the actual and compiled format code.

Check the following URL http://asm.ow2.org/index.html

Friday, February 27, 2009

Trim prefix and suffix any characters

java.lang.String has API for trim, which will remove whitespaces(blankspace) from prefix and sufix of the string.

How to do the same for other characters which are not required and has to be truncated. We can even write a regular expression(regexps) to format this.

For example,
aaaaWelcomeaaaa
in this 'a' needs to be removed/trim and output String has to be like below
Welcome

Find the API implementation below which helps us to achieve this

System.out.println(trim("aaaaWelcomeaaaa",'a'));

/** Trim characters in prefix and suffix
* @param str String 
* @param ch character which has to be removed
* @return null, if str is null, otherwise string will be returned 
* without character prefixed/suffixed
*/
public static String trim(String str,char ch) {
if(null ==str)return null;
str=srt.trim();
int count=str.length();
int len = str.length();
int st = 0;

char[] val = str.toCharArray();   

while ((st < len) && (val[st] == ch)) {
st++;
}
while ((st < len) && (val[len - 1] == ch)) {
len--;
}
return ((st > 0) || (len < count)) ? str.substring(st, len) : str;
}

Tuesday, October 14, 2008

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

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

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.

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