Showing posts with label J2SE. Show all posts
Showing posts with label J2SE. Show all posts

Tuesday, December 30, 2014

JAVA CODE TO GET COMPLETE JVM DETAIL

import java.io.*;

class JVMFlight{
public static void main(String bag[]){
System.out.println("--start--");

StringWriter stringBuffer = new StringWriter();
PrintWriter out = new PrintWriter(stringBuffer);

out.println();
out.println();
out.println("    java.home: " + System.getProperty("java.home"));
out.println("    java.vendor: " + System.getProperty("java.vendor"));
out.println("    java.version: " + System.getProperty("java.version"));
out.println("    java.vm.name: " + System.getProperty("java.vm.name"));
out.println("    java.vm.version: " + System.getProperty("java.vm.version"));
out.println("    os.name: " + System.getProperty("os.name"));
out.println("    os.arch: " + System.getProperty("os.arch"));
out.println("    os.version: " + System.getProperty("os.version"));
out.println("");

System.out.println(stringBuffer.toString());
System.out.println("--end--");
}
}

Sunday, December 21, 2014

Swap Index of Two values in Java List

boolean idFlag = false;

if(propertyList.contains("ID")){
idFlag = true;
int index = propertyList.indexOf("ID");
Collections.swap(propertyList, index, 0);
}

if(propertyList.contains("NAME")){
int index = propertyList.indexOf("NAME");
if(idFlag){
Collections.swap(propertyList, index, 1);
}else{
Collections.swap(propertyList, index, 0);
}
}


Give your valuable comment
Keep Visiting :)

Monday, December 15, 2014

Java ArrayStack Code

interface Stack {
  public void push(int elt);
  public int pop();
  public boolean isEmpty();
}

public class ArrayStack implements Stack{
  private final int MAX_ELEMENTS = 10;
  private int[] stack;
  private int index;
  public ArrayStack() {
    stack = new int[MAX_ELEMENTS];
    index = -1;
  }
  public void push(int elt) {
    if (index != stack.length - 1) {
      index++;                                        //1
      stack[index] = elt;                             //2
    } else {
      throw new IllegalStateException("stack overflow");
    }
  }
  public int pop() {
    if (index != -1) {
      return stack[index--];
    } else {
      throw new IllegalStateException("stack underflow");
    }
  }
  public boolean isEmpty() { return index == -1; }
}

Wednesday, September 24, 2014

Java Utility

Info
Useful java utility method for String, Collections and Array

import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import junit.framework.Assert;

/*
 * Author: Raj Kirpalsinh
 * */

public class JavaUtility {

/* checking not null and not empty on the string object without trimming */
public static boolean isNotNullAndNotEmpty(String reference) {
return (reference != null && reference.trim().length()>0);
}


/* checking null/empty on the string object without trimming */
public static boolean isNullOrEmpty(String reference) {
return (reference == null || reference.trim().length()==0);
}

/* checking not null and  not empty on the Collection (interface) object */
public static boolean isNotNullAndNotEmpty(Collection<?> reference) {
return (reference != null && reference.size()>0);
}

/* checking null/empty on the Collection (interface) object */
public static boolean isNullOrEmpty(Collection<?> reference) {
return (reference == null || reference.size()==0);
}

/* checking not null and not empty on the Map (interface) object */
public static boolean isNotNullAndNotEmpty(Map<?,?> reference) {
return (reference != null && reference.size()>0);
}

/* checking null/empty on the Map (interface) object */
public static boolean isNullOrEmpty(Map<?,?> reference) {
return (reference == null || reference.size()==0);
}

/* trimming string array all elements values*/
public static String[] trim(String[] refArray) {
        if (refArray == null) {
            return refArray;
        }
        for (int i = 0, len = refArray.length; i < len; i++) {
            refArray[i] = refArray[i].trim();
        }
        return refArray;
    }

/* checking not null and not empty on the Array (Object[])*/
public static boolean isNotNullAndNotEmpty(Object[] reference) {
return (reference != null && reference.length>0);
}

/* checking null/empty on the Array (Object[])*/
public static boolean isNullOrEmpty(Object[] reference) {
return (reference == null || reference.length==0);
}

/* Closing all the objects/streams have Closeable interface nature */
public static void closeMe(Closeable reference) {
if(reference!=null) {
try {
reference.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
}

/* Converting any string (i.e word/line) in Camel-Case
* i.e hello good morning buddy -->> Hello Good Morning Buddy 
* */
public static String toCamelCase(String reference) {
if(isNullOrEmpty(reference) == false) {
String words[] = reference.split(" ");
StringBuilder line = new StringBuilder();
for(String word : words) {
word = word.trim().toLowerCase();
if(isNotNullAndNotEmpty(word)){
word = word.replaceFirst(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());
line.append(word).append(" ");
}
}
return line.toString().trim();  
}
return reference;
}


public static void main(String dataBag[]) {
System.out.println("------BEGIN------");

String str = "  hello good morning buddy  ";
System.out.println("toCamelCase: "+toCamelCase(str));

String test = "";

Assert.assertEquals((isNotNullAndNotEmpty(test) == false), (isNullOrEmpty(test) == true));
Assert.assertEquals((isNotNullAndNotEmpty("") == false), (isNullOrEmpty("") == true));
Assert.assertEquals((isNotNullAndNotEmpty("adfa") == true), (isNullOrEmpty("") == false));

System.out.println("------END------");
     }
}

Keep Visiting :)

Convert Number to Local Currency Using Java

package com;

import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

public class NumberToCurrencyEngine
{
   public static void main(String[] args)
   {
      //This is the amount which we want to format
      Double currencyAmount = new Double(50000);
       
      //Get current locale information
      Locale currentLocale = Locale.getDefault();
       
      //Get currency instance from locale; This will have all currency related information
      Currency currentCurrency = Currency.getInstance(currentLocale);
       
      //Currency Formatter specific to locale
      NumberFormat currencyFormatter =      NumberFormat.getCurrencyInstance(currentLocale);

      //Test the output
      System.out.println(currentLocale.getDisplayName());
       
      //System.out.println(currentCurrency.getDisplayName());
       
      System.out.println(currencyFormatter.format(currencyAmount));
   }
}

Output
English (India)

Rs.50,000.00

Basic understanding of Connection Pool With Example

Connection Pool



Baciscally Connection Pool usage is to Avoid making and destroying the Connection object repeatedly.
Connection Pool is like keeping a door of home open instead of locking it and opening it all time whenever need to go Inside.

Connection Pool means Set of Connections which are cashed and shared.
So whenever a resource need a database communication then it will ask the connection pool for the connection and if free connection is available then it will get connection from the pool and will use it.  Once it done with the need of connection it will give the connection back to the Connection Pool, so it will be available for next time.

So here it will not require to create the connection object all the time whenever required. 
and creating and destroying connection object hits the performance of Application

Download following jar files

commons-dbcp.jar
commons-pool.jar
mysql-connector-java-version.n.n.n.jar

Example Code

package pool;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;

public class DataSourceEngine {

    private static DataSourceEngine     datasource;
    private BasicDataSource basicDataSource;

    private DataSource() throws IOException, SQLException, PropertyVetoException {
        basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("root");
        basicDataSource.setUrl("jdbc:mysql://localhost/SampleData");
       
        /* Below configurations are Optional. */
        basicDataSource.setMinIdle(1);
        basicDataSource.setMaxIdle(10);
        basicDataSource.setMaxOpenPreparedStatements(100);

    }

    public static DataSourceEngine getInstance() throws IOException, SQLException, PropertyVetoException {
        if (datasource == null) {
            datasource = new DataSourceEngine();
            return datasource;
        } else {
            return datasource;
        }
    }

    public Connection getConnection() throws SQLException {
        return this.basicDataSource.getConnection();
    }

}

===========
package pool;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DataSourceMain {

public static void main(String[] bag) {

Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        
        try {
            connection = DataSourceEngine.getInstance().getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT * FROM STUDENT");
             while (resultSet.next()) {
                 System.out.println("ROLL_NUMBER: " + resultSet.getString("ROLL_NUMBER"));
                 System.out.println("NAME: " + resultSet.getString("NAME"));
             }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
e.printStackTrace();
} catch (PropertyVetoException e) {
e.printStackTrace();
} finally {
            if (resultSet != null) {
            try {
            resultSet.close(); 
            }  catch (SQLException e) { }
            }
            if (statement != null) {
            try { 
            statement.close(); 
            } catch (SQLException e) { }
            }
            if (connection != null) {
            try { 
            connection.close(); 
            } catch (SQLException e) {}
            }
        }

}
}

Keep Visiting :)

Tuesday, September 23, 2014

Java code to Create log file and write logs in it

It s very simple code just set Environment Variable and run the program. It will create the log file and will write the outputs into the EngineLogs.log file




package filer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/*
 * Author : Raj Kirpalsinh
 * */
class Base{

private String path = null;

Base(String path){
this.path = path;
}

public boolean setStandardLogOutput() {

if(path == null) {
System.out.println("Sorry !! Path is null");
return false;
}

File stdLogDirPath = new File(path);

if(stdLogDirPath.exists()==false) {
System.out.println("Directory path "+path+ " does not exist. Creating the directory path.");
if(stdLogDirPath.mkdirs() == false) {
System.out.println("Could not create directory path : "+path);
return false;
}else {
System.out.println("Directory path created successfully : "+path);
}
}

if(stdLogDirPath.isDirectory()==false) {
System.out.println(path +" is not a directory");
return false;
}

File logFile = new File(path, "EngineLogs.log");
if(logFile.exists()==false) {
System.out.println("Log file "+logFile.getName()+ " does not exist");
boolean isFileCreated = false;
try {
isFileCreated = logFile.createNewFile();
if(isFileCreated == true) {
System.out.println("Log file "+logFile.getName()+ " created at path : "+path);
FileOutputStream fs = new FileOutputStream(logFile,true);
PrintStream ps = new PrintStream(fs); 
System.setOut(ps);
System.setErr(ps);
}else {
System.out.println("Error while creating file  ");
}
} catch (IOException e) {
System.out.println("Exception while creating the logfile. Reason: "+e.getMessage());
e.printStackTrace();
return false;
}

return true;
}
}

public class Engine extends Base {

Engine(String path){
super(path);
}

public static void main(String[] args) {
String ENGINE_HOME = System.getenv("ENGINE_HOME"); 
System.out.println(ENGINE_HOME);
Engine engine = new Engine(ENGINE_HOME);
boolean flag = engine.setStandardLogOutput();
if(flag == false) {
System.out.println("Error while setting the Eninge stardard logs output in a EngineLogs.log file");
}
System.out.println("--Begin--");
System.out.println("--Finish--");
}

}

Keep visiting :) 

How to Avoid NullPointerException ?

There are various ways to Avoid NullPointerException

1) if( null != objName ){ }


2) instead of .toString() method always use String.valueOf(objName);


3) Instead of of returning null collections object from the methods

    try to return empty objects
return Collections.EMPTY_SET;
return Collections.EMPTY_MAP;
return Collections.EMPTY_LIST;

4) while comparing two objects using the obj1.equals(obj2) method

   keep in mind that obj1 should be known and object2 should be unknown.
   means in the argument of .equals() method always pass the unknown object

  These are four simple basic ways. there are many more.


Keep Visiting :) 

  

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...