Archive

Archive for the ‘Java’ Category

CXF Raw SOAP Envelope via Interceptor

November 3rd, 2009 3 comments

CXF SOAPRecently I started using the CXF SOAP library from Apache and was stumped on a simple problem, that being, how to view/modify a raw SOAP envelope. This sounds like a relatively simple task (not too bad when you know how) however it does in fact require some know-how.

The CXF SOAP library gives you access to all parts of the SOAP request and response life-cycle (via HTTP) using CXF Interceptors. The different points in time are referred to as phases and an interceptor can be placed at any one of the defined phases and automatically gain access to the SOAP message object and it’s current state.

For this example I have chosen Phase.RECEIVE which is one of the first phases which is essentially unprocessed by the CXF SOAP stack, which means I have free rain to pre-process the SOAP envelope (if I want to). Particularly handy if you need to maintain backwards compatibility with old SOAP API’s, poorly defined complex SOAP objects, dodgy WSDL definitions or maybe you simply want to view raw SOAP envelope (handy for debugging).

The crux to this problem is manipulating InputStream’s, once an InputStream has been read it is not available, which obviously causes a problem as the rest of the CXF SOAP stack expects it to be available. The solution is to use the CXF provided CachedOutputStream and IOUtils.copy which takes a cache copy of the InputStream making it available for future use :)

Once the Interceptor is implemented all that remains is to add it to the CXF SOAP client pror to usage.

This is an example of gaining access to an incoming client SOAP envelope, the interceptor could quite easily be in the sent phase or even part of the SOAP server implementation…it’s up to you.

package CXFSoap;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;

public class PacketInterceptor extends AbstractPhaseInterceptor<Message>{

	public PacketInterceptor(){
		super(Phase.RECEIVE);
	}

	public void handleMessage(Message message) throws Fault{
		// Get the supplied SOAP envelope in the form of an InputStream
		InputStream inputStream = message.getContent(InputStream.class);

		if (inputStream != null){
			String processedSoapEnv = "";
			// Cache InputStream so it can be read independently
			CachedOutputStream cachedInputStream = new CachedOutputStream();  
			try {
				IOUtils.copy(inputStream,cachedInputStream);
				inputStream.close();
				cachedInputStream.close();
				
				InputStream tmpInputStream = cachedInputStream.getInputStream();
				try{
					String inputBuffer = "";
					int data;
					while((data = tmpInputStream.read()) != -1){
						byte x = (byte)data;
						inputBuffer += (char)x;
					}
					/**
					  * At this point you can choose to reformat the SOAP
					  * envelope or simply view it just make sure you put
 					  * an InputStream back when you done (see below)
 					  * otherwise CXF will complain.
					  */
					processedSoapEnv = fixSoapEnvelope(inputBuffer);
				}
				catch(IOException e){
					
				}
			} 
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// Re-set the SOAP InputStream with the new envelope
			message.setContent(InputStream.class,new ByteArrayInputStream(processSoapEnv.getBytes()));
	
			/**		
			 * If you just want to read the InputStream and not 
			 * modify it then you just need to put it back where
			 * it was using the CXF cached inputstream
			 *
			 * message.setContent(InputStream.class,cachedInputStream.getInputStream());
			*/
		}
	}

	private String fixSoapEnvelope(String xml){
		...
	}
}

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import Stuff.StuffObj;
import CXFSoap.PacketInterceptor;
import CXFSoap.VIPCoreAPI;

public class CXFTest{

	    public static void main(String args[]) throws Exception{
	    		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		    	factory.setServiceClass(VIPCoreAPI.class);
		    	factory.setAddress("http://x.x.x.x/SOAP/API");
		    	factory.setWsdlLocation("http://x.x.x.x/SOAP/API?wsdl");
		    	factory.setUsername("xxx");
		    	factory.setPassword("xxx");


		    	/**
		    	 * This is the important part, the interceptor needs
		    	 * to be added to the CXF SOAP client prior to
		    	 * the SOAP call being made.
		    	 */
		    	factory.getInInterceptors().add(new PacketInterceptor());

		    	API client = (API)factory.create();
		    	StuffObj stuff = client.getStuff();
		    	System.out.print(stuff.toString());
	    }
}

Java: File Copy and File Move

October 7th, 2009 No comments

It has been a while since I’ve done any major Java development, it seems I have got used to having all the standard file tools which are available in scripted 4th and 5th generation languages like PHP.

Java whilst incredibly powerful is sometimes a bit awkward when dealing with certain problems. Often it’s the level abstraction and/or ability to get under the hood that can cloud a somewhat simple task, in my case file copying and moving.

Here is a small package that simplifies file copies and moves :)

package Utils.SystemTools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy{
	
	public static void copy(File source,File dest) throws IOException{
		try{
			copy(source.getPath(),dest.getPath());
		} 
		catch (IOException e){
			throw e;
		}
	}
	
	public static void copy(String source,String dest) throws IOException{
		try{
			File sourceFile = new File(source);
			File destFile = new File(dest);
			InputStream in = new FileInputStream(sourceFile);
			OutputStream out = new FileOutputStream(destFile);
			
			int bufferSize = 1024;
			byte[] buf = new byte[bufferSize];
			int len;
			while ((len = in.read(buf)) > 0){
				out.write(buf,0,len);
			}
			in.close();
			out.close();
	    }
	    catch(IOException e){
	    	throw e;
	    }
	}
	
	public static void move(String source,String dest) throws IOException{
		try{
			copy(source,dest);
		}
		catch(IOException e){
			throw e;
		}
		File sourceFile = new File(source);
		if (!sourceFile.delete()){
			throw new IOException("File deletion failed for: " + source);
		}
	}

	public static void move(File source,File dest) throws IOException{
		try{
			move(source.getPath(),dest.getPath());
		}
		catch(IOException e){
			throw e;
		}
		if (!source.delete()){
			throw new IOException("File deletion failed for: " + source.getPath());
		}
	}	
	
}
Categories: Code, General, Java Tags: ,

Simple Java File Logging

September 30th, 2009 No comments

Not much to say about this one, a small one off independent class to simplify the process of logging stuff to file. Something like this is often handy when writing backgrounded daemon processes.

FileLogger class

package Utils;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileLogger{
	
	private File logFile;
	
	private long logEntryNo = 0;
	
	private static FileLogger instance = null;
	
	public static final String DEFAULT_LOG_FILEPATH = "bin/Log/Daemon.log";
	
	public FileLogger(String logFilePath){
		logFile = new File(logFilePath);
		try{
			logFile.createNewFile();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		calcNumLines();
		instance = this;
	}
	
	public FileLogger(File logFile){
		this.logFile = logFile;
		calcNumLines();
		instance = this;
	}
	
	public static FileLogger getInstance(){
		return instance;
	}

	/**
	 * Adds and entry in the log file but also echos the log to standard out
	 * 
	 * @param data
	 * @param printToStdOut
	 */
	
	public void add(String data,boolean printToStdOut){
		if (printToStdOut){
			System.out.print("\n" + data + "\n");
		}
		add(data);
	}
	
	/**
	 * Add a log file entry
	 * 
	 * @param data
	 */
	
	public synchronized void add(String data){
		DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
		Date date = new Date();
		String dateTime = dateFormat.format(date);
		
		try{
			if (logFile.createNewFile()){
				FileWriter fileWriter = new FileWriter(logFile);
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
				bufferedWriter.newLine();
				bufferedWriter.close();
			}
			else{
				FileWriter fileWriter = new FileWriter(logFile,true);
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
				bufferedWriter.newLine();
				bufferedWriter.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void calcNumEntries(){
		try {
			FileReader fileReader = new FileReader(logFile);
			BufferedReader bufferedFileReader = new BufferedReader(fileReader);
			
			try{
				String line;
				while((line = bufferedFileReader.readLine()) != null){
					Pattern p = Pattern.compile("^\\[\\d+\\.\\d+\\.\\d+\\s+\\d+:\\d+:\\d+]#\\d+");
					Matcher m = p.matcher(line);
					
					if (m.find()){
						logEntryNo++;
					}
				}
				bufferedFileReader.close();
			} 
			catch (IOException e){
				e.printStackTrace();
			}
		} 
		catch (FileNotFoundException e){
			// The log file hasn't been created yet so gracefully ignore that fact
		}
	}
	
}

Usage:

FileLogger myFileLogger = new FileLogger(FileLogger.DEFAULT_LOG_FILEPATH);
myFileLogger.add("my log entry");

Auto Object Population via Reflection

September 24th, 2009 1 comment

Using reflection in the right place can some what simplify certain tasks, in this case the population of Custom classes (data objects). I have supplied below an example of a Class being auto-populated using ResultSet data from a JDBC request (of course it could really be any type of 2D data object).

If a public class variable is declared in the implementation of IModelObject (in this case the implementation is the RemoteConfig class) if the variable name is matched against a column name in the JDBC ResultSet then the value is assigned to the class variable. The great thing is if the variable is not defined in the class then it will quite simply never be populated…obviously as it doesn’t exist :)

In the example below only; String, int and boolean types are supported.

Basic interface class to keep thing reasonably generic

package Model.Objects;

import java.sql.ResultSet;

public interface IModelObject{
	
	public void populate(ResultSet rs);
	
	public String objToString();
	
	public void setDebug(boolean debug);
	
	public boolean getDebug();

}

Implementation of IModelObject which is the Class (data access object) to be auto-populated, (variables; var1, var2, var3, var4 will attempt to be auto-populated)

package Model.Objects;

import java.lang.reflect.*;
import java.sql.ResultSet;
import java.sql.SQLException;

@SuppressWarnings("unused")
public class RemoteConfig implements IModelObject{
	
	// Public variables ONLY are auto-populated using reflection

	public String var1;
	
	public int var2;
	
	public String var3;
	
	public boolean var4;
	
	private ResultSet resultSet;
	
	private static final String REFLECTION_TYPE_INT = "int";
	
	private static final String REFLECTION_TYPE_INTEGER = "Integer";
	
	private static final String REFLECTION_TYPE_STRING = "String";
	
	private static final String REFLECTION_TYPE_BOOLEAN = "boolean";
	
	private boolean debug = false;
	
	public RemoteConfig(){
		// Default constructor
	}
	
	public RemoteConfig(ResultSet rs){
		this.resultSet = rs;
		populate(rs);
	}
	
	public RemoteConfig(ResultSet rs,boolean debug){
		this.resultSet = rs;
		this.setDebug(debug);
		populate(rs);
	}
	
	public void populate(ResultSet rs){
		// NOTE: getFields only returns public variables (which is what we want)
		// if you need all declared variables the use getDeclaredFields
		for(int i=0;i< this.getClass().getFields().length;i++){
			try {
				String varName = this.getClass().getDeclaredFields()[i].getName();
				Field field = this.getClass().getDeclaredField(varName);
				
				try{
					populateClassVarByName(field);
				} 
				catch (IllegalArgumentException e) {
					e.printStackTrace();
				} 
			} 
			catch (SecurityException e) {
				e.printStackTrace();
			}
			catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		if (debug){
			System.out.print(objToString());
		}
	}
	
	private void populateClassVarByName(Field field){
		try{
			if (field.getType().getSimpleName().equals(REFLECTION_TYPE_INT) || 
				field.getType().getSimpleName().equals(REFLECTION_TYPE_INTEGER)){
			
				try {
					field.set(this,resultSet.getInt(field.getName()));
				} 
				catch (IllegalArgumentException e){
					e.printStackTrace();
				} 
				catch (IllegalAccessException e){
					e.printStackTrace();
				}
			}
			else if (field.getType().getSimpleName().equals(REFLECTION_TYPE_STRING)){
				try{
					field.set(this,resultSet.getString(field.getName()));
				}
				catch (IllegalArgumentException e){
					e.printStackTrace();
				}
				catch (IllegalAccessException e){
					e.printStackTrace();
				}
			}
			else if (field.getType().getSimpleName().equals(REFLECTION_TYPE_BOOLEAN)){
				try{
					if (resultSet.getString(field.getName()).equals("1")){
						field.set(this,true);
					}
					else if (resultSet.getString(field.getName()).equals("0")){
						field.set(this,false);
					}
					else{
						field.set(this,resultSet.getBoolean(field.getName()));
					}
				}
				catch (IllegalArgumentException e){
					e.printStackTrace();
				}
				catch (IllegalAccessException e){
					e.printStackTrace();
				}
			}
			
		} 
		catch (SQLException e){
			System.out.print("\n" + e.toString() + "\n");
		}
	}
	
	public String objToString(){
		String toStringResult = "\n---------" + this.getClass().getName() + "---------\n";
		
		for(int i=0;i< this.getClass().getDeclaredFields().length;i++){
			String varName = this.getClass().getDeclaredFields()[i].getName();
			try{
				Field field = this.getClass().getDeclaredField(varName);
				try {
					toStringResult += varName + ":" + field.get(this) + " (" + field.getType().getSimpleName() + ")\n";
				}
				catch (IllegalArgumentException e) {
					e.printStackTrace();
				} 
				catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			} 
			catch (SecurityException e) {
				e.printStackTrace();
			} 
			catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		toStringResult += "---------\n";
		
		return toStringResult;
	}
	
	public void setDebug(boolean debug){
		this.debug = debug;
	}
	
	public boolean getDebug(){
		return debug;
	}
}

Basic usage


/**
 * Get you your ResultSet via JDBC and pass it in
 */

RemoteConfig remoteConfig = new RemoteConfig(myResultSet,debug);

Java Reflection Examples

September 14th, 2009 No comments

Just to clear the air we are not talking about some funky new graphics render we are talking about programmatic reflection access of variables and methods :)

1. All of the variables public or private in a class can be accessed via reflection, it is assumed for this example that the code is in a class with class variables, hence the usage of “this” (but it doesn’t have to be it could be an instance object). Although we are only echoing the variable name and value to the screen we could be assigning them using the setter functions in the Field class. Really practical usage of this functionality is automatic population of Model classes from the Data Access layer, for example when using SOAP.

for(int i=0;i< this.getClass().getDeclaredFields().length;i++){
	try {
		String varName = this.getClass().getDeclaredFields()[i].getName();
		Field field = this.getClass().getDeclaredField(varName);
		field.setAccessible(true);
				
		try {
			System.out.print("Variablename: " + varName + "\n");
			System.out.print("Value: " + field.get(this).toString() + "\n");
		} 
		catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	catch (SecurityException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	catch (NoSuchFieldException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

2. This is an example of invoking a method via reflection, again this code assumes you are in a class. Also that class should contain a method called “test” with one String and an argument.

Class<?> params[] = {String.class};
		
try {
	Method method = this.getClass().getDeclaredMethod("test",params);
	try {
		method.invoke(this,"argument!!!!!");
	} 
	catch (IllegalArgumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	catch (IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	catch (InvocationTargetException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
} 
catch (SecurityException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} 
catch (NoSuchMethodException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

Test function to be called via reflection.

public void test(String str){
	System.out.print("Method test invoked via reflection with arg: " + str);
}
Categories: Code, General, Java Tags: ,