Thursday, September 11, 2014

Little About Heap Memory

1) Heap is a run time data area from which memory for all class Instances and arrays is allocated

2) Heap is created at Virtual Machine Startup

3) Heap storage is reclaimed by the Garbage Collector

4) Heap may be of fixed size or may be expanded as required

5) Heap memory does not need to be Contiguous

6) If a program need More heap memory than the automatic memory management system provides then Java Virtual Machine throws OutOfMemoryError

Monday, September 8, 2014

SIMPLE JAVA CODE ABOUT FACTORY DESIGN PATTERN

/*
Creational Patterns - Factory Pattern
Factory of what? Of classes.
In simple words, if we have a super class and n sub-classes,
and based on data provided,
we have to return the object of one of the sub-classes,
we use a factory pattern.
*/
class Person {

public String name;
private String gender;

public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}

public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}

}


class Male extends Person {
  public Male(String fullName) {
setName(fullName);
setGender("Male");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Mr. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}
}


class Female extends Person {
  public Female(String fullName) {
setName(fullName);
setGender("Female");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Ms. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}

}

class DPFactory{
  public static void main(String args[]) {

DPFactory factory = new DPFactory();
Person  person = factory.getPerson(args[0], args[1]);
System.out.println(person);

}
public Person getPerson(String name, String gender) {
if (gender.equals("M")){
return new Male(name);
}else if(gender.equals("F")){
return new Female(name);
}else{
return null;
}
}
}

JAVA BlockingQueue SIMPLE CODE

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class Consumer implements Runnable{

    protected BlockingQueue queue = null;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            System.out.println("Taken:"+queue.take());
            System.out.println("Taken:"+queue.take());
            System.out.println("Taken:"+queue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Producer implements Runnable{

    protected BlockingQueue queue = null;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            queue.put("1");
            System.out.println("Put:1");
            Thread.sleep(1000);
         
            System.out.println("Put:220");
            queue.put("220");
            Thread.sleep(1000);
         
            System.out.println("Put:38");
            queue.put("38");
            Thread.sleep(1000);          
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class BlockingQueueFlight {

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

        BlockingQueue queue = new ArrayBlockingQueue(1024);

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();

        Thread.sleep(4000);
    }
}

CODE OF BATCH OPERATION IN JAVA



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class CommitWriteBatchTestFlight {

public static void main(String[] dataTrays){
System.out.println("--BEGIN--");
String commitCommand = "COMMIT WORK WRITE BATCH";

final String TBL_NAME = "PLAYERS";
final String COL_ID = "ID";
final String COL_NAME = "NAME";
final String COL_TEAM = "TEAM";
final String COL_TOTAL_RUNS = "TOTAL_RUNS";

String createTableQuery = "CREATE TABLE PLAYERS ( " +
"ID INT, " +
"NAME VARCHAR(255), " +
"TEAM VARCHAR(255), " +
"TOTAL_RUNS VARCHAR(255)" +
")";

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@192.168.8.87:1521:aaadb","netvertextrunk","netvertextrunk");

Statement stmt = connection.createStatement();
stmt.execute(createTableQuery);
System.out.println("Table create Successfully");
stmt.close();

PreparedStatement commitPrepStmt = connection.prepareStatement(commitCommand);
PreparedStatement prepStmt = connection.prepareStatement("INSERT INTO PLAYERS (ID, NAME, TEAM, TOTAL_RUNS) VALUES (?, ?, ?, ?)");

long startTime = System.currentTimeMillis();

for(int i=1; i<=11; i++){
prepStmt.setInt(1, i);
prepStmt.setString(2, "Player"+i);
prepStmt.setString(3, "Team"+i);
prepStmt.setString(4, "100"+i);
prepStmt.executeUpdate();
}
prepStmt.close();

//connection.commit();
//System.out.println("Execution Time: "+(System.currentTimeMillis()-startTime)+" ms");

commitPrepStmt.executeUpdate();
System.out.println("Execution Time: "+(System.currentTimeMillis()-startTime)+" ms");

connection.close();

} catch (Exception e) {
System.out.println("Error while executing preparedstatement, Reason: "+e.getMessage());
}

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

JAVA ARRAY UTILITY CLASS

package com.raj.utility;

import java.util.ArrayList;

import java.util.List;


public class ArrayUtil {

    /
    public static boolean isNullOrEmpty(T[] array) {
        return (array == null || array.length == 0);
    }
 
 
    public static boolean notNullOrEmpty(T[] array) {
        return !isNullOrEmpty(array);
    }
 
 
    public static String[] trim(String[] array) {
        if (array == null) {
            return null;
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = array[i].trim();
        }
        return array;
    }
 
    public static List toList(String[] array) {
   
        java.util.List list = new ArrayList(array.length);
        for (String entry : array) {
            list.add(entry);
        }
        return list;
    }

    public static String[] asArray(List list) {
        if (list == null) return null;
        return list.toArray(new String[0]);
    }
}

JAVA CODE TO WRITE LOGS IN PARTICULAR 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--");
}

}

JAVA UTILITY METHODS FOR ALL

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------");
     }
}

COPY PARTICULAR ROW OF A TABLE AND APPEND IT AT THE END OF TABLE

function copyAndAppend(id){
$(“#”+id+” tr:last”).after(“
” + $(“#serviceRow”).html() + “
“);
}
Explanation:
1) $(“#serviceRow”).html() : I will copy all the inner content of an element having id = “serviceRow”
2) $(“#”+id+” tr:last”) : I have used ‘id’ variable, its value will be the id of a table, and “tr:last”.after() will
add the new row at the end of the table