Archive for java

A Simple Java TLV Parser

* Read here for an explanation of TLV.
* In the following sample code, all found tag values are returned as a byte array containing individual tag values, each of which is itself a byte array.

 
    /**
     * Reads TLV values for a given hex string.
     */
    public static byte[][] readTLV(String tlvHexString, int tag) {
        return readTLV(hexStringToByteArray(tlvHexString), tag);
    }
 
    /**
     * Reads TLV values for a given byte array.
     */
    public static byte[][] readTLV(byte[] tlv, int tag) {
        if (tlv == null || tlv.length < 1) {
            throw new IllegalArgumentException("Invalid TLV");
        }
 
        int c = 0;
        ArrayList al = new ArrayList();
 
        ByteArrayInputStream is = null;
        try {
             is = new ByteArrayInputStream(tlv);
 
             while ((c = is.read()) != -1) {
                if (c == tag){
                    log.debug("Got tag");
                    if ((c = is.read()) != -1){
                        byte[] value = new byte[c];
                        is.read(value,0,c);
                        al.add(value);
                    }
                }
            }
        } finally {
            if (is != null) {
                try{
                    is.close();
                }catch (IOException e){
                    log.error(e);
                }
            }
        }
        log.debug("Got " + al.size() + " values for tag "
            + Integer.toHexString(tag));
        byte[][] vals = new byte[al.size()][];
        al.toArray(vals);
        return vals;
    }
 
    /**
     * Converts a hex string to byte array.
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
 

Velocity Template

Configuration Properties

General Properties

 
input.encoding
output.encoding
parser.pool.size
runtime.interpolate.literals
runtime.introspector.uberspect
 

Logging Properties

 
# Log file location. Default to velocity.log in the execution path
runtime.log
# Which log system to use. Defaults to Avalon LogKit
runtime.log.logsystem.class=org.apache.velocity.runtime.log.SimpleLog4JLogSystem
# Output stack trace
runtime.log.xxx.stacktrace=true | false
# Long invalid references in template. Default to true. Should be turned off in prod.
runtime.log.invalid.references= true | false
 

Resource Loader Properties

 
resource.loader=file, class, jar
 
# File Resource Loader
file.resource.loader.class= org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path=./src/templates/ch2
file.resource.loader.cache=true
file.resource.loader.modificationCheckInterval=2
 
# Classpath Resource Loader
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
 
# JAR Resource Loader
jar.resource.loader.class = org.apache.velocity.runtime.resource.loader.JarResourceLoader
jar.resource.loader.path = jar:file:/tmp/ResourceLoader2.jar
 
# DataSourceResourceLoader
 

Directive Properties

 
directive.include.out-put.errormsg.start
directive.include.output.errormsg.end
 
## Maximum depth of parse (default to 10)
directive.parse.maxdepth
 
## default to velocityCount
directive.foreach.counter.name
## default to 1
directive.foreach.counter.initial.value
 

Macro Properties

 
velocimacro.library=macroLibrary.vm
velocimacro.permissions.allow.inline=true | false
velocimacro.permissions.allow.inline .to.replace.global=true | false
## If true, changes to variables inside macro are visible only inside macro
## Default to false
velocimacro.context.localscope=true | false
## Default to false
velocimacro.library.autoreload=true | false
## Determines whether an inline macro is visible outside the defining template
velocimacro.permissions.allow.inline.local.scope=true | false
 

Velocity Template Language (VTL)

* Comments

 
## Single line comment
#* Multiple
line comments *#
 

* Escape char

 
## Escape character is \
\$myName = $myName
 

* Variables

 
## Variable is prefixed with a dollar sign
$myName
 
## Formal reference of variables
${myName}
 
## Quiet reference which will not be displayed if not set
$!undefinedVar
 
## Access object method
$myDate.getDate()
$myDate.getMonth()
 
## Access Java bean variables
$myDate.Date
$myDate.Month
 
## Access Map variables
$myMap.firstName
 
## Create variables in a template
#set($msg = "Hello world!")
I have a message: $msg
 
#set($str = "A string")
#set($num = 123)
#set($bool = true)
 

* Performing arithmetic
- Supports + - * / %
* Logical operators
AND: &&
OR: ||
NOT: !

Directives

* Include

 
## include template as is, no parsing
#include("footer.vm")
 
## included template needs to be parsed
#parse("footer.vm")
 

* If/else
Comparison operators: ==, !=, <, >, <=, >=

 
#set($myBool = true)
#if($myBool)
It is true
#else
It is false
#end
 
#if ($myName == "John")
    Hello John!
#elseif ($myName == "Jane")
    Hello Jane!
#else
    Hello world!
#end
 

* Access collections with #foreach

 
## Define Velocity array
#set($myArray = ["one", "two", "three"])
#foreach($item in $myArray)
    List Item: $item
#end
 
## Use range
#foreach($num in [1..9])
    List number: $num
#end
 

* Macros

 
#macro(myMacro $param1 $param2)
     \$param1: $param1
     \$param2: $param2
    #foreach($num in [1..9])
        List number: $num
    #end
#end
Call macro
#myMacro("John", "Jane")
 

References

* http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html
* VTL Reference Guide
* Pro Jakarta Velocity: From Professional to Expert by Rob Harrop Apress © 2004

Convert Eclipse Regular Project to Java Project

In Eclipse, regular project can be converted to Java project by editing the .project file as follows.

 
  <buildSpec>
    <buildCommand>
      <name>org.eclipse.jdt.core.javabuilder</name>
    </buildCommand>
  </buildSpec>
  <natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
  </natures>
 

A cleaner way

* Delete existing project without deleting existing files.
* Create new Java project from existing source.

Download Old Versions of Java Products

Try the following link to download previous versions of Java products:
http://java.sun.com/products/archive/.