Monday, February 20, 2012

OSGi for Beginners

Open Services Gateway initiative framework (OSGi)

1. What is OSGi ?
 
OSGi is a specification. The core of the OSGi specification defines a component and service model for Java. The components and services can be dynamically activated, de-activated, updated and de-installed.
A very practical advantage of OSGi is that every bundle must define its exported Java packages and its required dependencies. This way you can effectively control the provided API and the dependencies of your plug-ins.

OSGi bundles:

The OSGi specification defines the OSGi bundle as the unit of modularization.
A bundle is a cohesive, self-contained unit, which explicitly defines its dependencies to other modules and services. It also explicitly defines its external API.

Technically OSGi bundles are .jar files with additional meta information. This meta 
information is stored in the "META-INF" folder in the "MANIFEST.MF" file.
bundle = identity & dependency info + jar

The "MANIFEST.MF" file is part of a standard jar specification to which OSGi adds additional metadata. Any non-OSGi runtime will ignore the OSGi metadata. Therefore OSGi bundles can be used without restrictions in non-OSGi Java environments.

Bundle-SymbolicName and Version:

Each bundle has a symbolic name which is defined via the Bundle-SymbolicName property. and a version number in the Bundle-Version property.
The Bundle-Version and the Bundle-SymbolicName uniquely identifies a bundle in OSGi.Both properties are defined in the "MANIFEST.MF" file.
 
Bundle dependencies and public API:

Via the "MANIFEST.MF" file a bundle can define its dependency to other bundles or packages. OSGi will throw a ClassNotFoundException, if a class from a bundle tries to access a class without a defined dependency to it.
 
In the MANIFEST.MF file a bundle also defines the Java packages which should be exported and therefore available to other bundles (as API). Packages which are not exported are not visible to other bundles.

All these restrictions are enforced via a specific OSGi classloader. Each bundle has its own classloader. Access to restricted classes is not possible, also not via reflection.

A bundle can define that it depends on a certain version (or a range) of another bundle, e.g. bundle A can define that it depends on bundle C in version 2.0, while bundle B defines that it depends on version 1.0 of bundle C.

Bundle Lifecycle:

With the installation of a bundle in the OSGi runtime this bundle is persisted in a local bundle cache. The OSGi runtime is then trying to resolve all dependencies of the bundle.
If all required dependencies are resolved the bundle is in the status "RESOLVED" otherwise it is in the status "INSTALLED".
If several bundles exist which would satisfy the dependency, then the bundle with the highest version is taking. If the versions are the same, then the bundle with the lowest ID will be taken. If the bundle is started, its status is "STARTING". Afterwards it gets the "ACTIVE" status.


OSGi offers the following advantages:

Reduced complexity: Developing OSGi means developing modules ie bundles. They hide their internals from other bundles and the communication is through well defined interfaces.Hence the later changes can be easily accommodated without affecting other modules.

Reuse : The OSGi component model makes the integration of third party components very easy.

You can install, uninstall, start, and stop different modules of your application dynamically without restarting the container.

Your application can have more than one version of a particular module running at the same time.

OSGi provides very good infrastructure for developing service-oriented applications, as well as embedded, mobile, and rich internet apps. 

Some of the currently popular implementations of the OSGi specs :

Apache Felix:
Eclipse Equinox
Knopflerfish

Popular application servers which use OSGi technology :

Weblogic – Oracle Weblogic Application Server
WebSphere – IBM Websphere JEE Application Server

REFERENCE:

Thursday, February 16, 2012

Java Reflection: Annotations

What are Java Annotations?

Annotations is a new feature from Java 5. Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection. The annotation can be attached to Classes, Methods,Parameters,Fields etc.

How to create custom Annotation?

To create an annotation we use the interface keyword and add an @ symbol infront of it. The @ symbol will tell the compiler that it doing some business with an annotation.

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
The @ in front of the interface marks it as an annotation. Once you have defined the annotation you can use it in your code.Here is an example of class annotation:
@MyAnnotation(value="Class Annotation")
public class MyClass {
}
The two directives in the annotation definition, @Retention(RetentionPolicy.RUNTIME) and @Target(ElementType.TYPE), specifies how the annotation is to be used. 
  @Retention(RetentionPolicy.RUNTIME) means that the annotation can be accessed via reflection at runtime. If you do not set this directive, the annotation will not be preserved at runtime, and thus not available via reflection.

@Target(ElementType.TYPE) means that the annotation can only be used ontop of types (classes and interfaces typically). You can also specify METHOD or FIELD, or you can leave the target out alltogether so the annotation can be used for both classes, methods and fields.
 

Class Annotations

You can access the annotations of a class, method or field at runtime. Here is an example that accesses the class annotations:

Class aClass = MyClass.class;
Annotation[] annotations = aClass.getAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
    }
}
You can also access a specific class annotation like this:

Class aClass = MyClass.class;
Annotation annotation = aClass.getAnnotation(MyAnnotation.class);

if(annotation instanceof MyAnnotation){
    MyAnnotation myAnnotation = (MyAnnotation) annotation;
    System.out.println("value: " + myAnnotation.value());
}

Method Annotations

Here is an example of a method with annotations:
public class MyClass {
  @MyAnnotation(value = "Method Annotation")
  public void doSomething(){}
}
 
You can access method annotations like this:

Method method = ... //obtain method object
Annotation[] annotations = method.getDeclaredAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
    }
}
 
You can also access a specific method annotation like this:

Method method = ... // obtain method object
Annotation annotation = method.getAnnotation(MyAnnotation.class);

if(annotation instanceof MyAnnotation){
    MyAnnotation myAnnotation = (MyAnnotation) annotation;
    System.out.println("value: " + myAnnotation.value());
}


Parameter Annotations

It is possible to add annotations to method parameter declarations too. Here is how that looks:


public class MyClass {
  public static void doSomethingElse(
        @MyAnnotation(value="Parameter Annotation") String parameter){
  }
}
 
You can access parameter annotations from the Method object like this:

Method method = ... //obtain method object
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Class[] parameterTypes = method.getParameterTypes();

int i=0;
for(Annotation[] annotations : parameterAnnotations){
  Class parameterType = parameterTypes[i++];

  for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("param: " + parameterType.getName());
        System.out.println("value: " + myAnnotation.value());
    }
  }
}
 
Notice how the Method.getParameterAnnotations() method returns a two-dimensional Annotation array, containing an array of annotations for each method parameter.

Field Annotations

Here is an example of a field with annotations:

public class MyClass {
  @MyAnnotation(value = "Field Annotation")
  public String myField = null;
}
 
You can access field annotations like this:

Field field = ... //obtain field object
Annotation[] annotations = field.getDeclaredAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
    }
} 
 
You can also access a specific field annotation like this:


Field field = ... // obtain method object
Annotation annotation = field.getAnnotation(MyAnnotation.class);

if(annotation instanceof MyAnnotation){
    MyAnnotation myAnnotation = (MyAnnotation) annotation;
    System.out.println("value: " + myAnnotation.value());
}



The whole tutorial is on the github:
https://github.com/abdulwaheed18/Annotation-Tutorial

Friday, January 27, 2012

How to install libflashplayer.so on linux

When we trying to install the flash player for your linux operating system, we download file libflashplayer.so but we do know where to put this file.

This article guild you step by step to install the flash player for linux.


Step 1: Go to Adobe website and download you suitable version of flash player libflashplayer.so 32-bit/64bit . Then extract it to libflashplayer.so File.

Step 2:
cd to the folder has file libflashplayer.so and install
  • If you are using FireFox:
  • sudo mv libflashplayer.so /usr/lib/mozilla/plugins/libflashplayer.so
     
  • If you are using Google Chrome + Firefox
sudo mv libflashplayer.so /usr/lib/mozilla/plugins/libflashplayer.so
    sudo mkdir /opt/google/chrome/plugins
    sudo cp /usr/lib/flashplugin-installer/libflashplayer.so 
    /opt/google/chrome/plugins
Thanks.

Wednesday, January 18, 2012

Basic Linux Commands



*) How to extract tr.gz. file
To extract one or more members from an archive :
             tar -zxvf {file.tar.gz}

For example, If your tar name is backup.tar.gz, enter the following at a shell prompt:
             tar -zxvf backup.tar.gz



*) How to run .bin file

Change the permission of the file you downloaded to be executable. Type the following command:
              $ chmod +x file.bin

Start the installation process or run .bin file.Type the following command:
             ./file.bin

For example if .bin file name is application.bin. Type:
        $ chmod +x application.bin
        $ ./application.bin



*) How to set a BASH variable equal to the output from a command?

Use $(), which I find easier to read, and allows for nesting.
        OUTPUT=$(ls -1) echo $OUTPUT


*) How to read IP Address In a Shell Script

Type the following command:

ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'


*) How to find out particular ProcessId
                  ps -ef | grep processname
                  eg: ps -ef | grep mysql


*) How to display Line number from a file
          sed -n "linenumber p" file.txt
          sed -n "3 p" file1.txt

*) How to check Hidden file
          ls -a

*) How to check port
         netstat -tulpn


*) How to find directory on linux?
        find / -name 'httpdocs' -type d

the first parameter "/" is where to look, in this case "/" it's the entire system.
-name could be -iname to ignore case also -type is not mandatory
use : man find for more option


*) How to check free RAM size ?
                  free -m


*) How to clear cache memory ? 
        echo 1 > /proc/sys/vm/drop_caches

*) How to check linux version
              cat /proc/version

*) How to check which all service is running ?
                   intictl list 
For a particular service
                   intictl list | grep nova




Wednesday, January 4, 2012

How to Set JAVA_HOME / PATH variables Under Linux

After installing Java Development Kit on Linux/Unix, you may still need to do some configuration to get Java ready for running or compiling Java programs. The following instruction will guide you through the process of setting up JDK for software development.

In Linux, ~/.bash_profile is a startup script which generally runs once. This particular file is used for commands which run when the normal user logs in. Common uses for .bash_profile are to set environment variables such as PATH, JAVA_HOME, to create aliases for shell commands, and to set the default permissions for newly created files.

Set JAVA_HOME / PATH for single user

Login to your account and open .bash_profile file
$ cd $HOME
$ vi ~/.bash_profile

Set PATH and JAVA_HOME as follows:
 
PATH=$PATH:$HOME/bin:/usr/jdk1.6.0_30/bin
JAVA_HOME=/usr/jdk1.6.0_30


Note: Don't delete the previous PATH, Just append the jdk path after : like "/usr/jdk1.6.0_30/bin" as above .

export PATH
export JAVA_HOME

Save and close the file. Just logout and login back to see new changes:
$ echo $JAVA_HOME
$ echo $PATH


Tip: Use the following command to find out exact path to which java executable under UNIX / Linux:
$ which java


How to set JAVA PATH on Windows

Sunday, December 11, 2011

How to enable SSL on apache Tomcat 7.0

This tutorial shows how to enable SSL support for Apache Tomcat web server.
Requirement

*) Apache Tomcat 5.0
*) JDK 1.5

Note: if you have JDK below 1.4, you need to install Java Secure Socket Extensions (JSSE)

To install and configure SSL support on Tomcat, you need to follow these simple steps.


Generating the KeyStore file:

*) Create a keystore file to store the server's private key and self-signed certificate by executing the following    
    command.
*) Enter command line and change directory to your JAVA\bin folder. (Default path is: C:\Program    
    Files\Java\jre6\bin).
*) Type “keytool –genkey –alias tomcat –keyalg RSA" and press Enter.
        Where tomcat is an alias name and RSA is a key algorithm.
*) Type your password for the keystore. (Default password is: changeit). In this example, I’ll use password as “password"

Enter general information about this Certificate. The example is the image below. In the last line, Enter key password for (tomcat) should be the same as you enter before.Note that this information will be displayed to users who attempt to access a secure page.



*) The file .keystore will be created on your account. (Currently, I use administrator account so it’ll be in  
    C:\Documents and Settings\Administrator).
    I have copied the .keystore file and placed in tomcat folder.

Configure Tomcat:
*) Open server.xml in Tomcat\conf folder. (Default path is: C:\Program Files\Apache Software  
     Foundation\Tomcat x.x\conf).
*) Uncomment the paragraph below this line

<!-- Define a SSL HTTP/1.1 Connector on port 8443 This connector uses the JSSE configuration, when using APR, the connector should be using the OpenSSL style configuration described in the APR documentation -->

Add new attribute 

    keystoreFile="PATH\TO\KEYSTORE\.keystore"
    keystorePass=”password” to the Connector element. If you haven’t change keystore’s password, you    
               don’t have to add this attribute.
   Chnage protocol="org.apache.coyote.http11.Http11NioProtocol"

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" keystoreFile="C:\software\apache-tomcat-7.0.23-windows-x64\apache-tomcat-7.0.23\.keystore" keystorePass="password" />

*) Save and restart Apache Tomcat service.

Test the result:

Open browser and navigate to the Apache Tomcat server with https://localhost:8443

Thursday, December 8, 2011

Java Date, Calendar and Time API - Tutorial


The Calendar class’ date/time API is a nifty tool for accurately manipulating date and time values without too much stress or custom coding. It provides direct support for time based objects. This article gives a few examples how this API can be used. .

The class java.util.Date was the first implementation which was used for manipulating dates. The class java.util.Calendar was added in Java 1.1 and provides simplified access to storing and manipulating dates.
It is recommended to use Calendar if possible. In reality you have to convert frequently from Date to Calendar and vice versa, e.g. during database access you often get a java.sql.Date object. The following explains how to use Calendar and how to convert Dates into Calendar.

It also offers a set of methods for converting and manipulating temporal information. In addition to retrieving the current date and time, the Calendar class also provides an API for date arithmetic. The API takes care of the numerous minor adjustments that have to be made when adding and subtracting intervals to date and time values.

Calendar’s built-in date/time arithmetic API is extremely useful. For example, consider the number of lines of code that go into calculating what the date will be five months from today. Try doing this yourself — you need to know the number of days in the current month and in the intervening months, as well as make end-of-year and leap year modifications to arrive at an accurate final result. These kinds of calculations are fairly complex and are quite easy to get wrong — especially if you’re a novice developer.


To format a date you can use the class SimpleDateFormat. For example to get today's date in the 'dd/MM/yy' format you can use:
  DateFormat df = new SimpleDateFormat("dd/MM/yy"); 
  String formattedDate = df.format(new Date());

To format the date in in the format 'yyyy/MM/dd' you can use.
  DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 
  String formattedDate = df.format(theDate);

Table 1. Calendar field access

FieldExplanationCalendar.YEAR Identifies the year
Calendar.MONTH Identifies the month
Calendar.DAY_OF_MONTH Identifies the day
Calendar.HOUR Identifies the hour
Calendar.MINUTE Identifies the minute
Calendar.SECOND Identifies the second

Tutorial is on GitHub: Timer Tutorial

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...