Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, 19 September 2013

Groovy - Putting object in a Map and iterating over it

import jxl.*
import jxl.write.*

//to read from excel
Workbook excelFile= Workbook.getWorkbook(new File("c:\\Testing\\test.xls"));
Sheet sheet = excelFile.getSheet(0)


//declaring map
def getTestDataMap = [:]
rows = sheet.getRows();
for( tc_row in 1..rows-1){
Cell testCase = sheet.getCell(0,tc_row);
Cell customerId = sheet.getCell(1,tc_row);
Cell productId = sheet.getCell(2,tc_row);
Cell productStatus = sheet.getCell(3,tc_row);
Cell propertyName = sheet.getCell(4,tc_row);
Cell propertyValue = sheet.getCell(5,tc_row);
String testCaseNumber = testCase.getContents();

getTestDataMap.put(testCaseNumber,new GetOperationBO(testCaseNumber: testCase.getContents(),customerIdData:customerId.getContents(),productIdData: productId.getContents(),productStatusData:productStatus.getContents(),propertyNameData:propertyName.getContents(),propertyValueData:propertyValue.getContents()))
}

excelFile.close()

// iterating
for ( e in getTestDataMap ) {
GetOperationBO getOperationBO = new GetOperationBO();
    getOperationBO.testCaseNumber = e.key
    getOperationBO = e.value

    log.info getOperationBO.testCaseNumber
  log.info getOperationBO.customerIdData
    log.info getOperationBO.productStatusData
}


class GetOperationBO {

String testCaseNumber
String customerIdData
String productIdData
String productStatusData
String propertyNameData
String propertyValueData
}

Tuesday, 17 September 2013

Reading/Writing from Excel in soap UI using groovy

Dowload jexcelapi_2_6_12 and put it in ext folder of soap ui .. .restart SOAP UI.. create one sample xls and paste the below code in soap ui...

import jxl.*
import jxl.write.*

//to read from excel
Workbook excelFile= Workbook.getWorkbook(new File("c:\\Testing\\myfile.xls"));
Sheet sheet = excelFile.getSheet(0)
Cell a1 = sheet.getCell(0,0)
log.info a1 // getCell(row,column) -- place some values in myfile.xls
Cell b2 = sheet.getCell(1,1)  // then those values will be acessed using a1, b2 & c3 Cell.
Cell c2 = sheet.getCell(2,1)
String s1 = c2.getContents();
log.info s1
excelFile.close()

// To write in excel
WritableWorkbook workbook1 = Workbook.createWorkbook(new File("c:\\Testing\\myfile.xls"))
WritableSheet sheet1 = workbook1.createSheet("Worksheet Number 1", 0)
log.info(sheet1.isHidden())
Label label = new Label(0, 1, "some data to put");
sheet1.addCell(label);
workbook1.write()
workbook1.close()


Disclaimer-- code copied from various blogs :)

Monday, 16 September 2013

Calling Java method from jar in soap UI:

1. Put the required jars in soapUI-3.5\bin\ext folder...
2. First restart SOAP UI and then execute the  code snippet....


-- sample  code---
import com.ssh.*

// Class present in the jar which is loaded from ext
GetLogs transactionLog = new GetLogs();

// sample method to call
transactionLog.getLogs("sample string");

------------------------------------

When I was calling java method from soap UI.. initially I was getting null pointer exception for few minutes I was wondering how to go forward as there were no logs displayed.. then as we know to debug any application log is the solution..In case if anyone is getting any exception or unexpected response we can always check soapui and soapui-errors files in soapUI-3.5\bin .... Hope it helps....

Thursday, 12 September 2013

Java Example to ssh to Unix box

I looked around for the sample code to connect to the unix box... I could find lot of examples but very few with private keys...and  found bit difficult to understand.
After spending some time.. I could found few examples to suit my requirement... so thought it might be helpful for someone else also...
I Referred conversion of private key from this link - http://www.tuxify.de/?p=519
Make sure you save the keys in .ssh format..

Here it goes---

package com.ssh;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;



public class ConnectionTest {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();

KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance("RSA");
keyPairGenerator.initialize(2048, new SecureRandom());
// PrivateKey privateKey =
// keyPairGenerator.genKeyPair().getPrivate();

StringWriter writer = new StringWriter();
// PEMWriter pemWriter = new PEMWriter(writer);

// pemWriter.writeObject(privateKey);

String privateKeyStr = writer.toString();

String user = "urusername";
String host = "ip address of the box u r trying to connect";
// ogre
// String host = "10.200.169.202";
int port = 22;
String privateKey = "key in ssh format";
String passphrase = "ur key's passphrase";
// jsch.addIdentity(privateKey);
jsch.addIdentity(privateKey, passphrase);

System.out.println("identity added ");
// addIdentity(String,bytearrayof ssh format file,null,byte array of
// passphrase file)
Session session = jsch.getSession(user, host, port);
System.out.println("session created. " + session);

java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword("ur password");
System.out.println("before session connect");
session.connect();
System.out.println("session connected.....");

Channel channel = session.openChannel("shell");
channel.setInputStream(null);
channel.setOutputStream(null);

InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();

((ChannelShell) channel).setPtyType("vt102");
channel.connect();

byte[] tmp = new byte[1024];

out.write(("ls" + ";exit").getBytes());
out.write(("\n").getBytes());
out.flush();

while (true) {

while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
// System.out.println("[debug] breaking at i < 0");
break;
}
String buffer = new String(tmp, 0, i);
String results = "";
// results.add(buffer);
// System.out.println("[debug]" + buffer);

System.out.println("result - " + buffer);
if (buffer.contains("REMOTE JSH COMMAND FINISHED")) {
System.out.println("[debug] breaking at finished");
break;
}
}
if (channel.isClosed()) {
// System.out.println("[debug] breaking at isClosed");
in.close();
break;
}
}
channel.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}

return;
}

// commented sftp code ...

/*
* Channel channel = session.openChannel("sftp");
* channel.setInputStream(System.in); channel.setOutputStream(System.out);
* channel.connect(); System.out.println("shell channel connected....");
*
* ChannelSftp c = (ChannelSftp) channel;
*
* String fileName = "D:/localfile.txt/test.txt";
* c.put(fileName, "./in/"); c.exit(); System.out.println("done");
*
* } catch (Exception e) { System.err.println(e); }
*/

}

Hope it helps :)


To copy the file and then delete from the unix box.. following code can be used--
Here, the session is the same variable which is created in the above code.. and logfileName is the file which needs to be copied...

public static void getLogBySftp(Session session, String  logFileName) throws JSchException, SftpException
{
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in); channel.setOutputStream(System.out);
channel.connect(); System.out.println("shell channel connected....");


//Channel channel = session.openChannel("sftp");
       ChannelSftp sftpChannel = (ChannelSftp) channel;
       System.out.println("Directory:" + sftpChannel.pwd());
      // sftpChannel.cd("remoteDirectory/");
       System.out.println("Directory after cd:" + sftpChannel.pwd());
       //sftpChannel.get( transactionId+".xml");
     
       System.out.println("xml file name  - "+logFileName);
       sftpChannel.get(logFileName, logFileName);

       sftpChannel.rm(logFileName);
     
       sftpChannel.exit();
}

Tuesday, 17 August 2010

Final is not final anymore in java 1.5



I read somewhere about this concept.. This is very interesting ..  

Playing with your sanity - Strings

Have a look at the following code:
public class MindWarp {
  public static void main(String[] args) {
    System.out.println(
      "Romeo, Romeo, wherefore art thou oh Romero?");
  }
  private static final String OH_ROMEO =
    "Romeo, Romeo, wherefore art thou oh Romero?";
  private static final Warper warper = new Warper();
}
If we are told that the class Warper does not produce any visible output when you construct it, what is the output of this program? The most correct answer is, "you don't know, depends on what Warper does". Now THERE's a nice question for the Sun Certified Java Programmer Examination.
In my case, running "java MindWarp" produces the following output
C:> java MindWarp 
Stop this romance nonsense, or I'll be sick
And here is the code for Warper:
import java.lang.reflect.*;

public class Warper {
  private static Field stringValue;
  static {
    // String has a private char [] called "value"
    // if it does not, find the char [] and assign it to value
    try {
      stringValue = String.class.getDeclaredField("value");
    } catch(NoSuchFieldException ex) {
      // safety net in case we are running on a VM with a
      // different name for the char array.
      Field[] all = String.class.getDeclaredFields();
      for (int i=0; stringValue == null && i
        if (all[i].getType().equals(char[].class)) {
          stringValue = all[i];
        }
      }
    }
    if (stringValue != null) {
      stringValue.setAccessible(true); // make field public
    }
  }
  public Warper() {
    try {
      stringValue.set(
        "Romeo, Romeo, wherefore art thou oh Romero?",
        "Stop this romance nonsense, or I'll be sick".
          toCharArray());
      stringValue.set("hi there", "cheers !".toCharArray());
    } catch(IllegalAccessException ex) {} // shhh
  }
}
How is this possible? How can String manipulation in a completely different part of the program affect our class MindWarp?
To understand that, we have to look under the hood of Java. In the language specification it says in §3.10.5:
"Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern."
The usefulness of this is quite obvious, we will use less memory if we have two Strings which are equivalent pointing at the same object. We can also manually intern Strings by calling the intern() method.
The language spec goes a bit further:
  1. Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
  2. Literal strings within different classes in the same package represent references to the same String object.
  3. Literal strings within different classes in different packages likewise represent references to the same String object.
  4. Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
  5. Strings computed at run time are newly created and therefore distinct.
  6. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.
This means that if a class in another package "fiddles" with an interned String, it can cause havoc in your program. Is this a good thing? (You don't need to answer ;-)
Consider this example
public class StringEquals {
public static void main(String[] args) {
  System.out.println("hi there".equals("cheers !"));
}
private static final String greeting = "hi there";
private static final Warper warper = new Warper();
}
Running this against the Warper produces a result of true, which is really weird, and in my opinion, quite mind-bending. Hey, you can SEE the values there right in front of you and they are clearly NOT equal!
BTW, for simplicity, the Strings in my examples are exactly the same length, but you can change the length quite easily as well.
Last example concerns the HashCode of String, which is now cached for performance reasons mentioned in "Java Idiom and Performance Guide", ISBN 0130142603. (Just for the record, I was never and am still not convinced that caching the String hash code in a wrapper object is a good idea, but caching it in String itself is almost acceptable, considering String literals.)
public class CachingHashcode {
  public static void main(String[] args) {
    java.util.Map map = new java.util.HashMap();
    map.put("hi there", "You found the value");
    new Warper();
    System.out.println(map.get("hi there"));
    System.out.println(map);
  }
  private static final String greeting = "hi there";
}
The output under JDK 1.3 is:
You found the value
{cheers !=You found the value}
Under JDK 1.2 it is
null
{cheers !=You found the value}
This is because in the JDK 1.3 SUN is caching the hash code so if it once calculated, it doesn't get recalculated, so if the value field changes, the hashcode stays the same.
Imagine trying to debug this program where SOMEWHERE, one of your hackers has done a "workaround" by modifying a String literal. The thought scares me.
[Heinz: Author's note: the comment below on using "final" to solve this problem is not correct. Firstly, you cannot make arrays immutable, which is a design flaw in Java, so you could still change the content of the array even if the handle were final. Secondly, in JDK 1.5, you can set final fields using reflection. See Java 5 - "final" is not final anymore and for a similar contortion with autoboxing see Mangling Integers.]
There is of course a small keyword that would have stopped this problem, namely "final". I got into the habit a few months ago to make all my data members final where possible, and it has paid off more than once. Surprisingly, the char array in String is not final.
Consider the following example code:
public class Bla {
  private char[] c1 = "hello".toCharArray();
  private final char[] c2 = "bye".toCharArray();
  public String toString() {
    return c1 + ", " + c2;
  }
}

import java.lang.reflect.*;

public class BlaTest {
  private static Field c1;
  private static Field c2;
  static {
    try {
      c1 = Bla.class.getDeclaredField("c1");
      c1.setAccessible(true);
      c2 = Bla.class.getDeclaredField("c2");
      c2.setAccessible(true);
    } catch(NoSuchFieldException ex) { }
  }
  public static void main(String[] args) {
    Bla bla = new Bla();
    try {
      c1.set(bla, "mutatedc1".toCharArray());
      c2.set(bla, "mutatedc2".toCharArray());
    } catch(IllegalAccessException ex) {
      ex.printStackTrace();
    }
    System.out.println(bla);
  }
}
When I run my program, I can quite happily change c1, but when I try to change c2 I get an exception. String has no reason for value to be non-final, so it should be final. If you have contacts at SUN, please forward them this newsletter and ask them to make value final. It might stop some nasty Java viruses from completely messing up the JVM.

Tuesday, 1 December 2009

To calculate size of an object in java

In one of mine project work I was required to calculate the size of an object the best way that I found is this :
when I started r&d for this topic I came to know that in java 1.5 there is an api introduced i.e instrumentation agent by using that we have a premain method which is called by the JVM even before the void main. so by storing the information of objects in jvm and then calculating the size was the core concept to know the memory utilization of an object. I know theortically it is very easy to write. Well I wont disappoint you .. practically as well :) here is the step by step approach to calculate the memory consumed by an object in your application :

First thing that is required is to have a class in your project which contains premain method the sample class is shown below:-


package com.memory;


import java.lang.instrument.Instrumentation;


public class MyAgent {
  static Instrumentation inst;
         
         /** initializes agent */
         public static void premain(String agentArgs, Instrumentation instP) {
                 inst = instP;           
         }
         
}


Second thing to do is to keep in mind that this application has to be run on command prompt and you have to make a jar of your project which will be having above mentioned class.  class name and package  are your choices.
While making jar of your project you have to write this line (Premain-Class: ****.rc.postpay.controller.MyAgent) in your manifest file. This is mandatory the class name and package name varies according to your comfort and requirement.

well half of the work is done now next task is to recusively calculate the size . For that use the code shown below:

  /**
          * Returns object size without member sub-objects.
          * @param o object to get size of
          * @return object size
          */
         public static long sizeOf(Object o) {
                 if(inst == null) {
                         throw new IllegalStateException("Can not access instrumentation environment.\n" +
                                         "Please check if jar file containing SizeOfAgent class is \n" +
                                         "specified in the java's \"-javaagent\" command line argument.");
                 }
                 return inst.getObjectSize(o);
        }
        
         /**
          * Calculates full size of object iterating over
         * its hierarchy graph.
          * @param obj object to calculate size of
          * @return object size
          */
         public static long fullSizeOf(Object obj) {
                 Map visited = new IdentityHashMap();
                 Stack stack = new Stack();              long result = internalSizeOf(obj, stack, visited);              while (!stack.isEmpty()) {                result += internalSizeOf(stack.pop(), stack, visited);              }              visited.clear();              return result;          }                                 private static boolean skipObject(Object obj, Map visited) {              if (obj instanceof String) {                // skip interned string                if (obj == ((String) obj).intern()) {                  return true;                }              }              return (obj == null) // skip visited object                  || visited.containsKey(obj);           }      private static long internalSizeOf(Object obj, Stack stack, Map visited) {              if (skipObject(obj, visited)){                  return 0;              }              visited.put(obj, null);                            long result = 0;              // get size of object + primitive variables + member pointers               result += MyAgent.sizeOf(obj);                           // process all array elements              Class clazz = obj.getClass();              if (clazz.isArray()) {                if(clazz.getName().length() != 2) {// skip primitive type array                    int length =  Array.getLength(obj);                            for (int i = 0; i < length; i++) {                                   stack.add(Array.get(obj, i));                        }                 }                       return result;             }                            // process all fields of the object              while (clazz != null) {                Field[] fields = clazz.getDeclaredFields();                for (int i = 0; i < fields.length; i++) {                  if (!Modifier.isStatic(fields[i].getModifiers())) {                    if (fields[i].getType().isPrimitive()) {                            continue; // skip primitive fields                    } else {                      fields[i].setAccessible(true);                      try {                        // objects to be estimated are put to stack                        Object objectToAdd = fields[i].get(obj);                        if (objectToAdd != null) {                                                  stack.add(objectToAdd);                        }                      } catch (IllegalAccessException ex) {                           assert false;                       }                    }                  }               }               clazz = clazz.getSuperclass();              }              return result;           }  } Put all these methods in MyAgent class as these methods needs the instance of Intrumentation agent.Call the method [ MyAgent.fullSizeOf(o);] where o is an object for whom every one is concerned. to write in a file or to print on the console you can write custom methods like the one shown below. You can call this below mentioned method wherever you need to know the size of your object and this method will print the size on console and write in file as well.     public static void measureSize(Object o, String filename)     {         System.out.println("inside measure size");         long sizeInBytes = MyAgent.fullSizeOf(o);         double sizeInKB = (sizeInBytes / 1024);         double sizeInMB = (sizeInKB / 1024);         try         {             // Create file             FileWriter fstream = new FileWriter("c://MemoryUsageForReferenceData", true);             BufferedWriter out = new BufferedWriter(fstream);             out.write(filename + "," + sizeInKB + "," + sizeInMB +"\n");             // Close the output stream             out.close();         }         catch (Exception e)         {// Catch exception if any             System.err.println("Error: " + e.getMessage());         }         // long size = MyAgent.getObjectSize(o);         /*          * System.out.printf("size =%d", size);          */         // int mapSize = o.size();         // System.out.println("map size" + mapSize);         System.out.println("size --- " + sizeInKB);     } Well we are almost done . The only thing remaining is to run this application on command prompt. Firstly I will summarize then we will run. Make one class Like My Agent put all the methods which are shown below put this class in your project and make the jar having manifest file which contains [Premain-Class: uk.co.o2.rc.postpay.controller.MyAgent]  package and class name depends on you premain-class is mandatory dont play with that. Thats it we are done now open your command prompt and run your jar by this command. Set all the classpath that you need for your project . Then execute this command java  - javaagent:[yourJar name] [the class name which contains the main Method] for example : java -javaagent:c:/memoryAgent.jar com.memoryagent.Test Done :) please post queries for anything confusing/wrong