Yet another Java Developer.

JSF Developer living in Oklahoma City

Special Sidebar

You can add any content in this area by go to
Admin->Design->Widgets->Sidebar4

Proper way to read InputStream to byte array

There are many ways to accomplish this but this one does not use any external dependencies like Apache commons.

Two common pitfalls that I see are that people forget to flush the ByteArrayOutputStream and they call ‘baos.write(buffer)’ instead of ‘baos.write(buffer, 0, read)’ without actually clearing the buffer, which causes the last write to append previous bytes if the read returned less than what have been read from input stream.

	private String extract(InputStream inputStream) throws IOException {	
		ByteArrayOutputStream baos = new ByteArrayOutputStream();				
		byte[] buffer = new byte[1024];
		int read = 0;
		while ((read = inputStream.read(buffer, 0, buffer.length)) != -1) {
			baos.write(buffer, 0, read);
		}		
		baos.flush();		
		return  new String(baos.toByteArray(), "UTF-8");
	}

Flash Scope and Flash variables in Spring MVC

Sometimes its nice to be able to transfer object between request or for flash messages without need for a whole session. Here we will use session as our store mechanism for our flash scope. This concept here can be extended into implementing a ‘Conversation Scope’ but that is a whole different animal.

Example Usage

 @FlashAttribute(TABNAME_ATTRIB)
 public String getTabName() {
   return tabObject;
 }

Pass Enum values by reference in Java

Title might be little misleading since in java we pass always by value, but we can mimic passing by reference.

/**
 * This class allows us to pass values by reference ranter than value.
 * Not directly as java just passes reference of the object by value but indirecly 
 * @author Greg
 *
 * @param <E>
 */
public class IndirectReference<E> {
	public E ref;
 
	public IndirectReference(E ref) {
		this.ref = ref;
	}
 
	public void set(E ref) {
		this.ref = ref;
	}
}

Example usage

Just a snippet copied from my interpreter

	IndirectReference<ControlSignal> signal = new IndirectReference<ControlSignal>(ControlSignal.NOOP);
	if(signal.ref == ControlSignal.BREAK){
	    break;
	}

Regex to remove DOCTYPE prolog

While using HTML Tidy I needed to remove the DOCTYPE prolog to prevent
‘org.xml.sax.SAXParseException: Already seen doctype.’ exception.



Regex is quite simple, only catch is that we need to make sure we include the \n\r in our selecton and make it not greedy.

 convertedData = convertedData.replaceAll("<!DOCTYPE((.|\n|\r)*?)\">", "");

This will consume multiline as well as single declarations

/*		
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
*/

ANTLR Operator precedence grammar

This is snipper of my ANTLR grammar for parsing expressions with operator precedence,
By default the expressions are evaluated left to right which in some cases may produce undesired results, in order to fix that use of left and right parenthesis is required.


For example this two expressions will be evaluated differently

3 > 2 > 1
3 > (2 > 1)

Precedence


&&
||
< > <= >=
^
*/
+-

Grammar

According to ANTRL author currently we need a new rule for each precedence , which make is really messy but its not too bad after you get a hand of it. This grammar includes rewrite rules to generate our Abstract Syntax Tree(AST)

expression 
	: subExpr -> ^(EXPR subExpr)
	;
 
subExpr : logicalAndExp (addSubtractOp^ logicalAndExp)*
	;	
 
logicalAndExp
	: logicalOrExp (multiplyDivideOp^  logicalOrExp)*	 
	;
 
logicalOrExp
	: comparatorExp (CARET^  comparatorExp)* 	
	;
 
comparatorExp
	: powExp (comparatorOp^  powExp)* 	
	;
 
powExp 	: multExp (BARBAR^   multExp)*  
	;
 
multExp	
	:  expressionAtom (AMPAMP^ expressionAtom)*
	;
 
expressionAtom
	: 
	|   NUMBER
	|  ( LPAREN! subExpr^ RPAREN! ) 
	|   VARNAME
	|   function 
	;
 
 
addSubtractOp 
	:	PLUS
	|       MINUS
	;    
 
multiplyDivideOp 
	:	STAR
	|       SLASH
	;    
 
comparatorOp 
	:	GT
	|       LT
	| 	GTE
	|	LTE
	|	NEQ
	;

Abstract Syntax Trees

As stated before following two expression produce two different AST, ignore the semantics of the operators as they are only to show proper AST construction.

3 > 2 > 1
3 > (2 > 1)





Here is a expression parsed left to right

SET @me = 1+2+3*2

Here is a more complex expression that shows precedence and parenthesis operations

SET @me = 1*(2*3 + 3*2)/5+1

I think that for next post I will show on how to evaluate given expressions, also I am always looking for suggestions and comments

Custom port is not allowed or the host is not registered with this consumer key -yahoo developer network

To work around this error
Custom port is not allowed or the host is not registered with this consumer key.
Register the app as Desktop/Client application instead of web app.

TransactionRequiredException: Executing an update/delete query

Simply adding @Transactional on the method will resolve this issue

Convert given excel column name to column Index, ex ‘A=0′, ‘AA=26′

Other day I needed to convert excel spreadsheet column name to column index when having 200+ columns is easier to express as ‘FB’ instead of 157

A = 0
B = 1
AA = 26
AA = 27
FB = 157



This code will work for any number of column names.

	/**
	 * Convert given excel column name to column Index, ex 'A=0', 'AA=26'
	 * @param columnName
	 * @return 0 based index of the column
	 */
	private static short convert2ColumnIndex(String columnName) {
		columnName = columnName.toUpperCase();
		short value = 0;
		for (int i = 0, k = columnName.length() - 1; i < columnName.length(); i++, k--) {
			int alpabetIndex = ((short) columnName.charAt(i)) - 64;
			int delta = 0;
			// last column simply add it
			if (k == 0) {
				delta = alpabetIndex - 1;
			} else { // aggregate
				if (alpabetIndex == 0)
					delta = (26 * k);
				else
					delta = (alpabetIndex * 26 * k);					
			}
			value += delta;
		}
		return value;
	}


Converting from index to column name

This process is trivial we simply keep on taking mod 26 from index till we have nothing left, and converting that value to char.

StringOutputStream backed by ByteArrayOutputStream

The other day I needed to read output stream directly into a string, but JDK does not provides us with a stream directly for that. There have been numerous discussions on why and why not we should have this build into the JDK, but this was a case where I did need it and knew the encoding.

My implementation

StringOutputStream backed by ByteArrayOutputStream that simplifies reading of OutputStream directly into string.

 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
 
/**
 * StringOutputStream backed by ByteArrayOutputStream that simplifies  reading of {@link OutputStream}  directly into string
 * @author Grzegorz Bugaj
 *
 */
public class StringOutputStream extends OutputStream{
	private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
	private static final Charset DEFAULT_CHARACTER_SET = Charset.forName("UTF-8");
	private Charset characterSet;
 
	@Override
	public void write(int b) throws IOException {
		buffer.write(b);
	}
 
	@Override
	public void write(byte[] b) throws IOException {
		buffer.write(b);
	}
 
	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		buffer.write(b, off, len);
	}
 
	/**
	 * Get currently set character set if none set default charset of UTF-8 will be used
	 * @return Charaset 
	 */
	public Charset getCharacterSet() {
		if(characterSet == null)
			return DEFAULT_CHARACTER_SET;
 
		return characterSet;
	}
 
	public void setCharacterSet(Charset characterSet) {
		this.characterSet = characterSet;
	}
 
 
	@Override
	public String toString() {
		return new String(buffer.toByteArray(), getCharacterSet());
	}
}

Usage Example

	/**
	 * Read in given stream into a string
	 * @param stream
	 * @return
	 */
	public static String readAsString(InputStream stream) throws IOException{
		OutputStream sos = new StringOutputStream(); 		
		// Set chunk size to 64K chunk
		byte[] buffer = new byte[0x10000];
		int readLen;
		while((readLen = stream.read(buffer, 0, buffer.length)) != -1){
			sos.write(buffer, 0, readLen);
		}
		return sos.toString();
	}

SQL Rounding Error when calculating percentages

For cross compatability between sql and mysql servers when we do a division on a aggregated variable like count
we need to promote the INT to a DOUBLE type by multiplying it by 1.00 otherwise our results will loose precision

Examples


1/2=0 Incorrect Results
1.00/2=.5 or 1.00/2.00=.5 Good

For sake of consistency both variables have been promoted to DOUBLE


SELECT ROUND((COUNT(FieldA) * 1.00) / (COUNT(FieldB) * 1.00) * 100, 0)
FROM TESTTABLE

Sidebar3 : Please add some widgets here.