OrangeApple
Java Code Geeks

We thought different, it's your turn now!
Jul 7 '12

Spring, Hibernate, Spring Data, Akka, Twitter Bootstrap, Apache Tiles, jQuery powered Maven Java Web Project Kickstarter Codebase

I am happy to upload my second project to GitHub to help people get started with Java Web App Development as quickly as possible. I am sharing this code with Apache License 2.0. Here is the URL for the same: 

https://github.com/ykameshrao/spring-hibernate-springdata-springmvc-maven-project-framework

The project consists of following parts:

1) Commons-Deps: Dependencies declared as a single pom file to easily manage the project dependencies. It is upto personal choice of users to still continue have it this way or go with their own chosen method to manage dependencies in maven pom.

2) Commons: A lot of common code snippets are provided as part of commons jar module to help send mails using gmail, java mail, utf8 encoding, JCS cache managers, session managers, random string, etc.

3) Framework: This part of the code base includes JPA and Spring Data Entities, JPA and Spring Data Repositories, Services which are built using Java Generics to help provide the CRUD actions on these Entities when users build their own domain specific entities, repositories and services extending the ones provided here. It also contains, API and Web App Controllers providing basic functionality again for people interested in building their own Spring MVC controllers using these. Also, contained here are validators, exceptions, AOP based exception handlers.

4) Your Own Web App Code: This part of the code provides a bootstrapped web project with API and Web UI using the best practices I picked across time to do things using the third party frameworks, libraries I have chosen here. The API parts is configured to accept and generate both XML and JSON request and response formats. Akka is also configured here to present the method in which it can be used to offload activities from your Spring MVC controllers (Servlets). Here it is programmed to offload the task of sending emails.

This is the wrapper framework laid out to start building Spring based Web apps with Hibernate ORM layer or Spring Data ORM powered NoSQL and Spring MVC in Java programming language. The purpose of this project is to get you started quickly in Java web app development over a widely used and tested Java web development infrastructure. 

This project provides sample hibernate entities, spring data entities, akka actors to offload mail sending like jobs, models, repositories, services and controllers classes. There are also many framework level classes to help handle exceptions and errors in the project you may start developing using this. The UI for the default simple web project bundled in this framework is built using Twiiter Bootstrap, Apache Tiles, jQuery, jQuery Validation, JSPs.


I can try my best to provide with as much detail as possible here, but the best way to understand all that is provided is by reading the code. Therefore, I also provided a sample web app project with functionality to register and login a user. All the code is presented in a package structure that can be renamed as per your own choice and requirements. Enjoy!


Configurations

config/props/mail.properties
mail.transport.protocol=smtps
mail.host=smtp.gmail.com
mail.user=
mail.pass=
mail.port=465
mail.starttls=true
mail.auth=true
mail.debug=true
mail.fromAddress=

config/props/database.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/yourwebprojectdb
jdbc.username=
jdbc.password=
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=600
hibernate.c3p0.max_statements=50

src/main/resources/tiles/templates.web.xml
<?xml version=”1.0” encoding=”UTF-8” ?>
<!DOCTYPE tiles-definitions PUBLIC
       ”-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN”
       ”http://tiles.apache.org/dtds/tiles-config_2_0.dtd”>
<tiles-definitions>
<definition name=”base” template=”/WEB-INF/views/layout/web.jsp”>
<put-attribute name=”title” value=”” />
<put-attribute name=”header” value=”/WEB-INF/views/common/header.web.jsp” />
        <put-attribute name=”message” value=”/WEB-INF/views/common/message.web.jsp” />
<put-attribute name=”content” value=”” />
<put-attribute name=”footer” value=”/WEB-INF/views/common/footer.web.jsp” />
</definition>
<definition name=”home” extends=”base”>
<put-attribute name=”title” value=”Your Web Project” />
<put-attribute name=”content” value=”/WEB-INF/views/web/home.web.jsp” />
</definition>
    <definition name=”userRegistration” extends=”base”>
    <put-attribute name=”title” value=”Register” />
    <put-attribute name=”content” value=”/WEB-INF/views/web/userRegistration.web.jsp” />
    </definition>
    <definition name=”dashboard” extends=”base”>
    <put-attribute name=”title” value=”Dashboard” />
    <put-attribute name=”content” value=”/WEB-INF/views/web/dashboard.web.jsp” />
    </definition>
    <definition name=”error” extends=”base”>
    <put-attribute name=”title” value=”Error” />
    <put-attribute name=”content” value=”/WEB-INF/views/web/error.web.jsp” />
    </definition>
</tiles-definitions>

Startup VM Options Required
-Dconf.path=”path-to-config-folder-on-target-machine-containing-property-files”

Refer: src/main/resources/config/spring/applicationContext-properties.xml
<util:properties id=”mdbProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/mongodb.properties” />
    <util:properties id=”dbProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/database.properties” />
    <util:properties id=”logProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/log4j.properties” />
    <util:properties id=”amProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/api.messages.properties” />
:
:


Screenshots

The frameworks strung together supporting multiple activities in this framework layer of code are -
Maven
Java 1.7
Spring 3.1.1
Hibernate 4+
Spring Data
MongoDB
Akka 1.3+
Apache Tiles 2+
Twitter Bootstrap 2+
Velocity for Mails
BootSwatch
jQuery

3 notes View comments Tags: spring hibernate akka spring-data twiiter-bootstrap apache-tiles jsp spring-mvc open-source programming

Jan 14 '12

Scala based Spring Hibernate Wireframe to get you started in Scala Web App development over Spring

This is the wrapper wireframe framework laid out to start building Spring based Web apps with Hibernate ORM layer and Spring MVC in Scala programming language. The purpose of this project is to get you started quickly in Scala web app development over a tried and tested java framework: Spring.

This project provides sample hibernate entities, models, DAOs, Service and Controller classes. There are also many framework level classes to help handle exceptions and errors in the project you may start developing using this. Used components: Spring 3+ Hibernate 3+ Scala 2.9+ Maven

Link to my first open source project: https://github.com/ykameshrao/scala-spring-hibernate-springmvc-maven-framework

70 notes View comments Tags: scala spring hibernate open-source programming software

Dec 26 '11

Android Custom Hyperlinked TextView

Finding Links in Android is very simple you might have heard of Linkify which is a great class in which there are many static methods for getting a simple job done but the problem is that in Linkify you cannot specify the behavior that you require on clicking the links at the Most what Linkify does is that it simply finds the links based on the “Pattern” you provide and adds a “Scheme” string to complete the URL and created a Android Intent for Launching the Browser. The Linkify behavior cannot be overridden as all the methods in Linkify class are static final.

This was the issue that inspired me to create a Custom TextView Widget the one which collects the links in my scenario I also programmed it to collect the the Strings starting with “@” and “#” but this things can be changed by simply changing the Patterns that you require and giving the proper Regular Expression for them.

The LinkEnableTextView class is like this:

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;


public class LinkEnabledTextView  extends TextView
{
// The String Containing the Text that we have to gather links from private SpannableString linkableText;
// Populating and gathering all the links that are present in the Text
private ArrayList<Hyperlink> listOfLinks; 

// A Listener Class for generally sending the Clicks to the one which requires it
TextLinkClickListener mListener;

// Pattern for gathering @usernames from the Text
Pattern screenNamePattern = Pattern.compile("(@[a-zA-Z0-9_]+)");

// Pattern for gathering #hasttags from the Text
Pattern hashTagsPattern = Pattern.compile("(#[a-zA-Z0-9_-]+)");

// Pattern for gathering http:// links from the Text
Pattern hyperLinksPattern = Pattern.compile("([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\">\\]\\)]*[^\\. ,'\">\\]\\)])");

public LinkEnabledTextView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    listOfLinks = new ArrayList<Hyperlink>();

}

public void gatherLinksForText(String text)
{
    linkableText = new SpannableString(text);
    /*
     *  gatherLinks basically collects the Links depending upon the Pattern that we supply
     *  and add the links to the ArrayList of the links
     */
    gatherLinks(listOfLinks, linkableText, screenNamePattern);
    gatherLinks(listOfLinks, linkableText, hashTagsPattern);
    gatherLinks(listOfLinks, linkableText, hyperLinksPattern);

    for(int i = 0; i< listOfLinks.size(); i++)
    {
        Hyperlink linkSpec = listOfLinks.get(i);
        android.util.Log.v("listOfLinks :: " + linkSpec.textSpan, "listOfLinks :: " + linkSpec.textSpan);
        /*
         * this process here makes the Clickable Links from the text
         */
        linkableText.setSpan(linkSpec.span, linkSpec.start, linkSpec.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    /*
     * sets the text for the TextView with enabled links
     */
    setText(linkableText);
}

/*
 * sets the Listener for later click propagation purpose
 */
public void setOnTextLinkClickListener(TextLinkClickListener newListener)
{
    mListener = newListener;
}

/*
 * The Method mainly performs the Regex Comparison for the Pattern and adds them to
 * listOfLinks array list
 */

private final void gatherLinks(ArrayList<Hyperlink> links,
                               Spannable s, Pattern pattern)
{
    // Matcher matching the pattern
    Matcher m = pattern.matcher(s);

    while (m.find())
    {
        int start = m.start();
        int end = m.end();

        /*
         *  Hyperlink is basically used like a structure for storing the information about
         *  where the link was found.
         */
        Hyperlink spec = new Hyperlink();

        spec.textSpan = s.subSequence(start, end);
        spec.span = new InternalURLSpan(spec.textSpan.toString());
        spec.start = start;
        spec.end = end;

        links.add(spec);
    }
}

/*
 * This is class which gives us the clicks on the links which we then can use.
 */
public class InternalURLSpan extends ClickableSpan
{
    private String clickedSpan;

    public InternalURLSpan (String clickedString)
    {
        clickedSpan = clickedString;
    }

    @Override
    public void onClick(View textView)
    {
        mListener.onTextLinkClick(textView, clickedSpan);
    }
}

/*
 * Class for storing the information about the Link Location
 */

class Hyperlink
{
    CharSequence textSpan;
    InternalURLSpan span;
    int start;
    int end;
}

Now, having this you require just another interface for propagating the clicks to the place you require to handle them in my case I implemented the interface in my Activity and simple wrote a Log Command there.

The TextLinkClickListener interface is like this:

import android.view.View;

public interface TextLinkClickListener
{

 /*
  *  This method is called when the TextLink is clicked from LinkEnabledTextView
  */
public void onTextLinkClick(View textView, String clickedString)
}

After doing all this you just require to create an Activity using the Custom LinkEnabledTextView and check the things out yourself. There are a few things that you must do while creating a object of the Custom LinkEnabledTextView those are mentioned and described in the Code of the Activity below:


import android.text.method.MovementMethod;
import com.umundoinc.Tvider.Component.LinkEnabledTextView.LinkEnabledTextView;
import com.umundoinc.Tvider.Component.LinkEnabledTextView.TextLinkClickListener;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;

/*
 * Here the Activity is implementing the TextLinkClickListener the one we have created
 * the Clicks over the Links are forwarded over here from the LinkEnabledTextView
 */
public class TextViewActivity  extends Activity  implements TextLinkClickListener 
{
private LinkEnabledTextView check;
protected void onCreate(Bundle savedInstance)
{
    super.onCreate(savedInstance);

    String text  =  "This is a #test of regular expressions with http://example.com links as used in @twitter
                     for performing various operations based on the links this handles multiple links like
                     http://this_is_fun.com and #Awesomess and @Cool";

    check = new LinkEnabledTextView(this, null);
    check.setOnTextLinkClickListener(this);
    check.gatherLinksForText(text);
    check.setTextColor(Color.WHITE);
    check.setLinkTextColor(Color.GREEN);

    MovementMethod m = check.getMovementMethod();
    if ((m == null) || !(m instanceof LinkMovementMethod)) {
        if (check.getLinksClickable()) {
            check.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    setContentView(check);
}

public void onTextLinkClick(View textView, String clickedString)
{
    android.util.Log.v("Hyperlink clicked is :: " + clickedString, "Hyperlink clicked is :: " + clickedString);
}

Here, is the Screenshot describing the output in my Listener method I programmed it to display a Toast but anything can be achieved in same method.

image

Now that’s pretty much all that you’ll need that makes the Custom LinkEnabledTextView working, try it out and share your views and reviews over it.

6 notes View comments Tags: Programming android code samples software

May 4 '09

Google – The world’s first $100 Billion Behemoth

Well, never really expected a company to be that big and especially when all its offerings (from search to videos, social networking, office docs and analytics) are available for FREE. Google does not charge a single penny and its still the first $100 billion brand in the world. Only one word comes to mind – Awesome..!

It is on one of these praise filled discussions about Google that we were having at office that I was presented with the other side of this coin. People are voicing an important concern here. Google is actually killing the entire Software industry.
Now, that’s a very strong statement to make. But people are saying that and I had to agree to some issues that they raised.
How will programmers like us would be fed if everything is available for FREE. There is a difference between Open Source and FREE. Most of Google’s services are FREE but not Open Source. Before GMail, I knew of many email service providers that charged some money for bigger mailboxes. There was some kind of business model being thought out for this free service. But Google immediately disrupted it with there huge 1 GB mail boxes. Google Docs is a huge example that could have created some healthy competition with other trying to build better office services had Google Docs been a paid service. There is no more motivation to write a competitive product for any of already Google provided FREE services.

Even as a Product Manager, when I think of some new idea, I am always stuck at Business Model point since some similar or very close service is already available for FREE with Google. Even if I innovate something with user experience and some features for which I charge a premium, Google would easily incorporate that into their already free service in no time and my product and its business is already dead.

One cannot create exclusive and premium services with Ad monetization as the only business model. There needs to go in extra efforts on the parts of creators for creating something really extraordinary and remarkable that needs to be paid for. Google is creating a sting of below par quality services with a sting of bugs and issues (the recent Google Docs security loophole being an example) and calling them BETA’s and giving it out for FREE. This is in one way or the other, killing the software industry.

Google is already created a marketplace where Software industries are finding it difficult to sell ‘Software as a Service’ (SAAS). Hardware companies are anyways thriving as always, since it has to be bought for some price. It is analogical to what the cassette recorders and DVD burners did to the music and movie industry with fueling the piracy and making it cheaper to copy and sell rather than people going for buying there own original stuff. While, Google is making it very simple for the hardware companies with its FREE services for everything. This is also leading to Google dominion in Software industry since only it makes money by ads due to higher usage and brand recognition of its free services. At the end – people/consumers are at loss.

Even we use Google Analytics and Google AdSense on this very blog. The Wordpress blog software that we use here is again open source. The only money we paid was the hosting space (physical) and domain name. And Google may soon change it if they open up there Google apps service (hosting solutions) that provides free hosting space for python based web apps. As soon as this starts supporting Java and PHP, who would buy hosting space for simple blogs with minimal feature requirements?

View comments Tags: news software companies

Apr 6 '09

Tata

This post is written by: Dhaval Motghare (http://www.dhavalmotghare.com)

Tata Nano was launched recently to much fan fare, the response as expected was pretty overwhelming to say the least so much so that Tata motors would be conducting a lucky draw to decide who gets to buy one and who doesn’t, much the same way it did way back in 1998 when the Indica was launched. Indica as you know was Tata’s first proper passenger car unlike Sierra, Safari or Sumo which were more of people or goods carriers. And Indica was a great success which pulled back Tata from a loss of more than 500 crore’s from the previous year. I was really proud back then about Tata’s accomplishment, proud that finally an Indian company was making a world class car. Tata did a commendable job by indigenously developing the Indica but sadly when it came to mass producing it, they failed miserably. Everyone knows at least one person who has a Tata horror story to tell. Shoddy built quality, overheating engines, parts falling off, air conditioner or power windows that don’t work, huge panel gaps and the list goes on. My sense of pride soon took a back seat but still I had some hope. I thought Tata has just started its foray into the passenger car segment this is a pretty nascent stage to form an opinion, but over years Tata has consistently failed to deliver when it comes to quality and I might as well add the designers have also managed to consistently churn out more and more ugly designs, Nano and the new Indica vista being a proof of it.

So why is it so difficult for Tata to build a decent car? Ratan Tata doesn’t seem like a person who would tolerate such a thing yet Tata continues to churn out shoddily built cars day after day. Is it plain lethargy or just don’t care attitude which allows this to continue. Or is it that it is cheaper to built low quality cars because either way people buy it as long as the cars are cheap?

View comments Tags: tata indica tata nano companies

Mar 12 '09

Poor Man’s GPS

This post is written by: Dhaval Motghare (http://www.dhavalmotghare.com)

This is regarding some interesting piece of code I found on the Internet. As a requirement for one of my work projects I had to develop a location aware application for a blackberry device. As always you need a GPS built in for the same. You also have a option of using triangulation based on cell ID and tower ID if the network carrier provides you with such a information, but generally it is not available or you have to pay for it. But now you have a third option “Google”.

What google has done is as a requirment for its maps application for handheld devices it has created a huge database of cell ID, tower ID with a corresponding mapping with latitude and longitude. As a consequence if you can now get cell ID and tower ID for a particular device you could locate yourself without a GPS or a need to pay for the service if your carrier provides it.

How to do this? Well this post helped me in figuring this out. As you could see the post contains a way to fetch a lat/long values from an exposed google web service. All you need to do is somehow get cell ID and tower ID for your device. Java ME doesn’t have a specific API available for doing the same you could on some devices get the cell ID and tower ID by querying through the System.getProperty() method with a platform specific key.

For example on Nokia you could use

Series 40 3rd Edition, FP1 (or newer):

System.getProperty(“Cell-ID”)

S60 3rd Edition, FP2 (or newer):

System.getProperty(“com.nokia.mid.cellid”)

 

If the platform in question is a blackberry device it has a well documented API for getting the cell information. The following code would tell you how to go about it.

//#ifdef BLACKBERRY_8300try {Class.forName("net.rim.device.api.system.GPRSInfo");Class.forName("net.rim.device.api.system.GPRSInfo.GPRSCellInfo");} catch (Exception e) {e.printStackTrace();return false;}try {deviceInfoObject.setCellID(GPRSInfo.getCellInfo().getCellId());deviceInfoObject.setARFCN(GPRSInfo.getCellInfo().getARFCN());deviceInfoObject.setBSIC(GPRSInfo.getCellInfo().getBSIC());deviceInfoObject.setLAC(GPRSInfo.getCellInfo().getLAC());deviceInfoObject.setRAC(GPRSInfo.getCellInfo().getRAC());deviceInfoObject.setGPRSState(GPRSInfo.getGPRSState());deviceInfoObject.setMCC(GPRSInfo.getCellInfo().getMCC());deviceInfoObject.setMNC(GPRSInfo.getCellInfo().getMNC());} catch (Exception e) {e.printStackTrace();return false;}return true;

//#endif

After you have acquired the device info you could fetch lat/long values using the exposed google service. You could find the following code helpful which I ported to J2ME from the android specific code which could be found in the post I mentioned above.

public boolean queryForCoordinates(DeviceInfo deviceInfo) {

String baseURL = "http://www.google.com/glm/mmap";// Setup the connectionHttpConnection httpConnection = null;OutputStream outputStream = null;DataInputStream inputStream = null;

try {

httpConnection = openConnection(baseURL);byte[] pd;if(deviceInfo.getCellID() <= 0 || deviceInfo.getLAC() <= 0)pd = PostData(0, 0, 3105, 20601, false);elsepd = PostData(deviceInfo.getMCC(), deviceInfo.getMNC(), deviceInfo.getLAC(), deviceInfo.getCellID(), false);

handler.processRequestHeaderForCoordinates(httpConnection);

httpConnection.setRequestProperty("content-length", pd.length + "");outputStream = httpConnection.openOutputStream();outputStream.write(pd);outputStream.close();

DataInputStream dis = httpConnection.openDataInputStream();

// Read some prior datadis.readShort();dis.readByte();// Read the error-codeint errorCode = dis.readInt();if (errorCode == 0) {double lat = (double) dis.readInt() / 1000000D;double lng = (double) dis.readInt() / 1000000D;// Read the rest of the datadis.readInt();dis.readInt();dis.readUTF();

deviceInfo.setLatitude(lat);deviceInfo.setLongitude(lng);

System.out.println("Lattitude --" + lat);System.out.println("Longitude --" + lng);

} else {/* If the return code was not* valid or indicated an error,* we display a Sorry-Notification */return false;}return true;} catch (Exception e) {e.printStackTrace();return false;} finally {closeConnection(httpConnection, outputStream, inputStream);}

}

private byte[] PostData(int MCC, int MNC, int LAC, int CID, boolean shortCID) {/* The shortCID parameter follows heuristic experiences:* Sometimes UMTS CIDs are build up from the original GSM CID (lower 4 hex digits)* and the RNC-ID left shifted into the upper 4 digits.*/byte[] pd = new byte[]{0x00, 0x0e,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x1b,0x00, 0x00, 0x00, 0x00, // Offset 0x110x00, 0x00, 0x00, 0x00, // Offset 0x150x00, 0x00, 0x00, 0x00, // Offset 0x190x00, 0x00,0x00, 0x00, 0x00, 0x00, // Offset 0x1f0x00, 0x00, 0x00, 0x00, // Offset 0x230x00, 0x00, 0x00, 0x00, // Offset 0x270x00, 0x00, 0x00, 0x00, // Offset 0x2b(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,0x00, 0x00, 0x00, 0x00};

boolean isUMTSCell = ((long) CID > 65535);

if (isUMTSCell) {System.out.println("UMTS CID. {0} " + (shortCID ? "Using short CID to resolve." : ""));} else {System.out.println("GSM CID given.");}if (shortCID) {CID &= 0xFFFF;

View comments Tags: cell id gps tower id programming software

Mar 3 '09

Java Annotations: Explored & Explained

One of the many wonderful features of Java 5 SE is the introduction of the Annotations construct. Annotations are tags that we can insert into our program source code for some tool to process it and make sense out of it. Annotations processing tools generally use Reflection API (of Java 5 SE) to process the code at source level on Java code or bytecode level to process the class files into which the compiler has placed the annotations. Java Annotations are wonderfully explained in many places around the web, but the only place where I could find a sensible and complete example was a hard bound book by Prentice Hall Publications named Core Java : Volume II - Advanced Features, authored by Cay S. Horstmann and Gary Cornell. Almost all the places on web that try to explain Annotations miss the most crucial part of showing us an Annotation Processing Tool (APT) for our custom written annotations and the way to use it from our code. I have used the information from the book to build some Annotations for validating variables and initializing values in them from property files for my project. My observation of the lack of examples over the www for writing custom Java Annotations has motivated me to write this article. So, presenting to you a sample custom Java Annotation to help you write your own Annotations for whatever it is you may be doing.

I will take you through the NullValueValidate annotation whose purpose as its name suggests is to validate the variable it annotates to be containing a non null value. If it finds a null value while processing then it will throw a NullPointerException. I] Declaring an AnnotationLets begin by declaring our annotation. This declaration will be used by the code that intends to use the annotation to annotate the variables in its object.

package annotation.declaration;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Null Value Validate is, as the name suggests an annotation to
 * validate whether the parameter is null or not
 * @author         Y.Kamesh Rao
 *
 */
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)

public @interface NullValueValidate {
    String paramName();
}

Note the ‘@’(AT) symbol in front of the ‘interface’ keyword. This is the syntax used to declare an annotation. This is called an annotation interface. The methods of the interface correspond to the elements of the annotation. paramName() - This is the only element our annotation declaration consists of. It stores the name of the annotated field to display it in a message while processing. Note that the declaration looks like a function declaration. Actually, that is what it is. @interface actually declares a Java interface whose implementation is provided by the objects that use the annotation. Annotation processors receive the objects that use/implement the annotation and they call annotation interface methods to retrieve the annotation elements. In our case, the NullValueValidateAnnotationProcessor would receive the object of the class that has some fields annotated using the NullValueValidate annotation. This processor would then call the paramName() method to retrieve the value of this annotation element. We use 3 of the Java provided Annotations to annotate the properties of our declaration. These are alternatively referred to as the Built-In Annotations and are used for 'Annotating an Annotation'. (Well, there are much tougher tongue twisters than this). @Documented - Indicates that the annotation declaration has to be included while creating the docs for this project using JavaDocs. By default, Annotations are excluded from the documentation generated using the javadocs command. @Target - Indicates the target elements in your java program to which the annotation shall be applied. It can either the Field, Method, Class or the whole Package itself. Our NullValueValidateannotation shall be applicable to only class fields. Here are the possible values taken by this Enum -

  • TYPE - Applied only to Type. A Type can be a Java class or interface or an Enum or even an Annotation.
  • FIELD - Applied only to Java Fields (Objects, Instance or Static, declared at class level).
  • METHOD - Applied only to methods.
  • PARAMETER - Applied only to method parameters in a method definition.
  • CONSTRUCTOR - Can be applicable only to a constructor of a class.
  • LOCAL_VARIABLE - Can be applicable only to Local variables. (Variables that are declared within a method or a block of code).
  • ANNOTATION_TYPE - Applied only to Annotation Types.
  • PACKAGE - Applicable only to a Package.

@Retention - Indicates the retention policy to be used for the annotation. In simple words, for long would we retain the annotation. There are three possible values -

  • SOURCE - Annotations are to be discarded by the compiler.
  • CLASS - Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.  This is the default behavior.
  • RUNTIME - Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

We have set the RetentionPolicy to be RUNTIME since we plan to process the annotations at runtime of the program. @Target and @Retention are also called Meta-Annotations. II] Annotation Processing Tool An annotation processor tool, parses the object it receives and takes programmed actions on finding the annotations it is processing in the object under scrutiny. Here is the annotation processor for our previously declared annotation - NullValueValidate.

package annotation.processor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import annotation.declaration.NullValueValidate;

/**
 * The class file to actually carry out the validations
 * for the various validate annotations we have declared
 * @author         Y.Kamesh Rao
 */
public class NullValueValidateAnnotationProcessor {
    /**
     * Method to process all the annotations
     * @param obj    The name of the object where
     *               annotations are to be identified and
     *               processed
     */
    public static void processAnnotations(Object obj) {
        try {
            Class cl = obj.getClass();

            // Checking all the fields for annotations
            for(Field f : cl.getDeclaredFields()) {
                // Since we are Validating fields, there may be many
                // NullPointer and similar exceptions thrown,
                // so we need  to catch them
                try {
                    // Processing all the annotations on a single field
                    for(Annotation a : f.getAnnotations()) {
                        // Checking for a NullValueValidate annotation
                        if(a.annotationType() == NullValueValidate.class) {
                            NullValueValidate nullVal = (NullValueValidate) a;
                            System.out.println("Processing the field : "+ nullVal.paramName());

                            // Setting the field to be accessible from our class
                            // is it is a private member of the class under processing
                            // (which its most likely going to be)
                            // The setAccessible method will not work if you have
                            // Java SecurityManager configured and active.
                            f.setAccessible(true);

                            // Checking the field for a null value and
                            // throwing an exception is a null value encountered.
                            // The get(Object obj) method on Field class returns the
                            // value of the Field for the Object which is under test right now.
                            // In other words, we need to send 'obj' as the object
                            // to this method since we are currently processing the
                            // annotations present on the 'obj' Object.
                            if(f.get(obj) == null) {
                                throw new NullPointerException("The value of the field "+f.toString()+" can't be NULL.");
                            } else
                                System.out.println("Value of the Object : "+f.get(obj));
                        }
                    }
                } catch(Exception e) {
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch(Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

Most of the code is self explanatory with comments that it has. Please refer the code for detailed understanding of the same. Basically, it has a static method called processAnnotations that takes the object of the class which contains annotations that need to be processed. We then use Java Reflection API to process each of the Field in this received object parameter and take necessary actions of null value validation whenever we find a NullValueValidate Annotation on the field. If a null value is found, we throw the NullPointerException or we print the value on the console.

III] Annotation UsagePlease refer the following code that uses the NullValueValidate annotation that we just implemented. It also uses the NullValueValidateAnnotationProcessorto process the declared annotations on its field at runtime by calling it from its constructor. Also do note that the annotations are used in a similar fashion as access modifiers like private or public with the variable/field declarations. Usually a newline is entered for better readability of the code. Else, the annotation can very well exist in the same line as the variable/field declaration. The name of the annotation is preceded by an ‘@’(AT) symbol.

package annotation;

import annotation.declaration.NullValueValidate;
import annotation.processor.NullValueValidateAnnotationProcessor;

/** Main class to test the Annotations  
 *   @author         Y.Kamesh Rao 
 */
public class AnnotationExample {
    @NullValueValidate(paramName = "testVar1") private String testVar1;
    @NullValueValidate(paramName = "testVar2") private String testVar2;


    public AnnotationExample() {
        testVar2 = "Testing the Null Value Validation...It Works...!";         
        
        // Calling the processor to process the annotations applied         
        // on this class object.         
        NullValueValidateAnnotationProcessor.processAnnotations(this);     
    }     
    
    public static void main(String args[]) {
        AnnotationExample ae = new AnnotationExample();     
    }
}

IV] Output

Processing the field:testVar1 
Value of the Object:Testing the Null Value Validation...It Works...!
Processing the field:testVar2 
The value of the field private java.lang.String annotation.AnnotationExample.testVar2 cannot be NULL.
java.lang.NullPointerException:The value of the field private java.lang.String annotation.AnnotationExample.testVar2 cannot be NULL.
        at annotation.processor.NullValueValidateAnnotationProcessor.processAnnotation(NullValueValidateAnnotationProcessor.java:66)
        at annotation.AnnotationExample.(AnnotationExample.java:28)
        at annotation.AnnotationExample.main(AnnotationExample.java:33)

V] Conclusion I had a lot of fun doing this sample annotation program and now I have implemented many custom made Annotations to load properties from property files, validations of database field lengths, etc. Annotations greatly reduces the verbosity of the code thus making it much simpler and readable. Annotations can be used for logging, generating code dependent deployment descriptors and other mechanical and repetitive jobs. I had a lot of fun compiling this article for you guys. I hope you benefit from it.

View comments Tags: programming annotations java 5

Mar 1 '09

Laptop Pointers

This post is written by: Dhaval Motghare (http://www.dhavalmotghare.com)

Well a lot of people ask me about everything from a say a USB drive to Floor standers while making a purchase, but lately it seems a lot many of them have a laptop purchase on their mind. So for all those I have compiled a list of pointers which one should look for when going for a laptop. Hope this helps.


To start with every thing at least in a laptop boils down to a size, weight and battery life. You might not agree with me on this but believe me once you use a laptop for a few months you would. Also never consider laptop a desktop replacement, its not all about the money, you can buy a laptop powerful enough to replace your desktop, but such a laptop would break your back when there is need to carry it, it would weigh at least 4 kilos. Also a battery back up of 1-1.5 hrs is the max you would get from it. This is not what a laptop is for, a laptop should weigh in the range of 1.5-2.7 kgs depending on budget, it should give you a battery back up in the range of 2-5hrs. and should have a size which is at least practical enough to carry around. So considering the above points I have a few suggestions for the components that should go into a laptop.

 

First and the foremost the processor, avoid AMD at any cost they are cheap but are not powerful and most importantly have a very high TDP rating (heat up a lot and are a drain on the battery), consider the new core 2 duo series from Intel, if possible avoid the 5xxx and 7xxx series and go for the 8xxx and 9xxx series if the budget permits, if you are a little tight on budget go for the 7xxx series, the new 8xxx and above series are from a new family (penryn) and built on a 45 nm process so they are more efficient and have a lower TDP.

8100, 8300 or P8400 are a good choice.

 

Secondly the primary memory, 2 GB is decent enough, at most 3 GB, anything more than that is waste of money since anything more than 3 GB lies unused. Rather than getting more memory concentrate on the FSB speed, 800 MHz is a good choice, but don’t go below 667 MHz.

 

Graphics - These days you do need to pay attention to graphics as well, and this has nothing to do with gaming, most computers now come preloaded with windows vista which has this unnecessary but nevertheless present UI enhancement like Aero effect (transparent windows) and flip 3D (3D space based window switching) which are heavy for onboard graphics, so for vista to run decently on your system you need a graphics subsystem at least a little better than what on board graphics has to offer. There are two choices nVidia and ATI (AMD), considering the points I mentioned earlier you should avoid nVidia 9xxx series and go for 8xxx series, the two options available are 8400 and 8600, similarly form ATI anything above 3400 is best avoided again for the aforementioned reasons.
As I said don’t use a laptop as a desktop replacement, so it goes without saying that its best not to use laptops for gaming, but with the graphic cards I mentioned earlier you could play most of the games at low resolutions.

 

Screen size - According to me at least you should avoid anything bigger than 15 inches, the ideal size being 13.3 inches, but again that’s your call, just remember that the screen size is inversely proportional to weight and battery life. You should also consider the new LCD displays which have a LED backlight, again this are expensive but good for battery life.

 

Secondary memory - The capacity is entirely your call, but do consider what the rpm is, the best bet is 5400 rpm anything below and the performance is affected and anything above is taxing on battery life with no noticeable improvement in performance. 

 

Other miscellaneous details (Bluetooth, biometric security, camera etc) don’t affect the either the size or the battery or weight but only the price so that’s for you to decide, one more thing which is most important at least for me is looks, more often than not I make suboptimal decisions which are purely motivated by the looks of the product. So I am not the right person to go to if looks are not important for you.
Still other things which maybe useful to some people are don’t expect too much from the onboard speakers, if you do want to use your laptop as entertainment device choose a laptop which has a blue ray drive with HDMI and optical out as I/O ports, then pair them with a LCD display and a decent pair of speakers.

 

Regarding the brands available, avoid all Indian brands (HCL, Wipro, Zenith etc), also avoid brands like (Compaq, Acer, LG, Samsung), the brands I trust are Sony, Dell, HP, Toshiba, Fujitsu etc not necessarily in that order. One thing I didn’t mention here was Apple, since apple has such a low penetration in India or for that matter the whole world that it’s no brainer to avoid it. But it does make some amazing products, the Mac book pro being one of them, it’s a awesome laptop which comes preloaded with leopard and I must say here that once you use leopard you would never use anything again, so if you are not put off by the premium price apple commands do give it a shot.

22 notes View comments Tags: hardware laptops gadgets

Feb 25 '09

Hello World

Welcome to orangeapple.org..! We would collaborate here to mainly talk about Apple and its amazing Products and Technologies. This Apple is Orange cause we are coming to you, out of Nagpur in INDIA which is also famous to be the Orange City. We will review and preview amazing Apple products like the MacBook, iMacs, iPhone and iPods.

But more than Apple fanatics, we are tech geeks at heart and mind. This is one of the reasons we appreciate and celebrate the sheer genius that goes into making Apple products. We would speak and share about any tech stuff we may come across and think that it deserves to be placed here.

Most of us here write software programs to eat those burgers and biryanis we love. We program for the iPhone and iPod touch using the Cocoa Touch Framework, for websites and desktops using Java and MySQL, for Mobiles using Symbian, J2ME, Windows Mobile and BREW. Hence, you may also stumble upon posts about these technologies, some sample code and solutions to common problems.

Expect from us -

  1. Tech reviews and previews of various hardware and software products and solutions
  2. Code examples for Spring, Hibernate, SQL, Java, C, C++, Flex, Actionscript, Javascript, CSS, Objective C, iPhone SDK and more
  3. Tips and Tricks for Linux and Mac OSX
  4. And a lot of hate stuff for Windows

You will see the posts coming in pretty soon. So check back or subscribe to the RSS feed and be the part of ‘Think Different’ revolution.

View comments Tags: announcements news