Monday, December 6, 2010

Writing a sample EJB Client Program using EJB 3.0

This post describes of creating a sample EJB Stateless bean and testing it in the JEE Server and it is based on EJB 3.0. Hope it will be useful..


DepartmentPersonIntf.java

package samplestateless;
public interface DepartmentPersonIntf{ //public void addNewDepartments(String name,String location); //public void addPersonInDept(String name); //public List getPersonInDept(String name);
public String getMessage(String name);
}


SampleStatelessbean.java

package samplestateless;
import javax.ejb.Stateless;import javax.ejb.Remote;import samplestateless.DepartmentPersonIntf;
@Stateless(name="SampleStatelessbean")@Remote(samplestateless.DepartmentPersonIntf.class)
public class SampleStatelessbean implements samplestateless.DepartmentPersonIntf{ public String getMessage(String name){ return "Message from Server :" +name; } public static void main(String[] args) { System.out.println("Hello World!"); }}

in META-INF create an xml sun-ejb-jar.xml with the below text.

<span><sun-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>SampleStatelessbean</ejb-name>
<jndi-name>SampleStatelessbean</jndi-name>
</ejb>
</enterprise-beans>
</sun-ejb-jar></span>


Use the below command for creating a jar.
jar -cvf ejbtest.jar samplestateless META-INF

SampleEJBTest.java

package samplestateless;
import javax.naming.Context;import javax.naming.InitialContext;import samplestateless.DepartmentPersonIntf;import java.util.Properties;
public class SampleEJBTest{ public static void main(String[] args) throws Exception { DepartmentPersonIntf departmentPersonIntf; Properties prop = new Properties(); prop.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory"); prop.put(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming"); prop.put(Context.PROVIDER_URL, "localhost:4848"); InitialContext initialContext = new javax.naming.InitialContext(prop); departmentPersonIntf = (DepartmentPersonIntf)initialContext.lookup("SampleStatelessbean"); String message = departmentPersonIntf.getMessage("Unit Testing"); System.out.println("Hello World!"+message); }}

Create an EJBTest.jar file and deploy it in the server to test the above program.

Sunday, November 21, 2010

String.replaceAll() vs String replaceAll code

String manipulation is one of the most commonly used aspect of programming. We do a lot of string manipulation like replacing a particular word in a string, stripping the string of unwanted words/tags, concatenating a string etc., .

It is very easy to introduce inefficiencies in the code while doing string manipulation. Programming languages provides a lot of built in API’s to manipuate a string. There is a very little chance for the built in API(s) to have inefficient code. Mostly it is the incorrect usage of API’s by us which brings in the inefficiency.

Let us take a case to illustrate this point,

Do a HTML escape for the given html document. The code should convert all the <, > , & , ‘ , ” in the string to < , > , & , ' , " respectively.

Source: Codeexperiments

Version 1:

This can be easily accomplished by using the java api String.replaceAll(String regex, String replacement). The following code does the html escaping.

String str = “

Hello World
”;
str = str.replaceAll(“<”,”<”); str = str.replaceAll(“>”,”>”);
str = str.replaceAll(“\”",”"”);
str = str.replaceAll(“\’”,”'”);
str = str.replaceAll(“\’”,”&”);

As you can see the code is very simple and clean. Does the job of HTML escaping the given string. But is it efficient?

Version 2:

We shall try to do HTML escaping without using the String.replaceAll() method. The following code analyzes each character in the given string and replaces it with the appropriate escaped value.

StringBuilder strBuilder = new StringBuilder();
int size = strIn.length();
for(int i = 0 ; i < charval =" strIn.charAt(i);">’:
{
strBuilder.append(“>”);
break;
}
case ‘\”:
{
strBuilder.append(“'”);
break;
}
case ‘\”‘:
{
strBuilder.append(“"”);
break;
}
case ‘&’:
{
strBuilder.append(“&”);
break;
}
default:
{
strBuilder.append(charVal);
}
}
}

String escapedString = strBuilder.toString();

Results:

Each version of the code was run 1000 times in a loop and here are the results

Version 1: Time taken for String.replaceAll(str,str) ::250 ms
Version 2: Time taken for custom replace all code ::15 ms

On running both the version of the code, it is found the version 2 which did not use the String.replaceAll() was on an average 10 to 15x faster than the version 1 of the code which used String.replaceAll().

Performance difference in String And StringBuilder

One of the most common mistake we do with Strings is when we try to concatenate multiple strings to form a bigger string. There are a lot of cases where we try to build a large string like, building a large json string to be passed, building a html, building a bulk insert sql, etc., In majority of cases we would be looping to create the large string.

In this experiment we shall try to create a large string which will contain “hello world” 20000 times.

Version 1:

String largeString = “”;
for(int i = 0 ; i < 20000; i++)
{
largeString = largeString + “hello world”;
}

The code might look alright, let us see how it performs

It took almost 186 Seconds to complete the operation in my PC (P4 3.04GHz, 1GB RAM)

For such a small operation it took more than 3 minutes to complete, surprising?

Let us experiment with another implementation using StringBuilder

Version 2:

StringBuilder largeStringBuilder = new StringBuilder();
for(int i = 0 ; i < 20000 ; i++)
{
largeStringBuilder.append(“hello world”);
}

This code took 15 ms to build the same string. Please notice it is not 15 seconds it is 15 milli seconds. That is almost 12400X faster than the string concatenation done in version 1 of the code.

Source: Codeexperiments

Thursday, November 18, 2010

Adding Custom Templats in Eclipse and RAD

The same way I try to avoid the redundancy in my code, the same way I try to avoid the redundancy in my writing. I am lazy and templates do the most writing for me. Eclipse comes bundled with predefined templates, but they are too general and not all of them are too useful. The real power is in custom templates. In this article I would like to show you how to create them and list a few useful pieces for inspiration.

What are templates

Exactly as the name suggests, templates are little pieces of code with defined placeholders. An example of simple template is

view sourceprint?
1.System.out.println(${text});

Each template has a name, which serves as a shortcut to the template itself. You type the name, press CTRL + SPACE and it will be expanded.

Our first template would expand to

I will not explain here what it all means, I already did this in my previous post on templates. What is important now, is that the ${text} placeholder (variable) was highlighted and can be edited immediately.

The true power of templates can be fully seen in more complex templates. The first power point lies in the fact, that you can have more than one variable with same name. Our second template will have more variables:

view sourceprint?
1.int ${increment} = ${value};
2.y = ${increment} + ${increment};

and will expand to



When you start typing now, all occurrences of increment variable will be changed. You can then switch to the next variable by pressing TAB key. In the end, you can have



in just three key presses - one for i, one for TAB and one for 2.

To make it even better, the template system provides predefined variables, which will be expanded depending on their context. I will not list them, you can find them under the Insert variable button.



Notice, that you are not getting only a list, you are also getting a description and an usage example.

To make it clear, I will illustrate one builtin variable - ${enclosing_type}. When this one is expanded you will get a name of the class (or interface, enum) in which your template was expanded.

"But how can I use it?", I hear you asking. I have prepared few templates just for inspiration, I believe that after reading this you will find thousands others and I believe that you will create them and share them with us.

Custom templates

Open Window -> Preferences and type Templates into the search box.




You will get a list of all editors, and their respective template settings. This is because templates are closely bound to editors - you will get different builtin variables in different editors. Also note, that your list may vary from my list, it all depends on installed plugins.

Now you must decide what type of template you would like to create. If it is a Java template, which will be applicable in context of classes, interfaces and enums, then choose Java -> Editor -> Templates. If you create a Java template you won't be able to use it in XML editor, that's quite expected.

So click on the New button, to get a dialog. Here it is, in all its glory:




Name is the name of the template. Choose it well, because it will serve as a shortcut to your template. After you type the name of the template (or at least a few characters from its name) and hit CTRL+SPACE it will be expanded.

Description is what you will see next to the template name when the template name is ambiguous.




Pattern is the template body. And the Context? This varies in every editor. If you look in the combobox in Java templates, you will see Java and Javadoc. It is simple a context within the respective editor in which the template would be applicable.

Check Automatically insert if you want the template to expand automatically on ctrl-space when there is no other matching template available. It is usually good idea to leave the checkbox checked, otherwise you would get a template proposal "popup". See what happens when I uncheck it on sysout template.




If I would have checked it, it would automatically expand, as there is no other template matching sysout* pattern.

My list

So here is the list I promised. I have categorized it.

Java (Java->Editor->Templates)
  • logger - create new Logger
    1.private static final Logger logger = Logger.getLogger(${enclosing_type}.class.getName());
    Notice the usage of ${enclosing_type} variable. This way you can create a logger in few hits. After the template expands, you will probably get red lines, indicating that Logger clas could not be found. Just hit CTRL + SHIFT + O to invoke the organize imports function. You are using shortcuts, aren't you?

  • loglevel - log with specified level
    1.if(${logger:var(java.util.logging.Logger)}.isLoggable(Level.${LEVEL})) {
    2. ${logger:var(java.util.logging.Logger)}.${level}(${});
    3.}
    4.${cursor}
    Let me explain the details. ${logger:var(java.util.logging.Logger)} uses a builtin "var" variable. It starts with logger, the default name, in case the var variable finds no match. It is then followed by var(java.util.logging.Logger), what will evaluate to the name of the variable (member or local) of the specified type (in our case of the Logger type). Further, the ${cursor} variable marks the place where the cursor will jump after you press enter. So the result after expanding could be



    You might wonder what is the purpose of the if. It is there only for performance gain. If specified level is not allowed the logging method will never be called and we can spare JVM some string manipulation to build the message.
  • readfile - read text from file

    Never can remember how to open that pesky file and read from it? Nor can I, so I have a template for it.
    01.BufferedReader in;
    02.try {
    03. in = new BufferedReader(new FileReader(${file_name}));
    04. String str;
    05. while ((str = in.readLine()) != null) {
    06. ${process}
    07. }
    08.} catch (IOException e) {
    09. ${handle}
    10.} finally {
    11. in.close();
    12.}
    13.${cursor}
Maven (Web and XML -> XML Files -> Templates)
  • dependency - maven dependency

    1. <groupId>${groupId}groupId>
    2. <artifactId>${artifactId}artifactId>
    3. <version>${version}version>
    4.dependency>
    5.${cursor}
  • parent - maven parent project definition
    1.<parent>
    2. <artifactId>${artifactId}artifactId>
    3. <groupId>${groupId}groupId>
    4. <version>${version}version>
    5. <relativePath>{$path}/pom.xmlrelativePath>
    6.parent>
    7.${cursor}
web.xml (Web and XML -> XML Files -> Templates)
  • servlet - new servlet definition
    01.<servlet>
    02. <servlet-name>${servlet_name}servlet-name>
    03. <servlet-class>${servlet_class}servlet-class>
    04. <load-on-startup>${0}load-on-startup>
    05. servlet>
    06.
    07.<servlet-mapping>
    08. <servlet-name>${servlet_name}servlet-name>
    09. <url-pattern>*.htmlurl-pattern>
    10.servlet-mapping>
    11.${cursor}
JSP pages (Web and XML -> JSP Files -> Templates)
  • spring-text - spring text field with label and error
    1.<label for="${path}" class="${label_class}"><fmt:message key="${path}"/>label>
    2.<spring:input path="${path}" cssClass="${input_class}"/>
    3.<spring:errors path="${path}"/>
    4.
    5.${cursor}
  • spring-checkbox
    1.<label for="${path}" class="${label_class}"><fmt:message key="${path}"/>label>
    2.<spring:checkbox path="${path}" cssClass="${input_class}"/>
    3.
    4.${cursor}
  • spring-select
    1.<label for="${path}" class="${label_class}"><fmt:message key="${path}"/>label>
    2.<spring:select path="${path}" cssClass="${input_class}">
    3.<spring:options items="${items}" itemLabel="${label}" itemValue="${value}"/>
    4.spring:select>
    5.<spring:errors path="${path}"/>
    6.
    7.${cursor}
  • spring-generic
    1.<label for="${path}" class="${label_class}"><fmt:message key="${path}"/>label>
    2.<spring:${type} path="${path}" cssClass="${input_class}"/>
    3.<spring:errors path="${path}"/>
    4.
    5.${cursor}
    These are my favorites. They regularly save me a huge amount of time. Creating spring forms has never been easier for me.
In some editor types you can set the template to 'new', for example, in XML editor it is new XML. This is really useful, as you can prepare the skeleton of a new file. For example, this is what I use to create new Spring servlet configuration for freemarker application.
01.xml version="1.0" encoding="UTF-8"?>
09.
10.<context:component-scan base-package="" />
11.
12.<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
13.<property name="templateLoaderPath" value="/"/>
14.bean>
15.
16.<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
17.<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
18.<property name="exposeSpringMacroHelpers"><value>truevalue>property>
19.<property name="cache" value="true"/>
20. <property name="prefix" value="/pages/"/>
21. <property name="suffix" value=".ftl"/>
22.bean>
23.
24.<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
25. <property name="basename"><value>messagesvalue>property>
26.bean>
27.beans>

Now, I can create new XML file from template and it will be ready to use. Before I knew about templates, I used to copy this from an older project, or search for it in Spring documentation. Now I don't have to..



If you can overcome the initial laziness and create your own templates from the pieces of code you really use, than this investment will shortly return in form of less typing. If you have some interesting templates, please, share them with us.

Listing Hardcoded Strings in a Java Class

The below program Lists all the hard coded strings available in a java source. It will be useful for you to move all the hard coded strings of a java class to a constants file by customizing this program. It is an initial draft of the program.. keep on following this blog for the final version.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Test {

public static void main(String[] args) throws Exception {

String fileName = "D:/workspace/demo/src/util/Utility.java";
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
BufferedReader bis = new BufferedReader(new InputStreamReader(fis));
String strLine;
while((strLine = bis.readLine()) != null) {

while(strLine.contains("\"")) {
int beginIndex = strLine.indexOf('"');
String remString = strLine.substring(beginIndex+1);
int endIndex = remString.indexOf('"');
"+(beginIndex+endIndex));
String temp = strLine.substring(beginIndex, (beginIndex+endIndex+2));
System.out.println("token : "+temp);
strLine = strLine.substring(beginIndex+endIndex+2);

}
}

}

}

Excited to post my experiments with Java

Hi Techies,

This is Ravinder Gaddam working as a developer in one of the reputed MNC with a highly paid Java job. I am not much satisfied with the robotic coding and routine coding which most of the developers were doing all the time. So i have decided the blogger platform to start experimenting on java.

I am really surprised that most of us are working in high technical jobs and spend most of our time to read filmy gossips , bloody political news but don't have time to experiment on our knowledge in the technologies and sharing things with other techies.

My motto is to develop a blog which have all the knowledge base of java experiments which will be useful to the future techies and to develop a technology cafe that can survive the needs of present and future developers by rectifying their doubts and queries and encourage them to learn by experimenting themselves.

I am concluding my views and thoughts in brief as i am not a politician to write lectures here. Wish me all the best and support in this endeavor.Guys who are ready to experiment here are always welcome.

Ravinder.G
ravinder855@gmail.com