<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bytearray - Programming, Computers and Technology &#187; Code</title>
	<atom:link href="http://bytearray.brixtonjunkies.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://bytearray.brixtonjunkies.com</link>
	<description></description>
	<lastBuildDate>Tue, 03 Nov 2009 11:52:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>CXF Raw SOAP Envelope via Interceptor</title>
		<link>http://bytearray.brixtonjunkies.com/2009/11/03/cxf-raw-soap-envelope-via-interceptor/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/11/03/cxf-raw-soap-envelope-via-interceptor/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 11:18:43 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Web/HTML]]></category>
		<category><![CDATA[cxf]]></category>
		<category><![CDATA[interceptor]]></category>
		<category><![CDATA[raw soap envelope]]></category>
		<category><![CDATA[soap]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=675</guid>
		<description><![CDATA[Recently 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 [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;"><img class="size-full wp-image-318 alignleft" title="CXF SOAP" src="http://bytearray.brixtonjunkies.com/wp-content/uploads/2009/11/soap-bar.jpg" alt="CXF SOAP" width="144" height="144" />Recently I started using the <a href="http://cxf.apache.org" target="_blank" rel="nofollow">CXF</a> 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 <em>(not too bad when you know how)</em> however it does in fact require some know-how.</p>
<p>The CXF SOAP library gives you access to all parts of the SOAP request and response life-cycle <em>(via HTTP)</em> using CXF <strong>Interceptors</strong>. The different points in time are referred to as <strong>phases</strong> and an interceptor can be placed at any one of the defined phases and automatically gain access to the SOAP message object and it&#8217;s current state.</p>
<p>For this example I have chosen <strong>Phase.RECEIVE</strong> 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 <em>(if I want to)</em>. Particularly handy if you need to maintain backwards compatibility with old SOAP API&#8217;s, poorly defined complex SOAP objects, dodgy WSDL definitions or maybe you simply want to view raw SOAP envelope <em>(handy for debugging)</em>.</p>
<p>The crux to this problem is manipulating InputStream&#8217;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  <strong>CachedOutputStream</strong> and <strong>IOUtils.copy</strong> which takes a cache copy of the InputStream making it available for future use <img src='http://bytearray.brixtonjunkies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Once the Interceptor is implemented all that remains is to add it to the CXF SOAP client pror to usage. </p>
<p>This is an example of gaining access to an incoming client SOAP envelope, the interceptor could quite easily be in the <strong>sent phase</strong> or even part of the SOAP server implementation&#8230;it&#8217;s up to you.</p>
<pre class="brush: java; title: ; notranslate">
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&amp;amp;lt;Message&amp;amp;gt;{

	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 = &amp;amp;quot;&amp;amp;quot;;
			// 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 = &amp;amp;quot;&amp;amp;quot;;
					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){
		...
	}
}
</pre>
<pre class="brush: java; title: ; notranslate">

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(&amp;amp;quot;http://x.x.x.x/SOAP/API&amp;amp;quot;);
		    	factory.setWsdlLocation(&amp;amp;quot;http://x.x.x.x/SOAP/API?wsdl&amp;amp;quot;);
		    	factory.setUsername(&amp;amp;quot;xxx&amp;amp;quot;);
		    	factory.setPassword(&amp;amp;quot;xxx&amp;amp;quot;);

		    	/**
		    	 * 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());
	    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/11/03/cxf-raw-soap-envelope-via-interceptor/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>SOAP Debugging with tcpdump</title>
		<link>http://bytearray.brixtonjunkies.com/2009/10/27/soap-debugging-with-tcpdump/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/10/27/soap-debugging-with-tcpdump/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 09:49:39 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Web/HTML]]></category>
		<category><![CDATA[soap]]></category>
		<category><![CDATA[tcpdump]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=646</guid>
		<description><![CDATA[You are on a Linux box (SOAP client) making a SOAP request to a SOAP server somewhere on port 80, to view the request and response with tcpdump here are the commands execute at shell. Incoming SOAP envelope (server response) Outgoing SOAP envelope (client request) Of course if you have additional traffic going in and [...]]]></description>
			<content:encoded><![CDATA[<p>You are on a Linux box <em>(SOAP client)</em> making a SOAP request to a SOAP server somewhere on port 80, to view the request and response with tcpdump here are the commands execute at shell. </p>
<p><strong>Incoming SOAP envelope <em>(server response)</em></strong></p>
<pre class="brush: plain; title: ; notranslate">
tcpdump  -nnvvlXSs 4096 src port 80
</pre>
<p><strong>Outgoing SOAP envelope <em>(client request)</em></strong></p>
<pre class="brush: plain; title: ; notranslate">
tcpdump  -nnvvlXSs 4096 dst port 80
</pre>
<p>Of course if you have additional traffic going in and out from this box you can use the &#8220;and&#8221; operator to fine tune what you are after.</p>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/10/27/soap-debugging-with-tcpdump/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: File Copy and File Move</title>
		<link>http://bytearray.brixtonjunkies.com/2009/10/07/java-file-copy-and-file-move/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/10/07/java-file-copy-and-file-move/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 14:12:06 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[java file copy]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=604</guid>
		<description><![CDATA[It has been a while since I&#8217;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&#8217;s the level [...]]]></description>
			<content:encoded><![CDATA[<p>It has been a while since I&#8217;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. </p>
<p>Java whilst incredibly powerful is sometimes a bit awkward when dealing with certain problems. Often it&#8217;s the level abstraction and/or ability to get under the hood that can cloud a somewhat simple task, in my case <strong>file copying and moving</strong>.</p>
<p>Here is a small package that simplifies file copies and moves <img src='http://bytearray.brixtonjunkies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: java; title: ; notranslate">
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)) &gt; 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(&quot;File deletion failed for: &quot; + 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(&quot;File deletion failed for: &quot; + source.getPath());
		}
	}	

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/10/07/java-file-copy-and-file-move/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flex: Multiple File Uploader</title>
		<link>http://bytearray.brixtonjunkies.com/2009/10/01/flex-multiple-file-uploader/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/10/01/flex-multiple-file-uploader/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 14:32:27 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[file uploader]]></category>
		<category><![CDATA[flex uploader]]></category>
		<category><![CDATA[multi uploader]]></category>
		<category><![CDATA[uploader]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=529</guid>
		<description><![CDATA[Uploading is such a common task and can often be a little painful so I decided to write a small library in Flex which simplifies the task. I have released it under GPL license so feel free to use and modify it according to the conditions The Flex client side uploader supports multiple file upload [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://bytearray.brixtonjunkies.com/wp-content/uploads/2009/10/uploader.jpg"><img class="size-full wp-image-528  alignleft" title="Flex Multi Uploader" src="http://bytearray.brixtonjunkies.com/wp-content/uploads/2009/10/uploader.jpg" alt="Flex Multi Uploader" width="378" height="178" /></a>Uploading is such a common task and can often be a little painful so I decided to write a small library in Flex which simplifies the task. I have released it under GPL license so feel free to use and modify it according to the conditions <img src='http://bytearray.brixtonjunkies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The Flex client side uploader supports multiple file upload with queuing and multiple threads, meaning more than one upload can be active at a time. It is also written in component style so creating an instance of the uploader is very simple and can be achieved in only a few lines of code <em>(see the example below).</em> It also supports posted additional data with the file upload, handy if you need to pass instructions to the back-end upload script.</p>
<p>The back-end script is not included in the library but could easily be implemented in any language. I have however supplied a <strong>PHP</strong> example below of how to implement the back-end script to support the Flex uploader <em>(see the example below).</em> </p>
<p>One final note, this code is not polished, it&#8217;s definitely Alpha&#8230;but still very usable. If you have any issues or questions please let me know, cheers.</p>
<p><em><strong>Simple example implementation of uploader library</strong></em></p>
<pre class="brush: as3; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
				xmlns:cc=&quot;FileUploader.Renderers.*&quot;
				layout=&quot;absolute&quot;
			    creationComplete=&quot;{init()}&quot;
			    width=&quot;1018&quot;
			    height=&quot;455&quot;
				&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[

			private function init():void{
				fileUploader.addPostData('mydata','1234567890');
			}

		]]&gt;
	&lt;/mx:Script&gt;

	&lt;cc:FileUploadComp id=&quot;fileUploader&quot;
					   x=&quot;0&quot;
					   top=&quot;8&quot;
					   left=&quot;8&quot;
					   width=&quot;1000&quot;
					   maxThreadsEnabled=&quot;true&quot;
					   uploadUrl=&quot;http://a.b.c.d/MyUploaderScript.php&quot;
					   /&gt;
&lt;/mx:Application&gt;
</pre>
<p><em><br />
<strong>PHP backend example implementation of uploader code</strong></em></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
	$tmpFileName = isset($_FILES['Filedata']['tmp_name']) ? $_FILES['Filedata']['tmp_name'] : '';
	$orgFileName = isset($_FILES['Filedata']['name']) ? $_FILES['Filedata']['name'] : '';
	$mydata = isset($_REQUEST['mydata']) ? $_REQUEST['mydata'] : '';

	error_log('tmpfile: ' . $tmpFileName);
	error_log('filename: ' . $orgFileName);
	error_log('mydata: ' . $mydata);	

	if (true){
		print 'ok';
	}
	else{
		header('Status: 500 ' . $resultAry[1]);
		header('HTTP/1.1 500 ' . $resultAry[1]);

		$outputStr = '&lt;!DOCTYPE HTML PUBLIC \&quot;-//IETF//DTD HTML 2.0//EN\&quot;&gt;' .
				 '&lt;html&gt;&lt;head&gt;' .
				 '&lt;title&gt;500 ' . $resultAry[1] . '&lt;/title&gt;' .
				 '&lt;/head&gt;&lt;body&gt;' .
				 '&lt;h1&gt;500 ' . $resultAry[1] . '&lt;/h1&gt;' .
				 '&lt;hr&gt;' .
				 $_SERVER['SERVER_SIGNATURE'] .
				 '&lt;/body&gt;&lt;/html&gt;';
		print $outputStr;
	}
?&gt;
</pre>
<p>Also here&#8217;s and example of a Flash <strong>crossdomain.xml</strong><em> (this one is reasonably open!)</em> which will be needed in the <strong>root</strong> of your site&#8230;otherwise flex will complain. </p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;!DOCTYPE cross-domain-policy SYSTEM &quot;http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd&quot;&gt;
&lt;cross-domain-policy&gt;
	&lt;allow-access-from domain=&quot;*&quot; to-ports=&quot;*&quot;/&gt;
	&lt;site-control permitted-cross-domain-policies=&quot;all&quot;/&gt;
&lt;/cross-domain-policy&gt;
</pre>
<p style="text-align: center;"><a rel="nofollow" href="http://bytearray.brixtonjunkies.com/wp-content/uploads/uploader/FlexUploaderExample.html" target="_blank">Demo Flex Uploader</a></p>
<p style="text-align: center;"><a href="http://bytearray.brixtonjunkies.com/wp-content/uploads/2009/10/FlexFileUploader.zip">DOWNLOAD (version 1.0a)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/10/01/flex-multiple-file-uploader/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Simple Java File Logging</title>
		<link>http://bytearray.brixtonjunkies.com/2009/09/30/simple-java-file-logging/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/09/30/simple-java-file-logging/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 10:21:19 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[file logger]]></category>
		<category><![CDATA[logger]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[logging module]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=513</guid>
		<description><![CDATA[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 Usage:]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p><em><strong>FileLogger class</strong></em></p>
<pre class="brush: java; title: ; notranslate">
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 = &quot;bin/Log/Daemon.log&quot;;

	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(&quot;\n&quot; + data + &quot;\n&quot;);
		}
		add(data);
	}

	/**
	 * Add a log file entry
	 *
	 * @param data
	 */

	public synchronized void add(String data){
		DateFormat dateFormat = new SimpleDateFormat(&quot;dd.MM.yyyy HH:mm:ss&quot;);
		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(&quot;[&quot; + dateTime +  &quot;]#&quot; + ++logEntryNo + &quot;: &quot; + data);
				bufferedWriter.newLine();
				bufferedWriter.close();
			}
			else{
				FileWriter fileWriter = new FileWriter(logFile,true);
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write(&quot;[&quot; + dateTime +  &quot;]#&quot; + ++logEntryNo + &quot;: &quot; + 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(&quot;^\\[\\d+\\.\\d+\\.\\d+\\s+\\d+:\\d+:\\d+]#\\d+&quot;);
					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
		}
	}

}
</pre>
<p><strong>Usage:</strong></em></p>
<pre class="brush: java; title: ; notranslate">
FileLogger myFileLogger = new FileLogger(FileLogger.DEFAULT_LOG_FILEPATH);
myFileLogger.add(&quot;my log entry&quot;);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/09/30/simple-java-file-logging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress: Custom Post Order</title>
		<link>http://bytearray.brixtonjunkies.com/2009/09/25/wordpress-custom-post-order/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/09/25/wordpress-custom-post-order/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 10:08:10 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[query_posts]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=484</guid>
		<description><![CDATA[I recently had a requirement for custom ordering on WordPress categories and thought that I would share how I did it. All that is needed is this piece of code which essentially modifies the SQL statement being generated. Note that the argument assigned to orderby is the column name, hence it is case sensitive (I [...]]]></description>
			<content:encoded><![CDATA[<p>I recently had a requirement for custom ordering on WordPress categories and thought that I would share how I did it.</p>
<p>All that is needed is this piece of code which essentially modifies the SQL statement being generated. Note that the argument assigned to <strong>orderby</strong> is the column name, hence it is case sensitive <em>(I found out that ID breaks the naming conversion on the post table)</em>;</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
   if (is_category(array($myCatId))){
      query_posts($query_string . &quot;&amp;orderby=ID&amp;order=DESC&quot;);
   }
?&gt;
</pre>
<p><em>Code needs to be placed before this line</em></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php if (have_posts()) : while (have_posts()) : the_post(); update_post_caches($posts); ?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/09/25/wordpress-custom-post-order/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Auto Object Population via Reflection</title>
		<link>http://bytearray.brixtonjunkies.com/2009/09/24/auto-object-population-via-reflection/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/09/24/auto-object-population-via-reflection/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 10:24:33 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[object population]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=385</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <strong>ResultSet</strong> data from a <strong>JDBC</strong> request <em>(of course it could really be any type of 2D data object)</em>. </p>
<p>If a <strong>public class variable</strong> is declared in the implementation of <strong>IModelObject</strong> <em>(in this case the implementation is the <strong>RemoteConfig class</strong>)</em> 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&#8230;obviously as it doesn&#8217;t exist <img src='http://bytearray.brixtonjunkies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>In the example below only; <strong>String</strong>, <strong>int</strong> and <strong>boolean</strong> types are supported.</p>
<p><strong><em>Basic interface class to keep thing reasonably generic </em></strong></p>
<pre class="brush: java; title: ; notranslate">
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();

}
</pre>
<p><strong><em>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)</em></strong></p>
<pre class="brush: java; title: ; notranslate">
package Model.Objects;

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

@SuppressWarnings(&quot;unused&quot;)
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 = &quot;int&quot;;

	private static final String REFLECTION_TYPE_INTEGER = &quot;Integer&quot;;

	private static final String REFLECTION_TYPE_STRING = &quot;String&quot;;

	private static final String REFLECTION_TYPE_BOOLEAN = &quot;boolean&quot;;

	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&lt; 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(&quot;1&quot;)){
						field.set(this,true);
					}
					else if (resultSet.getString(field.getName()).equals(&quot;0&quot;)){
						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(&quot;\n&quot; + e.toString() + &quot;\n&quot;);
		}
	}

	public String objToString(){
		String toStringResult = &quot;\n---------&quot; + this.getClass().getName() + &quot;---------\n&quot;;

		for(int i=0;i&lt; this.getClass().getDeclaredFields().length;i++){
			String varName = this.getClass().getDeclaredFields()[i].getName();
			try{
				Field field = this.getClass().getDeclaredField(varName);
				try {
					toStringResult += varName + &quot;:&quot; + field.get(this) + &quot; (&quot; + field.getType().getSimpleName() + &quot;)\n&quot;;
				}
				catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
				catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			catch (SecurityException e) {
				e.printStackTrace();
			}
			catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		toStringResult += &quot;---------\n&quot;;

		return toStringResult;
	}

	public void setDebug(boolean debug){
		this.debug = debug;
	}

	public boolean getDebug(){
		return debug;
	}
}
</pre>
<p><strong><em>Basic usage</em></strong></p>
<pre class="brush: java; title: ; notranslate">

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

RemoteConfig remoteConfig = new RemoteConfig(myResultSet,debug);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/09/24/auto-object-population-via-reflection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java Reflection Examples</title>
		<link>http://bytearray.brixtonjunkies.com/2009/09/14/java-reflection-examples/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/09/14/java-reflection-examples/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 11:30:46 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=337</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <img src='http://bytearray.brixtonjunkies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>1.</strong> 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 &#8220;this&#8221; <em>(but it doesn&#8217;t have to be it could be an instance object)</em>. Although we are only echoing the variable name and value to the screen we could be assigning them using the setter functions in the <strong>Field</strong> class. Really practical usage of this functionality is automatic population of Model classes from the Data Access layer, for example when using SOAP.</p>
<pre class="brush: java; title: ; notranslate">
for(int i=0;i&lt; 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(&quot;Variablename: &quot; + varName + &quot;\n&quot;);
			System.out.print(&quot;Value: &quot; + field.get(this).toString() + &quot;\n&quot;);
		}
		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();
	}
}
</pre>
<p><strong>2.</strong> 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 &#8220;test&#8221; with one String and an argument.</p>
<pre class="brush: java; title: ; notranslate">
Class&lt;?&gt; params[] = {String.class};

try {
	Method method = this.getClass().getDeclaredMethod(&quot;test&quot;,params);
	try {
		method.invoke(this,&quot;argument!!!!!&quot;);
	}
	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();
}
</pre>
<p>Test function to be called via reflection.</p>
<pre class="brush: java; title: ; notranslate">
public void test(String str){
	System.out.print(&quot;Method test invoked via reflection with arg: &quot; + str);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/09/14/java-reflection-examples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: Multiple Thread Controller</title>
		<link>http://bytearray.brixtonjunkies.com/2009/09/10/java-multiple-thread-controller/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/09/10/java-multiple-thread-controller/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 11:33:13 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[thread controller]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=312</guid>
		<description><![CDATA[This 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 &#8220;thread workers&#8221; (this is your thread pool) which can be assigned to generic [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;"><img class="size-full wp-image-318   alignright" title="Thread" src="http://bytearray.brixtonjunkies.com/wp-content/uploads/2009/09/thread.gif" alt="Thread" width="111" height="131" />This 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 <strong>maxThreads</strong> worth of &#8220;thread workers&#8221; <em>(this is your thread pool)</em> which can be assigned to generic code of your choice, in the form of an IRunnableThread, which is basically a Java Runnable object.</p>
<p style="text-align: left;"><strong>ThreadTester</strong> 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.</p>
<p style="text-align: left;">The <strong>Daemon</strong> 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 <strong>3</strong></p>
<pre class="brush: java; title: ; notranslate">
package ThreadControl;

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

public class ThreadController implements Runnable{

private int maxThreads;

private ThreadWorker[] threads;

public static LinkedList&lt;IRunnableThread&gt; queue;

    /**
     *
     */

    public ThreadController(int maxThreads){
        this.maxThreads = maxThreads;
        queue = new LinkedList&lt;IRunnableThread&gt;();
        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&lt;maxThreads; i++) {
            threads[i] = new ThreadWorker();
            threads[i].start();
        }
    }

}
</pre>
<p style="text-align: left;"><em><strong>The implementation for one of the thread workers that is part of your thread pool of size: maxThreads</strong></em></p>
<pre class="brush: java; title: ; notranslate">
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
			}
		}
	}

}
</pre>
<p><em><strong>Runnable thread interface</strong></em></p>
<pre class="brush: java; title: ; notranslate">
package ThreadControl;

public interface IRunnableThread extends Runnable{

	public String getThreadId();

	public void setThreadId(String threadId);

}
</pre>
<p><em><strong>Test implementation for IRunnableThread,</strong></em></p>
<pre class="brush: java; title: ; notranslate">
package ThreadControl;

public class ThreadTester implements IRunnableThread{

	private final static int noAlertMessages = 5; 

	// In milliseconds
	private int messageDelay = 1000;

	private String testId = &quot;&quot;;

	private String threadId = &quot;&quot;;

	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&lt;noAlertMessages;i++){
			System.out.print(&quot;Thread Id: &quot; + threadId + &quot; - [&quot; + testId + &quot;]: test message #&quot; + (i + 1) + &quot;\n&quot;);
			System.out.print(&quot;Thread Queue Size: &quot; + ThreadController.queueSize() + &quot;\n&quot;);
			try{
				Thread.sleep(messageDelay);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print(&quot;*** &quot; + testId + &quot; complete! ***\n&quot;);
	}

	public String getThreadId() {
		return threadId;
	}

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

}
</pre>
<p><strong><em>Main statement where the test case is demonstrated<br />
</em></strong></p>
<pre class="brush: java; title: ; notranslate">
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(&quot;Test 1&quot;,5000));
		threadController.push(new ThreadTester(&quot;Test 2&quot;,333));
		threadController.push(new ThreadTester(&quot;Test 3&quot;,777));
		threadController.push(new ThreadTester(&quot;Test 4&quot;,450));
		threadController.push(new ThreadTester(&quot;Test 5&quot;,1024));
	}

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/09/10/java-multiple-thread-controller/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Perl: Unbuffered File Logging Module</title>
		<link>http://bytearray.brixtonjunkies.com/2009/08/21/perl-unbuffered-file-logging-module/</link>
		<comments>http://bytearray.brixtonjunkies.com/2009/08/21/perl-unbuffered-file-logging-module/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 17:54:38 +0000</pubDate>
		<dc:creator>alchemist</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[file logger]]></category>
		<category><![CDATA[logger]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[logging module]]></category>

		<guid isPermaLink="false">http://bytearray.brixtonjunkies.com/?p=217</guid>
		<description><![CDATA[This an old Perl module I dug up which is quite a handy, there is no file write buffering so if you do a tail -f on the log file while it&#8217;s writing you can see real time what is going into the log file. Logger Module Logger Module Usage]]></description>
			<content:encoded><![CDATA[<p>This an old Perl module I dug up which is quite a handy, there is no file <span style="text-decoration: underline;">write buffering</span> so if you do a <strong>tail -f </strong>on the log file while it&#8217;s writing you can see real time what is going into the log file.</p>
<p><strong><br />
Logger Module</strong></p>
<pre class="brush: perl; title: ; notranslate">
package Logger;
# Logger.pm
#---------------------------------------------------
#
# Basic module to log to file
#
#---------------------------------------------------
# Constructor for logger module

sub new{
    my $class = shift;
    my $args = shift;

    # Default is to create a new logfile, NOT to append to it
    my $append = 0;
    if (defined($args-&gt;{append})){
		$append = $args-&gt;{append};
    }

    my $disable = 0;
    if (defined($args-&gt;{disable})){
		$disable = $args-&gt;{disable};
    }

    my $self = { filename =&gt; $args-&gt;{filename},
		 		 append =&gt; $append,
		 		 line_no =&gt; 0,
		 		 disable =&gt; $disable
	     };

    bless($self,$class);
    $self-&gt;_init();
}

#---------------------------------------------------
# Initialise the log file

sub _init{
    my $self = shift;
    if (!$self-&gt;{disable}){
		$filename = $self-&gt;{filename};

		if ($self-&gt;{append}){
	    	# Open a file for appending in write mode
	    	open(LOG,&quot;&gt;&gt; $filename&quot;);
	    	select LOG;
	    	$| = 1;
	    	select STDOUT;
	    	$self-&gt;{log_handle} = *LOG;
		}
		else{
	    	# Create a new file in write mode
	    	open(LOG,&quot;&gt; $filename&quot;);
	    	select LOG;
	    	$| = 1;
	    	select STDOUT;
	    	$self-&gt;{log_handle} = *LOG;
		}
    }

    return $self;
}

#---------------------------------------------------
# Add to the log file

sub add{
    my $self = shift;
    if (!$self-&gt;{disable}){
		my $str = shift;

		my $handle = $self-&gt;{log_handle};
		my $timestamp = localtime(time);
		my $line_no = ++$self-&gt;{line_no};
		print $handle &quot;[$timestamp#$line_no]: &quot; . $str . &quot;\n&quot;;
    }
}

#---------------------------------------------------
# Close log file

sub close{
    my $self = shift;
    if (!$self-&gt;{disable}){
		my $handle = $self-&gt;{log_handle};
		close($handle);
    }
}

#---------------------------------------------------
1;
</pre>
<p><strong><br />
Logger Module Usage</strong></p>
<pre class="brush: perl; title: ; notranslate">
#!/usr/bin/perl -w

use strict;
use lib 'MyPerlLibDir/';
use Logger;

my $myLogString = 'This text will appear in the log file';

my $loggerObj = new Logger({ append =&gt; 0, disable =&gt; 0, filename =&gt; 'MyLogFile.txt'  });
$loggerObj-&gt;add($myLogString);
$loggerObj-&gt;close();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://bytearray.brixtonjunkies.com/2009/08/21/perl-unbuffered-file-logging-module/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

