Thursday 20 December 2012

SoapUI & Groovy Script - Tips

I've been working on a SoapUI project for the past few months.
I'm novice to SoapUI & web services.. Here are few tips which I think would be helpful for learners on this area.
 SoapUI is used to mimic the web server responses. Based on the request you can have a response.
 In SoapUI there are many ways you can dispatch a response. Scripting is most versatile and complex way to do that.

Usually we can do the scripting using groovy. But you may handle the same using your java code as well. However using Groovy & SoapUI APIs will reduce the coding much.

Groovy Scripting

There are few inbuilt variables available in SoapUI. They are log, mockRequest, context.

1) To define a variable

 def reqHolder = new XmlSlurper().parseText(mockRequest.requestContent);
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);
def holderRequest = groovyUtils.getXmlHolder(mockRequest.requestContent);
def responseLOB = reqHolder.Body.VerificationRequest.LOB;


2) How to declare a name space with a request

 holderRequest.declareNamespace('ns', 'http://www.xyz.xx.ic/verificationprocess/2');

3) To get a value from node.
 
 def idValue = holderRequest.getNodeValue("//ns:ID");

 getNodeValue() and [] are  for same purpose. But the latter is for returning array of values.

4) To see the number of items with same node, we can use getNodeValues().

def idValue = holderRequest.getNodeValue("//ns:ID");
def allIDFiles = holderRequest.getNodeValues("//ns:ID");


and then check the size of allIDFiles variable.

if (allIDFiles.length > 1) {
}


 5) To iterate through a list of files stored in your local direcrtory and compare the name of the file with the file name in the request using groovy script.

new File( folderName ).eachFile() { file ->
                if( file.name =~ /.xml/ ) {                   
                    if (file.name == "$responseValueWithFileName") {
                        log.info "Match Found for ID : "+"$responseValue";
                        actual = "$folderName"+"\\"+"$responseValueWithFileName"
                        context.content = new File("$actual").text;                                                              
                    }
                 }
             }






















Disclaimer:The information given in this blog are based on my coding experience. I am not assuring that the solutions provided here would be suitable for what you are looking :-)Just don't want to dirty my hands...

Monday 23 April 2012

Simple MVC Project.

This is a simple MVC project. This application uses the following technologies.

1. View

a. JSP
b. JavaScript

2. Model

a. Java DTO
b. Java Classes to interact with database

3. Controller

a. Servlet
----------------------------------------------------------------------------
This is a simple Add/Delete/Update/View records into a table in DB2.

Step 1 : Create the home.jsp. This JSP is the main JSP, which will have the records and options for delete and update and add links. The Screen will look like this.

Add New Music
Music NameYear Edit Delete

No Record Avaliable

Step 2: Create JSP for Adding new record. ( When user clicks on the Add New Music link in above screen)

The Screen will look like this.


Name
Year


Step 3: Create servlet to control the flow from JSP to the back end.

package org.test.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class AddServlet
*/
@WebServlet("/add")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String path ="/music";
RequestDispatcher dispater = getServletContext().getRequestDispatcher(path);
dispater.forward(request, response);
//response.sendRedirect(path);
}

}

Step3 : Create main servlet.

package org.test.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.test.dto.Album;

/**
* Servlet implementation class MusicServlet
*/
@WebServlet("/music")
public class MusicServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path ="/Home.jsp";
RequestDispatcher dispater = getServletContext().getRequestDispatcher(path);
ArrayList list = new ArrayList();
Album album = new Album();

album.setName("XYZ");
album.setYear("1977");
list.add(album);
Album album1 = new Album();
album1.setName("ABCD");
album1.setYear("1977");
list.add(album1);
request.setAttribute("list", list);
dispater.forward(request, response);
}

}

This will complete the Adding a new record into the table. The code for DB2 connectivity is written below. This needs to be integrated in the above code.

/**
* ConnectDB2.java
*/
package com.javaworkspace.connectdb2;

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

/**
* @author www.javaworkspace.com
*
*/
public class ConnectDB2 {
public static void main(String[] args) {
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;

try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection(
"jdbc:db2://localhost:5021/EMPLOYEE", "username",
"password");
statement = connection.createStatement();
resultSet = statement
.executeQuery("SELECT EMPNAME FROM EMPLOYEEDETAILS");
while (resultSet.next()) {
System.out.println("EMPLOYEE NAME:"
+ resultSet.getString("EMPNAME"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

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

Friday 16 March 2012

Interview Questions

1. what is finalize & finally?
2. What is serializable i/f? - marker
3. what are string pools handled in java?
4. what is singleton classes?
5. what are hibernate sessions?
6. what is difference between jdk1.4 & 1.5, 1.6?
7. what is spring IoC?
8. What is MVC?
9. Why to use DAO?
10. Give an example of final class in java?
11. what is AGILE?
11. What is difference between eXtreame programming & TDD?
12. what is design pattern?
13. what are constructors & primitive data types in Java?
14. what are normalizations?
15. what is garbage collection & how to call?
16. what is denormalization?
17. what is method overloading & overriding?
18. what is JDBC?why?
19. What are Strem in Java?
20. What are the threading methods?
21. why to use synchization?

Thursday 5 January 2012

Interview questions

These are few interview questions asked. The questions are based on Java and non technical. Some of the questions seems to be very simple and staight forward.

1. what is the difference between comments in java

Ans: 3 types of comments in java

a. // - which is single line comment
b. /* */ - which is to add a comment of more than one line, we can precede our comment using/*
c. /** */ -
multiple line comments. Used for documentation purpose.

2. when there is a problem with the application, as a developer where we need to look at.

Ans : error logs and application server log files

3. How do you avoid deadlocks in a multithreaded enviornment?

Ans : first approach try to avoid synchronized where ever possible. If it is unavoidable, then code in such way that each thread should get lock & unlock in the same order or squence.

4.
Write a Java program that:

- inputs a String from a user. Expect the String to contain spaces and alphanumeric characters only.
- capitalizes all first letters of the words in the given String.
- preserves all other characters (including spaces) in the String.
- displays the result to the user.

Answer : *
Approach : I have followed a simple approach. However there are many string utilities available
* for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)

/*****************************************************************************/
public static void main(String[] args) throws IOException{
System.out.println("Input String :\n");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String inputString = in.readLine();
int length = inputString.length();
StringBuffer newStr = new StringBuffer(0);
int i = 0;
int k = 0;
/* This is a simple approach
* step 1: scan through the input string
* step 2: capitalize the first letter of each word in string
* The integer k, is used as a value to determine whether the
* letter is the first letter in each word in the string.
*/

while( i < length){
if (Character.isLetter(inputString.charAt(i))){
if ( k == 0){
newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
k = 2;
}//this else loop is to avoid repeatation of the first letter in output string
else {
newStr = newStr.append(inputString.charAt(i));
}
} // for the letters which are not first letter, simply append to the output string.
else {
newStr = newStr.append(inputString.charAt(i));
k=0;
}
i+=1;
}
System.out.println("new String ->"+newStr);
}
}
/*****************************************************************************/

5. How to reverse a string?

InputStreamReader inst = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inst);
StringBuffer input = new StringBuffer(in.readLine());
System.out.println("Input String-->"+input);
System.out.print("reverse String-->");
System.out.print(input.reverse());

6. Palindrome program.

InputStreamReader instr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(instr);
StringBuffer input = new StringBuffer(in.readLine());
StringBuffer reverseStr = new StringBuffer(input.reverse());
String inStr = input.toString().trim();
String outStr = reverseStr.toString().trim();
System.out.println(reverseStr);
if (inStr.equals(outStr)) {
//if (input.length() == reverseStr.length()) {
System.out.println("Palindrome");
//}
} else {
System.out.println("not Palindrome");
}

7. How does equals() method differs for String and StringBuffer classes?

String.equals() compares the 2 strings whereas StringBuffer.equals will return true only if compared with itself.

for comparision of strings we must use String.euqals() method or convert the StringBuffer to String and then compare.