Archive

Posts Tagged ‘Java’

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");

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: ,

Java: Multiple Thread Controller

September 10th, 2009 No comments

ThreadThis example is for those of you writing server side Java daemons who want to take full control over how much CPU is used on multi-core machines. Essentially you have a controller objected which when constructed creates up to maxThreads worth of “thread workers” (this is your thread pool) which can be assigned to generic code of your choice, in the form of an IRunnableThread, which is basically a Java Runnable object.

ThreadTester is a basic implementation of an IRunnableThread which contains a simple unit test to show the thread controller working. Of course you can swap out ThreadTester for you own implementation.

The Daemon main statement shows how to start and use the thread controller at the upper most level. The argument to thread controller is the number of threads you require for simultaneous processing, in this example its 3

package ThreadControl;

import java.util.LinkedList;
import ThreadControl.ThreadWorker;

public class ThreadController implements Runnable{

private int maxThreads;

private ThreadWorker[] threads;

public static LinkedList<IRunnableThread> queue;

    /**
     *
     */

    public ThreadController(int maxThreads){
        this.maxThreads = maxThreads;
        queue = new LinkedList<IRunnableThread>();
        threads = new ThreadWorker[maxThreads];
    }

    public static int queueSize(){
    	return queue.size();
    }

    public int maxQueueSize(){
    	return maxThreads;
    }

    public synchronized void push(IRunnableThread threadCode){
    	 queue.addLast(threadCode);
         queue.notify();
    }

    public void push(IRunnableThread threadCode){
    	synchronized(queue) {
          queue.addLast(threadCode);
          queue.notify();
        }
    }

    public void run() {
        for (int i=0; i<maxThreads; i++) {
            threads[i] = new ThreadWorker();
            threads[i].start();
        }
    }

}

The implementation for one of the thread workers that is part of your thread pool of size: maxThreads

package ThreadControl;

import ThreadControl.ThreadController;

public class ThreadWorker extends Thread{

	public void run(){
		IRunnableThread r;
		
		while (true){
			synchronized(ThreadController.queue){
				while(ThreadController.queue.isEmpty()){
					try{
						ThreadController.queue.wait();
					}
					catch (InterruptedException ignored){
						
					}
				}
				r = ThreadController.queue.removeFirst();
			}
			// If we don't catch RuntimeException, 
			// the pool could leak threads
			try{
				r.setThreadId(Long.toString(this.getId()));
                r.run();
            }
			catch (RuntimeException e) {
                 // You might want to log something here
			}
		}
	}
	
}

Runnable thread interface

package ThreadControl;

public interface IRunnableThread extends Runnable{
	
	public String getThreadId();

	public void setThreadId(String threadId);
	
}

Test implementation for IRunnableThread,

package ThreadControl;

public class ThreadTester implements IRunnableThread{
	
	private final static int noAlertMessages = 5; 
	
	// In milliseconds
	private int messageDelay = 1000;
	
	private String testId = "";

	private String threadId = "";
	
	public ThreadTester(String testId){
		this.testId = testId;
	}
	
	public ThreadTester(String testId,int messageDelay){
		this.testId = testId;
		this.messageDelay = messageDelay;
	}
	
	public void run(){
		for(int i=0;i<noAlertMessages;i++){
			System.out.print("Thread Id: " + threadId + " - [" + testId + "]: test message #" + (i + 1) + "\n");
			System.out.print("Thread Queue Size: " + ThreadController.queueSize() + "\n");
			try{
				Thread.sleep(messageDelay);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print("*** " + testId + " complete! ***\n");
	}

	public String getThreadId() {
		return threadId;
	}

	public void setThreadId(String threadId) {
		this.threadId = threadId;
	}

}

Main statement where the test case is demonstrated

import ThreadControl.ThreadController;
import ThreadControl.ThreadTester;

public class Daemon {

	public static void main(String[] args) {
		ThreadController threadController = new ThreadController(3);
		
		try{
			new Thread(threadController).start();
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		
		threadController.push(new ThreadTester("Test 1",5000));
		threadController.push(new ThreadTester("Test 2",333));
		threadController.push(new ThreadTester("Test 3",777));
		threadController.push(new ThreadTester("Test 4",450));
		threadController.push(new ThreadTester("Test 5",1024));
	}

}
Categories: Code, General, Java Tags: , ,