Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, August 1, 2011

First touch of Java 7

Java 7 is here... and there are many improvements. But as a developer, what we can use on day to day use.. 

1. Strings in Switch 
  - Long waited feature. Makes life much simpler in many ways. Till Java 5, the handling was terrible by defining constants integers or characters and we tend to improve with enums on Java 5 and now finally to match with real world identities 

2. Multi catch exceptions
 Another graceful feature. Reduces lot of code duplication.

3. Try with resources.
   Whenever we access resources we do with try catch finally block, where we release the resources [closing the connections etc] at finally block. With this feature, there will be no need of such finally blocks. The resources on try will automatically released after the try block resulting in much cleaner code.

There are much more with collections, file API, and concurrency features. Will update soon. 

package org.nava.java7;


import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.System.out;


/**
 *
 * @author nadhimoolam
 */
public class ProjectCoinTest {


    public static void main(String args[]) {
        String condition = "BLue";
        testSwitch(condition);
        tryWithMulti();
        tryWithResources(new File("source"), new File("target"));
    }


    private static void testSwitch(String condition) {
        switch (condition.toLowerCase()) {
            case "blue":
            case "red":
                out.println("The choice is " + condition);
                break;
            default:
                out.println("Default ");
        }


    }


    private static void tryWithMulti() {
        try {
            File f = new File("Is this file exists ");
            throw new FileNotFoundException();
        } catch (NullPointerException | FileNotFoundException e) {
            out.println("It should be either null pointer or file not found " + e);
        } catch (Throwable t) {
            out.println("Its throwable now  " + t);
        } finally {
            out.println("Finally.");
        }
    }


    private static void tryWithResources(File source, File target) {
        try (InputStream fis = new FileInputStream(source);
                OutputStream fos = new FileOutputStream(target)) {


            byte[] buf = new byte[8192];


            int i;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        } catch (Exception e) {
            out.println("Exception on trying the resources..." + e);
        }
    }
}

Tuesday, July 12, 2011

ConcurrentTesting - Advanced Testing for Multi-Threaded Applications

IBM has created a tool for testing, debugging, and coverage-measuring of concurrent programs.

Concurrent Testing

Friday, July 8, 2011

Memcached with Java in Windows

Recently I got a chance to review design of using memcached in our J2EE application. To start with I tried the cache my windows 7 development environment.

Albeit, the cache mechanism has its own limitations, certainly its one of the simplest key-value in memory cache that can scale for large applications. Facebook uses this cache on around 900 dedicated servers to scale up its needs.

The memcached comes with application exe for windows and its very easy to install, start and stop the services.

One can also use telnet to access the server and its cache content.

Java

More info on installation: Memcached for Windows
Integration with Java : Java Integration
Memcached Java Client : spymemcached


I will try to post my sample code soon.

Thursday, June 23, 2011

Groovy Integration with Ant

Recently I come across a requirement to execute few SQL statements during the build process. Initially we thought of executing a shell/perl script to perform the job. Then we explored the power of dynamic JVM based scripting languages.. and here comes Groovy.

It jells with Ant very well and very good support for SQL operations, including executing a stored procedures. Adding groovy to your project is very simple and straight forward. Also, since groovy is much similar to java, literally there is no learning curve.

Check out the simplified and start grooving for your petty project needs....


<project name="GroovyBuild" basedir="." default="testGroovy">
<property name="jdbc.url" value="jdbc:oracle:thin:@yourdb"/>
<property name="jdbc.username" value="username"/>
<property name="jdbc.password" value="pass"/>
<path id="groovypath">
<pathelement location="C:\lib\groovy-all-1.8.0.jar"/>
<pathelement location="C:\lib\ojdbc14.jar"/>
</path>
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="groovypath"/>
<target name="setupDB">
<echo message="Test Groovy Started.."/>
<groovy>
import groovy.sql.Sql
def jdbcUrl = "${properties['jdbc.url']}"
def user = "${properties['jdbc.username']}"
def password = "${properties['jdbc.password']}"

def sql = Sql.newInstance("${jdbcUrl}","${user}","${password}","oracle.jdbc.driver.OracleDriver")

project.addReference("groovy.sqlinstance", sql)
</groovy>
</target>
<macrodef name="read">
<sequential>
<groovy>
def sql = project.getReference("groovy.sqlinstance")
println "TestName - Updatetime"
sql.eachRow("select testname,to_char(updatetime) as updatetime from groovy_test order by updatetime") {
println "${it.testname} - ${it.updatetime}"
}
</groovy>
</sequential>
</macrodef>
<macrodef name="add">
<sequential>
<groovy>
def name = 'test3'
def sql = project.getReference("groovy.sqlinstance")
try {
sql.execute("insert into groovy_test(testname,updatetime) values(${name},sysdate)")
} catch(Exception e){}
</groovy>
</sequential>
</macrodef>
<macrodef name="update">
<sequential>
<groovy>
def sql = project.getReference("groovy.sqlinstance")
try {
sql.execute("update groovy_test set updatetime = sysdate+1 where testname='test1'")
} catch(Exception e){}
</groovy>
</sequential>
</macrodef>
<target name="testGroovy" depends="setupDB">
<add/>
<update/>
<read/>
<echo message="Test Groovy Completed successfully.."/>
</target>
</project>



Sunday, May 15, 2011

Project Lombok

  • Do you have lot of POJO in your project and need to write getters/setters?
  • Do you want clean POJOs with default hashCode and Equals implementations?
  • Do you expect a cleaner way to express your POJO? 

Here is an attempt for all these expectations.

Project Lombok

Thursday, April 28, 2011

Dynamic Implementation for Interface

Legacy class implements my interface and everytime I change my interface, i had to change the legacy class as well to provide a default implementation and to get rid of my compilation issues

I want a default implementation to be applied to this legacy class whenever I add new methods to my interface.

And, I still want the legacy class to be a child of my interface

How do I get around this problem.?

Sunday, March 6, 2011

Powerful alternative to Java Date API

Java Date API is inherently so buggy. If you are looking at the source code, you will really regret how you can rely on that.

If you really want to work with Dates extensively, consider using Joda Time API. Its free and wonderful.

Joda Time

Serializing Java MimeMessage

Why doesn't the MimeMessage class implement Serializable so that I can serialize a message to disk and read it back later?

The JavaMail API was designed to layer on top of existing email systems, using existing message formats. The ability to use Java serialization was neither essential nor useful for such implementations, and thus was not considered a goal of the JavaMail API.

The hard part about serializing a Message is retaining the pointers to the Folder, Store and Session. If you only want to save the content of the message, and not the object itself, the writeTo method of a message gives your everything you need. If you want to create an entire email system based on serialized messages, you should be able to subclass Message et. al and implement Serializable in your subclass.

If you want to serialize other objects of your own that reference MimeMessages, the writeObject method of your object can use the writeTo method of MimeMessage, and the readObject method of your object can use the MimeMessage constructore that takes an InputStream. Your class will need to provide a Session when constructing the MimeMessage.

Tuesday, November 23, 2010

Twitter4J - Twitter Integration

Interesting pure Java API to fully integrate with Twitter API.

The highlight of the API is asynchronous requests/listeners.

http://twitter4j.org

Tuesday, November 16, 2010

How to execute JavaScript in Java

Java 6 provides full fledged scripting support. There is a in-built Mozilla Rhino Javascript engine available in JDK6 and JRE6.

Scripting is recommended in many large scale applications for Sophisticated configurations and ease of maintenance.

Using scripting from the Java platform is easy because the API is relatively small. You can quickly add scripting support to your application using only a handful of interfaces and classes in the javax.script package.

Following code quickly enables your Java environment to run a Java script.


ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval("print('Hello, world!')");
} catch (ScriptException ex) {
ex.printStackTrace();
}


More Details

Saturday, September 18, 2010

How to conduct J2EE Interviews

Recently I had opportunity to interview few candidates for one of our J2EE projects. I was surprised to know Java guys are forgetting the fundamentals and just becoming laborers of APIs. With the advent of IDEs,API knowledge also weakening. So are we headed?

In this juncture, a common web developer just knows how to utter few geek framework keywords and expects to land on a job. This does not seems to be good progress. This motivates to me share few topics on conducting interviews/achieving success in interviews.

Last not the least, here your have few refresh courses

http://www.geekinterview.com/Interview-Questions/J2EE
http://www.roseindia.net/interviewquestions/

Tuesday, March 11, 2008

Open Source Gateway Initiative[OSGi] - A Middleware Revolution!

Finally,world realizes the true purpose of Object Orientation - the Re-Usability and today any software development largely consists of adapting existing functionality to perform in a new environment,since large number of standard, well-tested building blocks have become readily available from various vendors.

Now, the core problem is, integration of many different libraries-(building blocks)as these libraries have become complex and require their own libraries to function --even if that functionality is never needed for the product.

This propels the need for tools/frameworks/specifications that standardize the integration aspects of software so that reusing existing components becomes reliable, robust and cheap.

There comes our OSGi!!!!!!!!!!!!!!

So what is OSGi?

A nonprofit organization-founded in March 1999- comprises of IBM,Ericsson,Nortel,Sybase,Sun,France Telecom,Motorola and Phillips that promotes an open dynamic component platform.

The objective of this Alliance is : "How to let applications from different vendors work reliably together and share resources in an embedded/network computer"

OSGi specifies JVM - (now only Java)- based service platform - so that software components/applications/modules/bundles can be remotely installed, started, stopped, updated and uninstalled without requiring a reboot;

Why JVM as Platform
Without any doubts, JVM is evovling as unanimous platform going forward for multi-layered, multi-faceted enterprise applications. Not only Java,but there are many other languages evovling on JVM [Current JVM Languages - PHP,Scala,Groovy,Ruby,Python]and certainly the list is growing day-by-day.

Speficiation - Overview

OSGi technology is the dynamic module system for Java™. The OSGi Service Platform provides functionality to Java that makes Java the premier environment for software integration and thus for development. Java provides the portability that is required to support products on many different platforms. The OSGi technology provides the standardized primitives that allow applications to be constructed from small, reusable and collaborative components. These components can be composed into an application and deployed.

The OSGi Service Platform provides the functions to change the composition dynamically on the device of a variety of networks, without requiring restarts. To minimize the coupling, as well as make these couplings managed, the OSGi technology provides a service-oriented architecture that enables these components to dynamically discover each other for collaboration. The OSGi Alliance has developed many standard component interfaces for common functions like HTTP servers, configuration, logging, security, user administration, XML and many more. Plug-compatible implementations of these components can be obtained from different vendors with different optimizations and costs. However, service interfaces can also be developed on a proprietary basis.

OSGi technology adopters benefit from improved time-to-market and reduced development costs because OSGi technology provides for the integration of pre-built and pre-tested component subsystems. The technology also reduces maintenance costs and enables unique new aftermarket opportunities because components can be dynamically delivered to devices in the field.

Framework

The core component of the OSGi Specifications is the OSGi Framework. The Framework provides a standardized environment to applications (called bundles). The Framework is divided in a number of layers.

L0: Execution Environment
L1: Modules
L2: Life Cycle Management
L3: Service Registry A ubiquitous security system is deeply intertwined with all the layers.

The L0 Execution environment is the specification of the Java environment. Java 2 Configurations and Profiles, like J2SE, CDC, CLDC, MIDP etc. are all valid execution environments. The OSGi platform has also standardized an execution environment based on Foundation Profile and a smaller variation that specifies the minimum requirements on an execution environment to be useful for OSGi bundles.

The L1 Modules layer defines the class loading policies. The OSGi Framework is a powerful and rigidly specified class-loading model. It is based on top of Java but adds modularization. In Java, there is normally a single classpath that contains all the classes and resources. The OSGi Modules layer adds private classes for a module as well as controlled linking between modules. The module layer is fully integrated with the security architecture, enabling the option to deploy closed systems, walled gardens, or completely user managed systems at the discretion of the manufacturer.

The L2 Life Cycle layer adds bundles that can be dynamically installed, started, stopped, updated and uninstalled. Bundles rely on the module layer for class loading but add an API to manage the modules in run time. The lifecycle layer introduces dynamics that are normally not part of an application. Extensive dependency mechanisms are used to assure the correct operation of the environment. Life cycle operations are fully protected with the security architecture, making it virtually impossible to be attacked by viruses.

The L3 layer adds a Service Registry. The service registry provides a cooperation model for bundles that takes the dynamics into account. Bundles can cooperate via traditional class sharing but class sharing is not very compatible with dynamically installing and uninstalling code. The service registry provides a comprehensive model to share objects between bundles. A number of events are defined to handle the coming and going of services. Services are just Java objects that can represent anything. Many services are server-like objects, like an HTTP server, while other services represent an object in the real world, for example a Bluetooth phone that is nearby. The service model is fully security instrumented. The service security model provides an elegant way to secure the communication between bundles passes.

Security
Security is based on Java and the Java 2 security model. The language by design limits many possible constructs. For example, buffer overflows used in viruses are impossible. Access modifiers in the language restrict the visibility of the code to other programmers. The OSGi platform extends this model by allowing private classes, a mechanism that is not available in a standard way in Java. The Java 2 security model provides a comprehensive model to check access by code to resources. The OSGi platform adds full dynamic management of the permissions, simplifying the life of operators and system administrators.

It Is SOA!
On top of the Framework, the OSGi Alliance has specified many services. Services are specified by a Java interface. Bundles can implement this interface and register the service with the Service Registry. Clients of the service can find it in the registry, or react to it when it appears or disappears.

This is similar to the service-oriented architecture made popular with web services. The key difference between web services and OSGi services is that web services always require some transport layer, which makes it thousands times slower than OSGi services that use direct method invocations. Also, OSGi components can directly react on the appearance and disappearance of services.

Examples:

Http Service
The Http Service is, among other things, a servlet runner. Bundles can provide servlets, which becomes available over the Http protocol. The dynamic update facility of the OSGi Service Platform makes the Http Service a very attractive web server that can be updated with new servlets, remotely if necessary, without requiring a restart.


Active participants:
Apache iFelix, iPojo, Spring - OSGi, Eclipse - Equinox


Whats new on OSGi-Release 4:

Powerful new modularization capabilities providing enhanced encapsulation of networked services that can share a single VM.

Modularized class sharing and hiding of implementation details.
Advanced handling of multiple versions of the same classes so old and new applications can execute within the same VM.

Localization of OSGi bundle manifests enabling service deployment anywhere.

Enhancements in security and policies: The new Conditional Permission Admin service provides an elegant and simple way to manage networked services securely. It also supports dynamic policies that can depend on external (custom) conditions. Combined with R4 support for digital signatures, this provides a central security solution to large deployments of products using the OSGi Service Platform.

A Declarative Services specification that addresses memory footprint issues that can prevent small embedded devices from using a service oriented architecture to support multiple applications. Additionally, it significantly simplifies the service-oriented programming model by declaratively handling the dynamics of services.

Compatibility with Release 3, requiring no changes for existing OSGi bundles, applications, or services.

Future is here...
The OSGi specifications are so widely applicable because the platform is a small layer that allows multiple Java™ based components to efficiently cooperate in a single Java Virtual Machine (JVM). It provides an extensive security model so that components can run in a shielded environment. However, with the proper permissions, components can reuse and cooperate, unlike other Java application environments. The OSGi Framework provides an extensive array of mechanisms to make this cooperation possible and secure.

The presence of OSGi technology-based middleware in many different industries creates a large software market for OSGi software components. The rigid definition of the OSGi Service Platform enables components that can run on a variety of devices, from very small to very big.

Adoption of the OSGi specifications can therefore reduce software development costs as well as provide new business opportunities.


Courtesy : ACM Queue Jan-Feb 2008 , Wiki

Sunday, July 29, 2007

Nava-Why Strings are Immutable?

In Java, String object is defined as immutable...meaning it cannot be changed, everytime you change the object [concatenate,replace etc], VM actually creates a new string object and update the references if required

[code]
String x="Nava";
x=x+" World";
S.O.P(x); // Nava World
/* Here actually three String objects are created--"Nava", "World" and "Nava World" and x is refrenced to third object, whereas other two String objects do not have any references which can be considered as "Lost" */
[/code]

I used to wonder, why such a concept "immutability" used in Java for String object.....and finally got elucidated.

Strings are the most commonly used objects in any programming languages, especially in Java. In terms of memory usage, they are on the top most place.

JVM designers well considered this aspect and constructed a special area of memory called the "String constant pool". When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.The existing String simply has an additional reference.

Ah! I hear how you appreciate.. why making String objects immutable is such a good idea.If several reference variables refer to the same String,without even knowing it, it would be bad if any of them could change the String's value.

Cool..but what if one overides the String Object? ..well String is a FINAL class :-)