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