Brent Dodson

Web Programming Page

eightball Register
Unregistered users click here to register registered users can post their website here
eightball Science Humor:
The devil finds work for idle glands.
eightball Chuck Norris Humor:
Who would win the race between Batman and Superman to the moon???Chuck Norris
eightball Jobs:
Need a Job?
Check these out!!!!!
Jobs available
To pack 8bit to 7bit hex -
// description of your code here


public static byte[] getSeptets(byte[] octetBytes, boolean hasUDH) throws IOException {
byte[] compressedData = null;
try {
ByteArrayOutputStream bas = new ByteArrayOutputStream();
int userDataHeaderLen = 0;
int padBits = 0;
int userDataLen = octetBytes.length;

if (hasUDH) {
userDataHeaderLen = (octetBytes[0] &0xFF) + 1; // plus 1 za
// prvi byte
// duzine
bas.write(octetBytes, 0, userDataHeaderLen);

userDataLen = octetBytes.length - userDataHeaderLen;
padBits = (userDataHeaderLen * 8) % 7;
if (padBits != 0)
padBits = 7 - padBits;
}

byte pack[] = pack(octetBytes, userDataHeaderLen, userDataLen, padBits);
bas.write(pack, 0, pack.length);

compressedData = bas.toByteArray();

} catch (Throwable e) {
throw new IOException("Exception in (8bit to 7bit Hex conversion)", e);
}

return compressedData;
}

public static byte[] pack(byte[] ba) {
return pack(ba, 0, ba.length, 0);
}

public static byte[] pack(byte[] ba, int off, int len, int pad) {
String m1 = "", m2 = "";

for (int i = 0; i m1 += "0";
for (int i = off; i m1 = zeroPad(Integer.toBinaryString(ba[i] &0x7F), 7) + m1;
if (m1.length() % 8 != 0)
m1 = zeroPad(m1, m1.length() + (8 - m1.length() % 8));
for (int i = 0; i int b = Integer.parseInt(m1.substring(i, i + 8), 2);
m2 = zeroPad(Integer.toHexString(b).toUpperCase(), 2) + m2;
}
return fromHexString(m2);
}

public static byte[] unpack(byte[] ba, int unpack_len) {
return unpack(ba, 0, ba.length, 0, unpack_len);
}

public static byte[] unpack(byte[] ba, int off, int len, int pad, int unpack_len) {
String m1 = "", m2 = "";
for (int i = off; i m1 = zeroPad(Integer.toBinaryString(ba[i] &0xFF), 8) + m1;
}
m1 = m1.substring(0, m1.length() - pad);
m1 = m1.substring(m1.length() % 7);
for (int i = 0; i intb = Integer.parseInt(m1.substring(i, i + 7), 2);
m2 = zeroPad(Integer.toHexString(b).toUpperCase(), 2) + m2;
}
m2 = m2.substring(0, unpack_len * 2);
return fromHexString(m2);
}

private static String zeroPad(String s, int p) {
while (s.length() s = "0" + s;
return s;
}
Decode/encode hex string -
// decode/encode hex string


public static String toHexString(byte[] ba) {
String hex = "";
for(int i = 0; i hex += zeroPad(Integer.toHexString(ba[i] &0xFF).toUpperCase(), 2);
return hex;
}

public static byte[] fromHexString(String hex) {
ByteArrayOutputStream bas = new ByteArrayOutputStream();
for (int i = 0; i int b = Integer.parseInt(hex.substring(i, i + 2), 16);
bas.write(b);
}
return bas.toByteArray();
}
To decode string from hex -
// To decode string from hex


public static String decodeStringFromHex(String hexText) {

String decodedText = null;
String chunk = null;

if (hexText != null &&hexText.length() >0) {
int numBytes = hexText.length() / 2;

byte[] rawToByte = new byte[numBytes];
int offset = 0;
// int bCounter = 0;
for (int i = 0; i chunk = hexText.substring(offset, offset + 2);
offset += 2;
rawToByte[i] = (byte) (Integer.parseInt(chunk, 16) &0x000000FF);
}
decodedText = new String(rawToByte);
}
return decodedText;
}
To encode string to hex -
// To encode string to hex


public static String encodeStringToHex(String sourceText) {
byte[] rawData = sourceText.getBytes();
StringBuffer hexText = new StringBuffer();
String initialHex = null;
int initHexLength = 0;

for (int i = 0; i int positiveValue = rawData[i] &0x000000FF;
initialHex = Integer.toHexString(positiveValue);
initHexLength = initialHex.length();
while (initHexLength++ <2) {
hexText.append("0");
}
hexText.append(initialHex);
}
return hexText.toString();
}

Write into file -
// Creates a file in c:/test/ and writes into that file


File outFile = new File("C:\\test\\[FILENAME]");
outFile.createNewFile();

BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
out.write([WRITING]);
out.flush();
out.close();

Java Cartesian iterator for an array of Iterables -

import java.util.Iterator;

/**
* Iterates over Cartesian product for an array of Iterables,
* Returns an array of Objects on each step containing values from each of the Iterables.
*
* @author jacek.p.kolodziejczyk@gmail.com
* @created 01-08-2010
*/
public class CartesianIterator implements Iterator{

private final Iterable[] iterables;
private final Iterator[] iterators;
private Object[] values;
private int size;
private boolean empty;

/**
* Constructor
* @param iterables array of Iterables being the source for the Cartesian product.
*/
public CartesianIterator(Iterable ...iterables) {
this.size = iterables.length;
this.iterables = iterables;
this.iterators = new Iterator[size];

// Initialize iterators
for (int i = 0; i iterators[i] = iterables[i].iterator();
// If one of the iterators is empty then the whole Cartesian product is empty
if (!iterators[i].hasNext()) {
empty = true;
break;
}
}

// Initialize the tuple of the iteration values except the last one
if (!empty) {
values = new Object[size];
for (int i = 0; i }
}

@Override
public boolean hasNext() {
if (empty) return false;
for (int i = 0; i if (iterators[i].hasNext())
return true;
return false;
}

@Override
public Object[] next() {
// Find first in reverse order iterator the has a next element
int cursor;
for (cursor = size-1; cursor >= 0; cursor--)
if (iterators[cursor].hasNext()) break;

// Initialize iterators next from the current one
for (int i = cursor+1; i
// Get the next value from the current iterator and all the next ones
for (int i = cursor; i
return values.clone();
}

/**
* Gets the next value provided there is one from the iterator at the given index.
* @param index
*/
private void setNextValue(int index) {
Iterator it = iterators[index];
if (it.hasNext())
values[index] = it.next();
}

@Override
public void remove() { throw new UnsupportedOperationException(); }
}



Test cases:

import java.util.Arrays;

import junit.framework.TestCase;
import util.Strings;
import util.collect.CartesianIterator;

public class CartesianIteratorTest extends TestCase {

public void test_empty() throws Exception {
CartesianIterator it = new CartesianIterator();

assertFalse(it.hasNext());
try {
assertEquals("", Strings.join("",it.next()));
fail("Should throw NoSuchElementException");
} catch (Exception e) { /* Ignore exception */ }
}

public void test_0() throws Exception {
CartesianIterator it = new CartesianIterator(
Arrays.asList(new String[] {}));

assertFalse(it.hasNext());
try {
assertEquals("", Strings.join("",it.next()));
fail("Should throw NoSuchElementException");
} catch (Exception e) { /* Ignore exception */ }
}

public void test_1() throws Exception {
CartesianIterator it = new CartesianIterator(
Arrays.asList(new String[] {"a"}));

assertTrue(it.hasNext());
assertEquals("a", Strings.join("",it.next()));
assertFalse(it.hasNext());
}

public void test_2() throws Exception {
CartesianIterator it = new CartesianIterator(
Arrays.asList(new String[] {"a", "b"}));

assertTrue(it.hasNext());
assertEquals("a", Strings.join("",it.next()));
assertTrue(it.hasNext());
assertEquals("b", Strings.join("",it.next()));
assertFalse(it.hasNext());
}

public void test_2_0() throws Exception {
CartesianIterator it = new CartesianIterator(
Arrays.asList(new String[] {"a", "b"}),
Arrays.asList(new String[] {}));

assertFalse(it.hasNext());
try {
assertEquals("", Strings.join("",it.next()));
fail("Should throw NoSuchElementException");
} catch (Exception e) { /* Ignore exception */ }
}

public void test_2_2() throws Exception {
CartesianIterator it = new CartesianIterator(
Arrays.asList(new String[] {"a", "b"}),
Arrays.asList(new String[] {"c", "d"}));

assertTrue(it.hasNext());
assertEquals("ac", Strings.join("",it.next()));
assertTrue(it.hasNext());
assertEquals("ad", Strings.join("",it.next()));
assertTrue(it.hasNext());
assertEquals("bc", Strings.join("",it.next()));
assertTrue(it.hasNext());
assertEquals("bd", Strings.join("",it.next()));
assertFalse(it.hasNext());
}

public void test_2_3_4() throws Exception {
CartesianIterator it = new CartesianIterator(
Arrays.asList(new String[] {"a", "b"}),
Arrays.asList(new String[] {"c", "d", "e"}),
Arrays.asList(new String[] {"f", "g", "h", "i"}));

assertTrue(it.hasNext());
assertEquals("acf", Strings.join("",it.next()));
assertTrue(it.hasNext());
assertEquals("acg", Strings.join("",it.next()));
assertEquals("ach", Strings.join("",it.next()));
assertEquals("aci", Strings.join("",it.next()));
assertEquals("adf", Strings.join("",it.next()));
assertEquals("adg", Strings.join("",it.next()));
assertEquals("adh", Strings.join("",it.next()));
assertEquals("adi", Strings.join("",it.next()));
assertEquals("aef", Strings.join("",it.next()));
assertEquals("aeg", Strings.join("",it.next()));
assertEquals("aeh", Strings.join("",it.next()));
assertEquals("aei", Strings.join("",it.next()));
assertEquals("bcf", Strings.join("",it.next()));
assertEquals("bcg", Strings.join("",it.next()));
assertEquals("bch", Strings.join("",it.next()));
assertEquals("bci", Strings.join("",it.next()));
assertEquals("bdf", Strings.join("",it.next()));
assertEquals("bdg", Strings.join("",it.next()));
assertEquals("bdh", Strings.join("",it.next()));
assertEquals("bdi", Strings.join("",it.next()));
assertEquals("bef", Strings.join("",it.next()));
assertEquals("beg", Strings.join("",it.next()));
assertEquals("beh", Strings.join("",it.next()));
assertTrue(it.hasNext());
assertEquals("bei", Strings.join("",it.next()));
assertFalse(it.hasNext());
}
}
Replace Node in XML -
// replaces a node with a new (textual node)
// @Node node - the node (or Document) you want to replace.
// @nodeToReplace - the node you want to replace
// @replacementNode - the node you want to replace it with!


private static void replaceNodeWithString(Node node, Node nodeToReplace, Node replacementNode) {
NodeList nodeList = node.getChildNodes();
for(int i=0; i Node childNode = nodeList.item(i);

if(childNode.getNodeName().equals(nodeToReplace.getNodeName())){
Element parentElement = (Element)childNode.getParentNode();
parentElement.insertBefore(replacementNode, childNode);
childNode.getParentNode().removeChild(childNode);
parentElement.normalize();
i--;
}
replaceNodeWithString(childNode, nodeToReplace, replacementNode);
}
}
Remove Empty Nodes From Dom document -
// Snippit to remove an empty node from the document.
// Node node contains the node (or whole DOM document) from which you want to remove.
// String nameToRemove is the name of the Node you want to remove.


private static void removeEmptyNodes(Node node, String nameToRemove) {
NodeList nodeList = node.getChildNodes();
for(int i=0; i Node childNode = nodeList.item(i);
String nodeName = childNode.getNodeName();
if(nodeName.equals(nameToRemove) &&childNode.getTextContent().equals("")){
childNode.getParentNode().removeChild(childNode);
i--;

}
removeEmptyNodes(childNode, nameToRemove);
}
}
Simple PDF creation with iText -
Simple class which illustrates usage of iText to create a PDF file.


package testrecorder;

import java.io.FileOutputStream;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfWriter;

/**
*
* @author ditch182
*/
class createPDF {
private static Font catFont = new Font(Font.FontFamily.HELVETICA, 18);
private static Font redFont = new Font(Font.FontFamily.HELVETICA, 12);
private static Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
private Object thistest;

public createPDF(Test test) {
try {

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(test.getControlNo().toString() + ".pdf"));
document.open();
addMetaData(document, test);
addContent(document, test);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private void addMetaData(Document document, Test thisTest) {
document.addTitle(thisTest.getControlNo().toString());
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Richard Hibbitts");
document.addCreator("Automated Test Recorder");
}

private void addContent(Document document, Test thisTest) throws DocumentException {
Anchor anchor = new Anchor("First Chapter", catFont);
anchor.setName("First Chapter");

// Second parameter is the number of the chapter
Chapter catPart = new Chapter(new Paragraph(anchor), 1);

Paragraph subPara = new Paragraph("Subcategory 1", subFont);
Section subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Hello"));

subPara = new Paragraph("Subcategory 2", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Paragraph 1"));
subCatPart.add(new Paragraph("Paragraph 2"));
subCatPart.add(new Paragraph("Paragraph 3"));

// Add a little list
//createList(subCatPart);

// Add a small table
//createTable(subCatPart);
// Now a small table



// Now add all this to the document
document.add(catPart);

// Next section
anchor = new Anchor("Second Chapter", catFont);
anchor.setName("Second Chapter");

// Second parameter is the number of the chapter
catPart = new Chapter(new Paragraph(anchor), 1);

subPara = new Paragraph("Subcategory", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("This is a very important message"));

// Now add all this to the document
document.add(catPart);
}



}
Spring : Practical use of Spring method cache -
Here is practical use of Spring method cache.Example is using Ecache with Spring cache annotation
(Please refer to this nice article about how to configure spring method cache - http://www.dzone.com/links/r/how_to_enable_a_method_cache_with_the_springframe.html)

We have a web-app for online air ticket booking .This App gets data from integrated partner airlines systems .
For example each partner airlines exposes REST to know available flights for a date between Source and Destination .And they also expose REST to book a ticket .

Web Application use case is like that -

1.Use comes to our website ,searches flights available for a Date between a Source and Destination
2. then she selects a flight and books ticket .

Step 1 - is tricky as we have to show all flights available for that Date between source and destination and this Data has to come from each partner airlines system.That means if we have 100 airline partners we have to make 100 REST (1 REST call to each airline )calls and have to wait long enough for data
to come from integrated airlines partner systems .This might take a long response time and user experience wont be nice .

Might be you have already noticed - Data here is Flights between a source and destination for a Date .Each Airline would configure flights for a Date and would rarely change it .So Step 1 is classic case of method cache.

We can consider these rules to populate flight data into cache -
1.Run a cron job to populate Flight Data into cache for routes those have high number of flights .
2.For routes having few flights we would populates cache when some web user first searches flight for that route .

For step 2 - User selects a Flights so we already know partner airline system's url and directly make REST call to that system .[This is easy and direct one ]

let see code now for a method cache -


public interface FlightSearchService {


//If data is already there in cache it would take it from there otherwise make a REST call to partenr airlines //systems and then keeps it in cache for
//whole day as crone job would run in midnight

@Cacheable(cacheName="flightCache", keyGeneratorName="flightSearch")
public ListgetFlights(Date date,City source,City Destination);


}

Now lets write a cacheUpDate method for to update Flights Data into flightCache


public interface ManagerFlightCache {
//This method should be called by some kind of crone job -say- it runs in midnight and collects all Flight //data for a month from all partner
// airlines system

@TriggersRemove(cacheName="flightCache", removeAll=true)
//this removeAll=true would first remove all cached data from flightCache
public void updateFlightCache(Date fromDate,Date toDate);
}


Here is our keyGenerator for flight cache

//This KeyGenerator referred as "flightSearch" referred in @Cacheable
public class MethodArgsConcatKeyGenerator implements CacheKeyGenerator{

public Serializable generateKey(MethodInvocation methodInvocation) {

return concatMethodArguments(MethodInvocation methodInvocation); }

}
private String concatMethodArguments(MethodInvocation methodInvocation){
StringBuilder key = new StringBuilder();
for(Object arg : methodInvocation.getArguments()){
key.append(arg.toString()+"-");
}
return key.toString();
}


With cache being populated every midnight for routes having too many flights Data -searching flights become real fast .If some one searches for flights beyond one month (cache is populated with Flights for one month) then it would make REST call to partner airlines systems and then Data would be put in the cache .

During midnight crone job would run (it would call updateFlightCache(date1,date2) to remove data already present in cache ).Method would first invalidate cache (remove flight Data from cache ) and then collect Data for one month(for busy routes only) ,this way it would capture any changes occured in flights (more flights might be added by a airline or removed ).

 Use OpenOffice.org        Spread Firefox Affiliate Button

For any questions or enquiries, i can be reached at my email
I look forward to hearing from you

Copyright © 2010 brentdodson.com