Tuesday, February 28, 2012

Blog: How to professionally highlight your blog code using (Syntax Highlighting)

Hello everyone

Recently I have searched for a way to automatically keep my code snippets formatted and colorized with proper highlighting & syntax, without painful self-highlighting way, and then Blogger/Wordpress doesn't have the immediate solution out here!

I found an excellent open source tool called Syntax Highlighter is available.
This is ready to use out of box 100% Javascript based SyntaxHighlighter with extensive features & multiple other options.

SyntaxHighlighter can be either downloaded & used on your own webserver or if you have a blog on Blogger, this can be directly used as well.

To downloaded SyntaxHighlighter for your own personal Webserver/Hosted
site: http://alexgorbatchev.com/wiki/SyntaxHighlighter:Download
Configuration Steps: http://alexgorbatchev.com/wiki/SyntaxHighlighter:Configuration
Brush Aliases: http://alexgorbatchev.com/wiki/SyntaxHighlighter:Brushes


Friday, February 24, 2012

Barcode: Professional java barcode API (reader & writer)

Originally Barcodes were 1D representation of data using width and spacing of bars. Common bar code types are UPC barcodes (as shown) which are seen on product packages. 

There are 2D barcodes as well (they are still called Barcodes even though they don’t use bars). A common example of 2D bar code is PDF417, QR Code (as shown) which is commonly used by mobile phone apps. You can read history and more info about Barcodes on Wikipedia..
QR Code
UPC-A
PDF417 code
There is an open source Java library called ‘zxing’ (Zebra Crossing) which can read and write many differently types of bar codes formats.
I tested zxing and it was able to read a pure barcode and embedded in the middle of a 100 dpi grayscale busy text document!
This article demonstrates how to use zxing to read and write bar codes from a Java program.

Sunday, February 12, 2012

Glassfish: How to create lookups resources (simple & JavaBean Object)

It is a good idea to make your code modular and maintainable (less code modifications) when depending on resources.

To create a resource in application server so that all deployed applications can look them up, and make your application is loosely coupled on the resource it lookups, and be more dynamic.

The resource types can be object, string, boolean, number, or any custom java bean types.

In Glassfish 3+ CLI (Command Line Interface), they are created and managed with a set of generic commands:

asadmin create-custom-resource ...
asadmin list-custom-resources ...
asadmin delete-custom-resource ...
asadmin get 'resources.custom-resource.*'
asadmin set ...


GlassFish admin console provides GUI (Graphical User Interface) way of doing things but I found using CLI (Command line Interface) is a lot faster.

Saturday, February 11, 2012

JEE7: Looking ahead to a new era

Get educated about Java EE 7 JSRs.
With the release of Java EE 7 scheduled for the second half of 2012, projected JSRs are all up and running. The Java EE 7 release, which will reflect the evolving needs of the industry as it moves into the cloud, is date driven: anything not ready will be deferred to Java EE 8.

Here is an update and summary of the key features of different specifications in the Java EE 7 platform.

Illustrator: adobe illustrator CS5.5 training notes

Illustrator is vector graphics drawing tool while Photoshop is pixel graphic drawing tool.

Resolution measurements:
DPI = Dot Per Inch
PPI = Pixel Per Inch

Resolution types:
When you create a picture 1" X 1" with PPI = 1000px then this is called high resolution document, but if the same image size created with PPI = 10px then this called low resolution image.

What is vector Graphics?

Vector Graphics is the use of geometrical primitives such as points, lines, curves, and shapes or polygon(s), which are all based on mathematical equations, to represent image in computer graphics.

Illustrator uses anchor points and connects these anchors with lines called paths, which is re-calculated each time image is sized.

when drawing in illustrator the path connecting anchor points doesn't appears on final appearance of drown shape, it just a skeleton for the graphic shape while appearance is the glow of the shape.

Java: Copy jar files programmatically into another destination

Copying a jar file programmatically involves the following steps:
  1. Create a JarOutputStream based on the destination jar file.
  2.  Loop through all entries in the source jar file, and get the InputStream from each entry.
  3. Create a new jar entry with the same name as the source jar entry, and put the new entry to the JarOutputStream.
  4. Now we have InputStream, OutputStream, and the new jar entry in place, we are ready to transfer the bits, by reading bytes from InputStream into a buffer and writing buffer content to OutputStream.
  5. Close the InputStream, flush the JarOutputStream, and close the jar entry. This completes the copying of one jar entry.
  6. After the loop ends, all entries are copied from source jar file to destination jar file. Finally, close the JarOutputStream.
package test;
import java.io.*;
import java.util.Enumeration;
import java.util.jar.*;

//java -cp . test.CopyZip xxx/lib/sac-1.3.jar /tmp

public class CopyZip {
   public static void main(String[] args) throws Exception {
       File sourceFileOrDir = new File(args[0]);
       File destDir = new File(args[1]);
       if (sourceFileOrDir.isFile()) {
           copyJarFile(new JarFile(sourceFileOrDir), destDir);
       } else if (sourceFileOrDir.isDirectory()) {
           File[] files = sourceFileOrDir.listFiles(new FilenameFilter() {
               public boolean accept(File dir, String name) {
                   return name.endsWith(".jar");
               }
           });
           for (File f : files) {
               copyJarFile(new JarFile(f), destDir);
           }
       }
   }

   public static void copyJarFile(JarFile jarFile, File destDir) throws IOException {
       String fileName = jarFile.getName();
       String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
       File destFile = new File(destDir, fileNameLastPart);

       JarOutputStream jos = new JarOutputStream(new FileOutputStream(destFile));
       Enumeration<JarEntry> entries = jarFile.entries();

       while (entries.hasMoreElements()) {
           JarEntry entry = entries.nextElement();
           InputStream is = jarFile.getInputStream(entry);

           //jos.putNextEntry(entry);
           //create a new entry to avoid ZipException: invalid entry compressed size
           jos.putNextEntry(new JarEntry(entry.getName()));
           byte[] buffer = new byte[4096];
           int bytesRead = 0;
           while ((bytesRead = is.read(buffer)) != -1) {
               jos.write(buffer, 0, bytesRead);
           }
           is.close();
           jos.flush();
           jos.closeEntry();
       }
       jos.close();
   }
}

A common error is:

Exception in thread "main" java.util.zip.ZipException: invalid entry compressed
                                                       size (expected 1665 but got 1680 bytes)
   at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:206)
   at test.CopyZip.copyJarFile(CopyZip.java:63)
   at test.CopyZip.main(CopyZip.java:37)

It usually occurs when text file entries in the source jar file contain some non-ASCII characters such as ^I ^Z ^D ^C. Some common files are META-INF/COPYRIGHT.html, META-INF/LICENSE.txt, etc, probably because these files were created in a non-ASCII editor but saved as text files.

To avoid this type of
ZipException, always create a new JarEntry with the same name, and pass it to putNextEntry() method. Do not pass the existing jar entry from the source jar file to putNextEntry()
method.


Test: JUnit 4 Do's and Don'ts (An important notes)

DEFINITION:

A unit test examines the behavior of a distinct unit of work. Within a Java application, the “distinct unit of work” is often (but not always) a single method. By contrast, integration tests and acceptance tests examine how various components interact. A unit of work is a task that isn’t directly dependent on the completion of any other task.
A JUnit 4 test case class skeleton:

1.Do not name your test main class Test.java;
Which has the same short name as @Test annotation. Unless you explicitly use @org.junit.Test, @Test will resolve to your test class, instead of org.junit.Test annotation type.

2.Avoid using Java assertion;
Use static assertXXX methods (statically imported) in org.junit.Assert class. Java assert is turned off by default, and can be enabled only at command line with "java -ea", or "java -enableassertions" options. So some tests using Java assert will always pass when running with the default configuration, regardless of the actual test conditions. For example, the following method passes unless -ea option is passed to java:


A secondary reason to favor org.junit.Assert.assertXXX over Java assert is, the former is a richer API with more descriptive output, whereas Java assert, in its common form, only fails with java.lang.AssertionError and stack trace with no description. Java assert can also provide details with a second param: assert false : reason.

Maven surefire plugin automatically enables Java assertions when running JUnit tests on JDK 1.4 and above. So when running with surefire, there is no problem of false positive test results. But still I would like my JUnit tests to work the same way across all testing environment.

3.Avoid using assertTrue(list1.equals(list2));
Use assertEquals(list1, list2) instead. assertTrue will only print out the useless message like "expecting true, but actual false", whereas assertEquals gives more helpful message like "expected:[null, 1, 2], but was:[1, 2]"

4.Do not add assertTrue(true) at the end of a @Test
To signal the success result. It's just not needed. The test simply passes when nothing goes wrong.

5.@Test method can declare throws clause;
e.g., throws NamingException. When an exception is thrown during test run, the test is failed. So use exception as a means to communicate test failures. Do not try-catch an exception, just to print it and manually fail() it. For example, do this:

Do NOT do this:

When running the try-catch version, ArithmeticException stack trace is printed, followed by another stack trace of java.lang.AssertionError from calling fail(), whereas in the shorter version, only the ArithmeticException is logged and hence much easier to trace.

6.How to run a single test?
org.junit.runner.JUnitCore, the default command-line runner, takes a list of test classes as input, but doesn't support running a single test method. Other tools and IDE may support it by providing their own runner. With maven surefire 2.7.3+ and JUnit 4 tests, it is supported with a -D sysprop (link):

It is preferable to put the test name at the very end of the line so it's easier to go through the history and edit command.

7.To check the version of your JUnit:

8.To skip or exclude a test;
Use @Ignore (org.junit.Ignore).

9.To test a performance;
Use @Test(timeout = xx) (org.junit.Test) specify timeout in milliseconds to cause a test method to fail if it takes longer than that number of milliseconds.
For example: if you test a database query and it should take by max 1 second run this query inside a test case with timeout of 1000 ms, and tweak it further to reach this goal.

10.To test throwing a certain exception;
Use @Test(expected = xx) (org.junit.Test) where xx is a Throwable or sub of it, to cause a test method to succeed if an exception of the specified class is thrown by the method.

11.To test suite of test classes;
Use @RunWith(Suite.class) (org.junit.runner.RunWith) and @Suite.SuiteClasses( { ATest.class, A1Test.class }) (org.junit.runners.Suite) on class level as suite class that runs multiple test classes at the same time, in order they specified in the SuiteClasses, so ATest class test cases will run first before A1Test test cases.

The test suite could be empty and just for groping related test classes.

12.To test suite of suites;
Use 
@RunWith(Suite.class) (org.junit.runner.RunWith) and  @Suite.SuiteClasses( { ATestSuite.class, BTestSuite.class })(org.junit.runners.Suite) on class level as suite master class that runs multiple suite classes at the same time, in order they specified in the SuiteClasses, so ATestSuite class test cases for all classes it includes will run first before BTestSuite test cases.

The test suite could be empty and just for groping related test classes.

13.Running parameterized tests;
Use @RunWith(value = Parameterized.class) (org.junit.runner.RunWith) and @Parameters(org.junit.runners.Parameterized.Parameters) on a class method with signature "public static Collection name(){}" contains array of test parameters.

The Parameterized test runner allows you to run a test many times with different sets of parameters. Test class should have a constructor with argument list parameters equals to parameterized method array value.

When running a parameterized test class, instances are created for the cross-product of the test methods and the test data elements. Each instance of test class will be constructed using the n-argument constructor and the data values in the @Parameters method.

As the following example:

This test class will run and resulting with three test cases to run as testAdd[0], testAdd[1], testAdd[2].

Other testing types is shell and mock testing.

References:
1- JUnit in Action 2nd edition by (Petar Tahchiev,Felipe Leme,Vincent Massol,Gary Gregory).
2- Java how to Junit notes.

Sunday, February 5, 2012

Database: Oracle NoSQL Database in 5 Minutes

Inspired by some other "Getting started in 5 minutes" guides, we now have a Quick Start Guide for Oracle NoSQL Database.  kvlite, the single process Oracle NoSQL Database, makes it incredibly easy to get up and running.  I have to say the standard disclaimer: kvlite is only meant for kicking the tires on the API.  It is not meant for any kind of performance evaluation or production use.