View RSS Feed

All Blog Entries

  1. Custom annotations - Adding a member

    by , 10-31-2011 at 06:45 PM (My Java Tips)
    Annotation types can have member variables. You will understand its importance when you use annotations for metadata, not just raw documentation. These member variables provides very useful information to code-analysis tools.

    Data members in annotation types are set up to work using limited information. The way to add member is to define a single method that should be named after the member which you want to allow for. The data type should be the return value of the ...
  2. Custom annotations - default values

    by , 10-31-2011 at 06:40 PM (My Java Tips)
    I'll focus on setting some default values for the annotation.

    Yes, you want the users to specify values for the annotations but only if their values differ some default values. Default values should be provided to make things easier.

    The following example shows how one can associate default values with custom annotations.

    Java Code:
    package com.domain.tiger.a;
    // Annotation type with default values
    public @interface GroupTODO {
  3. Annotating an annotation

    by , 10-31-2011 at 06:32 PM (My Java Tips)
    I will briefly write about annotating annotations. You should have good idea about the set of predefined annotation types we have seen in the last few posts.

    When you start writing your own annotation types, the main purpose of your annotation types is to provide basic documentation. Also you write annotation types that are specific to a certain member type,
    or perhaps a certain set of member types. This requires you to supply some sort of metadata on your annotation type, ...
  4. Adding public documentation

    by , 10-31-2011 at 06:24 PM (My Java Tips)
    Documented is a meta-annotation and its a marker annotation. A marker annotations have no member variables.

    Documented annotation is used to indicate that an annotation should appear in the Javadoc for a class. Remember that the default behavior is that annotations are not included in Javadocs. The presented example shows what the Documented meta-annotation looks like in use:

    Java Code:
    package com.domain.tiger.a;
    import java.lang.annotation.Documented;
  5. Setting up inheritance

    by , 10-31-2011 at 06:19 PM (My Java Tips)
    Inherited is a meta-annotation that is complicated as compared to other annotations. It is least-often used.

    Let me present a scenarios for better understanding: Suppose that you use your custom annotation called InProgress to mark a class as being in progress.
    If the Documented meta-annotation is applied correctly, then this will show up in the Javadoc. All is well till here.

    Suppose you write a new class and extend the in-progress class. Now remember one this: ...
  6. Java Persistence API - annotations

    by , 10-31-2011 at 06:15 PM (My Java Tips)
    The Java Persistence API heavily depends on the metadata annotations. The API consists of:

    Java Persistence API
    The Java Persistence query language
    Metadata annotations

    An entity is a persistence object. It is coded as a POJO, and marked as an entity with the @Entity (javax.persistence.Entity) annotation. By default, all properties/fields are persisted into the datastore, except those marked with the @Transient annotation. Following example shows few annotations ...
  7. SAX is underneath most XML processing

    by , 10-31-2011 at 06:08 PM (My Java Tips)
    SAX is a simple API for XML and is largely used because it is very popular because almost all XML processing involves SAX at some level.

    SAX is blazing fast and has been around for a while. XML is fairly easy to work with, but it's not an intuitive language in lots of ways. Most of the XML parsers these days use SAX since it already works pretty well.
    SAX is great at parsing XML. And if you know how to handle errors in SAX, then you know how to handle errors in almost any XML ...
  8. JAXP exposes SAX

    by , 10-31-2011 at 06:04 PM (My Java Tips)
    Many of you must be using JAXP API, the Java API for XML Processing for XML processing.

    The code below shows a fragment that uses JAXP for some SAX parsing.

    Java Code:
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    parser.parse(new File(args[0]), new MyHandler());
    This surely looks similar ...
  9. Categories of annotations

    by , 10-31-2011 at 05:57 PM (My Java Tips)
    There are three categories of annotations namely Marker, Single-Value and Full annotation.

    Let me present these one by one:

    Marker annotations

    There annotations have no variables. These are identified by name, with no additional data supplied. For example:


    Single-value annotations

    These are similar to markers, but also provide a single piece of data. You can only ...
  10. Broken Pipe - Transaction

    by , 10-31-2011 at 05:51 PM (My Java Tips)
    I assume that you are having a J2EE environment with connection pool and you are using hibernate.

    When you use transactions, you have to explicitly commit or rollback every time. Some programmers believe that queries do not have to be committed. This is not right in my opinion. If you do not commit, the connection is left assigned. Which means we have dangling connections that later will be killed by the database server like: MySQL. Connection pool would later attempt to reattach ...
  11. Hibernate Session

    by , 10-31-2011 at 05:44 PM (My Java Tips)
    Declaring your hibernate session as static is not a good idea because a session/connection does not have an endless lifetime.

    If you have static hibernate session, change it to dynamic. Everytime you want to run one or more transactions at once, obtain a new session object from sessionfactory. The given code shows
    static hibernate session. A new session will be created when getSession() is called for the first time. In the later calls, the same session will be returned. ...
  12. Using pagging techniques

    by , 10-30-2011 at 06:59 PM (My Java Tips)
    When displaying long lists on the web, we use paging techniques. In this post, I will show how to do that.

    Normally we display 10 or 15 results at a time and the user can scroll through the list. If list is a long one, then it does not make an sense to loat it completely. Loading the complete list in session and then loop through the results is not a nice approach. An approach can be to use pagination tags which means fetching and displaying the results one page at a time. Pagination ...
    Java EE , JSF , JSP
  13. Setting up hibernate.cfg.xml

    by , 10-30-2011 at 06:50 PM (My Java Tips)
    Hibernate.cfg.xml is a configuration file that is put in the project's root directory and it has to be put into class path as well.

    A sample cfg file for MySQL is given below. Do change the database URL, database name, username and password.

    <!--?xml version='1.0' encoding='UTF-8'?-->
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    ""&gt; ...
  14. Hibernate - Mapping files

    by , 10-30-2011 at 06:45 PM (My Java Tips)
    Mapping files are there to map entities with the database tables. In this post, I will present 2 sample mapping files.

    Mapping file for MySql is given below:
    <pre lang="java">
    <!--?xml version="1.0" encoding="UTF-8"?-->

    <class name="com.domain.example.Student" table="student">
    <id name="id" column="id" type="java.lang.Integer"> ...
  15. Java to JSON

    by , 10-30-2011 at 06:43 PM (My Java Tips)
    Creating JSON or XML from Java is simple. I'll show some short code sample.

    Java Code:
    Person p = new Person();
    JSONSerializer serializer = new JSONSerializer();
    String json = serializer.serialize( p );
    Created JSON String:

    Java Code:
       "class": "Person",
       "name": "William Shakespeare",
       "birthday": -12802392000000,
       "nickname": "Bill"
  16. HiveMind

    by , 10-30-2011 at 06:41 PM (My Java Tips)
    HiveMind is a services and configuration microkernel. I will elaborate this point in this post.

    HiveMind allows services which are actually POJOs (Plain Old Java Objects) to be easily accessed and combined. You should use interfaces to work with HiveMind because each service defines a Java interface it implements. Instantiating and configuring of each service just as necessary is handled by HiveMind. It allows these services to collaborate with each other via dependency injection. ...
    HiveMind , Software
  17. Log method entry and exit

    by , 10-30-2011 at 06:39 PM (My Java Tips)
    The typical approach we use in Java is given below:

    Java Code:
    public String myMethod(String param)
      if (LOG.isDebugEnabled())
        LOG.debug("myMethod(" + param + ")");
    String result = // . . .
    if (LOG.isDebugEnabled())
      LOG.debug("myMethod() returns " + result);
    return result;

    This will work ...
    HiveMind , XML
  18. StringBuilder

    by , 10-30-2011 at 06:32 PM (My Java Tips)
    Java 5 introduces StringBuilder which implements Serializable and CharSequence interfaces. It represents a mutable sequence of characters.

    StringBuilder is an API compatible with StringBuffer, but with no guarantee of synchronization. Following are the available constructors:

    Java Code:
    StringBuilder(CharSequence seq)
    StringBuilder(int capacity)
    StringBuilder(String str)
    This can be used in place of StringBuffer ...
    Java SE
  19. java.util.Locale

    by , 10-30-2011 at 06:27 PM (My Java Tips)
    Locale object deals with the geographical details. Different parts of the world have different languages, currencies and time zones. There are some operations that are different for different geographical areas. These are referred as locale-sensitive operations. These operations uses Locale to tailor the information according to the needs.

    Representing numbers is a locale-sensitive operation as formatting of number is different in different parts of the world. The example below prints ...
    Java SE
  20. Using prepaid statements

    by , 10-30-2011 at 06:22 PM (My Java Tips)
    SQL statements are executed on a database tables using Statement object. If the sql statement takes parameter, then it is a wise decision to use PreparedStatement as they are more flexible and makes coding easier.

    Creating SQL statements that take parameters provides flexible statements to work with. We can use the same statement and supply it with different values each time we execute it.
    We use place holders (question marks) in the query, which are supplied values to make ...
  21. Using Batches in JDBC

    by , 10-30-2011 at 06:18 PM (My Java Tips)
    Updating a record from Java using executeUpdate() method of Statement object is used commonly by JDBC programmers. Thing to note is that this is a costly activity in terms of time, as a database trip is made. As a programmer/developer, our aim should be to write efficient Java code. In this post, I will write about how you can efficiently make several updates.

    Batch update allows us to execute several update statements in a batch. It means only one database trip will be make, thus ...
  22. Logical Operators

    by , 10-30-2011 at 06:08 PM (My Java Tips)
    Following are logical operators that one can use in Java programming.

    ! Is not…
    ^ Exclusive Or…
    | Or… (bitwise)
    & And… (bitwise)
    || Or… (short cut, see &&)
    && And

    In this Java programming tutorial, I will code And, Or and Not operators as they are commonly used.

    Java Code:
    int a= 15;
    int b = 25;
    if(a<10 || b>10)
    System.out.println("Entered: Java
    Java SE
  23. Content Assist

    by , 10-30-2011 at 06:05 PM (My Java Tips)
    Eclipse provides content assist that really can save lot of development time. For instance putting try catch blocks where needed, for loop to iterate over an array/list etc.

    Key stokes required: Ctrl-Space

    Here is a list of useful things that can be done using content assistant:

    - Code completion, name completion, etc.
    - Does lots of useful completions in different contexts. Try it!
    - When the cursor is among the methods of a class declaration, ...
  24. Repositories

    by , 10-30-2011 at 05:48 PM (My Java Tips)
    In Maven, projects can share dependencies which means that different project can use common jar files.

    These jar files will be updated over time and Maven keeps each project current with the latest jar file. These jar files will be placed in a repository on a remote server and are accessed by the projects. These files will be mirrored in a local repository under the Maven installation. The remote repository location is given in the file which is located in your Maven ...
    Maven , XML
  25. Hibernate - SessionFactory

    by , 10-29-2011 at 08:44 PM (My Java Tips)
    We are writing an application that will use Hibernate to manage our application persistence object. We will need a SessionFactory which creates or open a session to talk to a database.

    Creating SessionFactory is easy. We can define the configuration in, hibernate.cfg.xml or create it programatically. I will present an example that will use the hibernate.cfg.xml configuration file, which is mostly use when creating Hibernate application.

    Below is ...

    Updated 10-29-2011 at 08:47 PM by Java Tip

  26. ThreadLocal

    by , 10-29-2011 at 08:36 PM (My Java Tips)
    I will present an example that shows how to start, stop, suspend, and resume threads.

    It uses the Runnable interface because it extends from Applet class and multiple inheritance is not allowed. This example uses a thread that counts and prints a string every second. The thread starts when the applet is initialized. It continues to run until the user leaves the page. If the user returns to the page (and all is well), the thread continues from where it left off. This allows applets ...
    Glassfish , Java SE
  27. The Thread Class

    by , 10-29-2011 at 08:29 PM (My Java Tips)
    java.lang.Thread is used to create and control threads. A new instance of this class must be created to use a new thread. Once a thread is created, it does not start running right away. Thread.start() must be called to actually make the thread run. On calling Thread.start(), the thread begins executing in the run() method of the target class.

    Remember that a new Thread class always starts running the public void run() method of a class. There are two ways to create a thread:

    Updated 10-29-2011 at 08:32 PM by Java Tip

    Java ME , Java SE
  28. Java Threads - synchronized

    by , 10-28-2011 at 08:27 PM (My Java Tips)
    In multithreaded environment, data may be corrupted. A was to prevent this is to prevent the interruption of critical regions.

    You have to fidn the critical region in your code which you think should be accessed by one thread at a time. Java's synchronized is used to ensure that only one thread is in a critical region at once. When the thread enters a synchronized code block, it locks on that region and no other thread can enter the critical region as long as the lock is released. ...
    Java SE
  29. View all keyboard shortcuts

    by , 10-28-2011 at 08:22 PM (My Java Tips)
    You need to know shortcut keys to speed up your work when working in Eclipse. In this post, Ill tell you how to view currently available key bindings.

    In Eclipse, just press Ctrl+Shift+L to see a full list of the currently available key bindings. This is a great way to learn what is available in the UI and to speed up your productivity by learning more key bindings. This information is also available in the improved General > Keys preference page.

    Name:  keycompletions.gif
Views: 371
Size:  12.3 KB ...
  30. Eclipse - Key Binding Assistance

    by , 10-28-2011 at 08:20 PM (My Java Tips)
    Using keyboard shortcuts while working in Eclipse saves a lot of effort. But some shortcuts are not easy to remember and some comprise of multiple keys like: Alt+Shift+Q Y" ("Open Synchronize View").

    Eclipse provides a little pop-up showing you the possible completions for the keys you have pressed already. In the preferences, under General > Keys, there is an "Advanced" tab. Go to this tab, and check "Help Me With Multi-Stroke Keyboard Shortcuts". ...
Page 14 of 17 FirstFirst ... 41213141516 ... LastLast