Spring Web Services 2 Cookbook
Paperback: 322 pages
Publisher: Packt Publishing (May 13, 2012)
Language: English
ISBN-10: 1849515824
ISBN-13: 978-1849515825
Books is available at Amazon.com

Spring Web Services 2 Cookbook

This is very nice book on Spring Web Services.
Problem Statement:
We need to display lights and play sounds for different activities in IT Departments.
Example: Specific production server went down. Or Build failed. Or Too much traffic on network, got email from xyz….etc
Solution 1:
DelCom Product: This comes with DLL and we need to write Java JNI.
http://www.delcomproducts.com/products_USBLMP.asp
Solution 2:
Arduino Micro Controller
http://joe.blog.freemansoft.com/2011/04/extreme-feedback-aka-status-lights-das.html
http://arduino.cc/en/
http://cweiske.de/tagebuch/usblamp-monitoring.htm
Writing simple USB Driver: http://www.linuxjournal.com/article/7353
Hudson Build Lights: http://www.rallydev.com/engblog/tag/indicator-lights/
-o-
Problem Statement: We have one application running in 10 servers. How to grep for exception or key word in all of them with one single command?
Solution: Use JSch and pass the command to all 10 servers and print the data on java console.
Download JSch jar from following site and put it in classpath.
http://www.jcraft.com/jsch/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class JavaTelnetExample {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession("userid", "hostname", 22);
session.setPassword("password");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("==>" + executeCommand(session, "date"));
System.out.println("==>" + executeCommand(session, "ls"));
System.out.println("==>" + executeCommand(session, "who"));
System.out.println("==>" + executeCommand(session, "tail -50 /path/abcd.log"));
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String executeCommand(Session session, String command)
throws Exception {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.setInputStream(null);
channel.setErrStream(System.err);
channel.connect();
InputStream in = channel.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line + '\n');
}
channel.disconnect();
return sb.toString();
}
}
Problem statement: JSPs are not working in embedded Jetty.
http://docs.codehaus.org/display/JETTY/Jsp+Configuration
Add following to web.xml file
<servlet id="jsp">
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>logVerbosityLevel</param-name>
<param-value>DEBUG</param-value>
</init-param>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>keepgenerated</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspf</url-pattern>
<url-pattern>*.jspx</url-pattern>
<url-pattern>*.xsp</url-pattern>
<url-pattern>*.JSP</url-pattern>
<url-pattern>*.JSPF</url-pattern>
<url-pattern>*.JSPX</url-pattern>
<url-pattern>*.XSP</url-pattern>
</servlet-mapping>
Add following to support JSP with Java 1.6
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.1.26</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>6.1.26</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api-2.5</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jsp-2.1</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jsp-api-2.1</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.1</version>
</dependency>
import java.io.File;
import java.io.FileReader;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
/**
* Add these files in classpath
* maven-artifact-2.0.6.jar,maven-core-2.0.6.jar,
* maven-model-2.0.6.jar,maven-project-2.0.6.jar,
* plexus-utils-2.0.7.jar
*
* @author polimeb
*
*/
public class ParseMavenPOM {
/**
* @param args
*/
public static void main(String[] args) {
String fileName = "c:/project/abcd/pom.xml";
try {
Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
File pomfile = new File(fileName);
reader = new FileReader(pomfile);
model = mavenreader.read(reader);
MavenProject project = new MavenProject(model);
System.out.println(project.getVersion());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
We need to make sure that all .properties, xml files are are in same encoding. Other wise app servers give trouble in starting and it is difficult to find out.
Note: Download and add jar in classpath from http://site.icu-project.org/
import java.io.File;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
/**
* This program provides file encoding for given file.
*
* Make sure that all files are using same encoding as parameter passed to JVM.
*
* http://userguide.icu-project.org/conversion/detection#TOC-CharsetDetector
*
*/
public class EncodingUtil {
/**
* @param args
*/
public static void main(String[] args) {
String PATH = "e://folder_name//";
try {
printFileEncoding(PATH + "a.properties");
printFileEncoding(PATH + "b.properties");
printFileEncoding("D://path2//asdf.xml");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void printFileEncoding(String fileName) {
try {
File file = new File(fileName);
file = new File(fileName);
byte fileContent[] = new byte[(int) file.length()];
checkEncoding(fileName, fileContent);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void checkEncoding(String fileName, byte[] byteData) {
CharsetDetector detector;
CharsetMatch match;
detector = new CharsetDetector();
detector.setText(byteData);
match = detector.detect();
StringBuffer sbData = new StringBuffer();
sbData.append("fileName==>").append(fileName);
sbData.append(" Confidence==>").append(match.getConfidence());
sbData.append(" Encoding==>").append(match.getName());
System.out.println(sbData.toString());
}
}
Logging is as old as cave man writing on walls in Java community.
After using Log4j, SLF4J, today I got a opportunity to start using Logback.
It is very easy to use and configure. The features I liked much are as follows.
1. Default no configuration file required.
2. Option to merge different configuration files to one. (Inclusion of properties files)
3. Option to enable them quickly to check on web in web applications.
4. Supporting groovy style.
5. Better documentation. http://logback.qos.ch/manual/introduction.html
6. Developed by Log4j author. Assuming that he knows all the problems in Log4j and improved Logback a lot. Also a trusted source to use library.
for more check Logback site http://logback.qos.ch/index.html .
Only thing I didn’t like is the name “LogBack”.
-o-
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This shows how to generate meaningful random id for application. If we need
* to work in clustered environment, we need to add host name or IP address of
* system.
*
* @author Bhavani P Polimetla
* @since May-03-2011
*
*/
public class TimeStampID {
public static void main(String[] args) {
Format formatter = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss:SSS a");
System.out.println(formatter.format(new Date()));
System.out.println("Use as random meaningful ID==>" + getTimeStampID());
System.out.println("Get Unique ID==>" + getUniqueSystemInfo() + ":"
+ getTimeStampID());
}
public static String getTimeStampID() {
Format formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return formatter.format(new Date());
}
public static String getUniqueSystemInfo() {
try {
InetAddress thisIPConfig = InetAddress.getLocalHost();
// System.out.println("Host Name==>"+thisIPConfig.getHostName());
// System.out.println("IP Address==>"+thisIPConfig.getHostAddress());
return thisIPConfig.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "";
}
}
In multithreaded environment, add thread id to make it more unique.
-o-
Output:
2011-05-03,13:46:36:673 PM
Use as random meaningful ID==>20110503134636673
Get Unique ID==>112.243.32.43:20110503134636689
This code is used for quick testing purpose.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* This program demonstrates consuming web service using Apache HTTPClient and SOAP message.
* Reference: http://www.webservicex.net/stockquote.asmx?op=GetQuote
* ClassPath: Keep these two files in class path: commons-httpclient-3.0.1.jar, commons-codec-1.4.jar
* @author Bhavani P Polimetla
* @since April-27-2011
*/
public class WSClient {
public static void main(String args[]) {
HttpClient httpClient = new HttpClient();
httpClient.getParams()
.setParameter("http.useragent", "Web Service Test Client");
BufferedReader br = null;
String data = "<?xml version=\"1.0\" encoding=\"utf-8\"?> "
+ "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"> "
+ "<soap12:Body> "
+ "<GetQuote xmlns=\"http://www.webserviceX.NET/\"> "
+ "<symbol>INFY</symbol> " + "</GetQuote> "
+ "</soap12:Body> </soap12:Envelope>";
PostMethod methodPost = new PostMethod(
"http://www.webservicex.net/stockquote.asmx?op=GetQuote");
methodPost.setRequestBody(data);
methodPost.setRequestHeader("Content-Type", "text/xml");
try {
int returnCode = httpClient.executeMethod(methodPost);
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.out
.println("The Post method is not implemented by this URI");
methodPost.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(methodPost
.getResponseBodyAsStream()));
String readLine;
while (((readLine = br.readLine()) != null)) {
System.out.println(readLine);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
methodPost.releaseConnection();
if (br != null)
try {
br.close();
} catch (Exception fe) {
fe.printStackTrace();
}
}
}
}
Output:
<!--?xml version="1.0" encoding="utf-8"?--><?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetQuoteResponse xmlns="http://www.webserviceX.NET/"><GetQuoteResult><StockQuotes><Stock><Symbol>INFY</Symbol><Last>65.99</Last><Date>4/27/2011</Date><Time>3:46pm</Time><Change>-0.27</Change><Open>66.25</Open><High>66.30</High><Low>65.31</Low><Volume>1689441</Volume><MktCap>37.701B</MktCap><PreviousClose>66.26</PreviousClose><PercentageChange>-0.41%</PercentageChange><AnnRange>53.28 - 77.92</AnnRange><Earns>2.62</Earns><P-E>25.29</P-E><Name>Infosys Technolog</Name></Stock></StockQuotes></GetQuoteResult></GetQuoteResponse></soap:Body></soap:Envelope>