Tuesday, October 2, 2012

What is an Annotation in Java!???


Java annotations are used to provide meta data for your Java code. Being meta data, the annotations do not directly affect the execution of your code, although some types of annotations can actually be used for that purpose.

Java annotations were added to Java from Java 5. This text covers Java annotations as they look in Java 6. As far as I know, Java annotations have not changed in Java 7, so this text should be valid for Java 7 programmers too.

Here is a list of the topics covered in this text:


Java Annotation Purposes

Java annotations are typically used for the following purposes:
  • Compiler instructions
  • Build-time instructions
  • Runtime instructions
Java has 3 built-in annotations that you can use to give instructions to the Java compiler. These annotations are explained in more detail later in this text.
Java annotations can be be used at build-time, when you build your software project. The build process includes generating source code, compiling the source, generating XML files (e.g. deployment descriptors), packaging the compiled code and files into a JAR file etc. Building the software is typically done by an automatic build tool like Apache Ant or Apache Maven. Build tools may scan your Java code for specific annotations and generate source code or other files based on these annotations.
Normally, Java annotations are not present in your Java code after compilation. It is possible, however, to define your own annotations that are available at runtime. These annotations can then be accessed via Java Reflection, and used to give instructions to your program, or some third party API.


Annotation Basics

An annotation in its shortest form looks like this:
@Entity
The @ character signals to the compiler that this is an annotation. The name following the @character is the name of the annotation. In the example above the annotation name is Entity.


Annotation Elements

Annotations can have elements for which you can set values. An element is like an attribute or parameter. Here is an example of an annotation with an element:
@Entity(tableName = "vehicles")
The annotation in this example contains a single element named tableName, with the value set tovehicles. Elements are enclosed inside the parentheses after the annotation name. Annotations without elements do not need the parentheses.
An annotation can contain multiple elements. Here is an example:
@Entity(tableName = "vehicles", primaryKey = "id")
In case an annotation contains just a single element, it is convention to name that element value, like this:
@InsertNew(value = "yes")
When an annotation just contains a single element named value, you can leave out the element name, and just provide the value. Here is an example:
@InsertNew("yes")


Annotation Placement

You can put Java annotations above classes, interfaces, methods, method parameters, fields and local variables. Here is an example annotation added above a class definition:
@Entity
public class Vehicle {
}
The annotation starts with the @ character, followed by the name of the annotation. In this case, the annotation name is Entity. The Entity annotation is an annotation I have made up. It doesn't have any meaning in Java.
Here is a bigger example with annotations above both the class, fields, methods, parameters and local variables:
@Entity
public class Vehicle {

    @Persistent
    protected String vehicleName = null;


    @Getter
    public String getVehicleName() {
        return this.vehicleName;
    }

    public void setVehicleName(@Optional vehicleName) {
        this.vehicleName = vehicleName;
    }

    public List addVehicleNameToList(List names) {

        @Optional
        List localNames = names;

        if(localNames == null) {
            localNames = new ArrayList();
        }
        localNames.add(getVehicleName());

        return localNames;
    }

}
The annotations are again just annotations I have made up. They have no specific meaning in Java.


Java's Builtin Annotations

Java comes with three annotations which are used to give the Java compiler instructions. These annotations are:
  • @Deprecated
  • @Override
  • @SuppressWarnings
Each of these annotations are explained in the following sections.


@Deprecated

The @Deprecated annotation is used to mark a class, method or field as deprecated, meaning it should no longer be used. If your code uses deprecated classes, methods or fields, the compiler will give you a warning. Here is an example:
@Deprecated
public class MyComponent {

}
The use of the @Deprecated annotation above the class declaration marks the class as deprecated.
You can also use the @Deprecated annotation above method and field declarations, to mark the method or field as deprecated.
When you use the @Deprecated annotation, it is a good idea to also use the corresponding@deprecated JavaDoc symbol, and explain why the class, method or field is deprecated, and what the programmer should use instead.


@Override

The @Override annotation is used above methods that override methods in a superclass. If the method does not match a method in the superclass, the compiler will give you an error.
The @Override annotation is not necessary in order to override a method in a superclass. It is a good idea to use it still, though. In case someone changed the name of the overridden method in the superclass, your subclass method would no longer override it. Without the @Overrideannotation you would not find out. With the @Override annotation the compiler would tell you that the method in the subclass is not overriding any method in the superclass.
Here is an example use of the @Override annotation:
public class MySuperClass {

    public void doTheThing() {
        System.out.println("Do the thing");
    }
}


public class MySubClass extends MySuperClass{

    @Override
    public void doTheThing() {
        System.out.println("Do it differently");
    }
}
In case the method doTheThing() in MySuperClass changes signature so that the same method in the supclass no longer overrides it, the compiler will generate an error.


@SuppressWarnings

The @SuppressWarnings annotation makes the compiler suppress warnings for a given method. For instance, if a method calls a deprecated method, or makes an insecure type cast, the compiler may generate a warning. You can suppress these warnings by annotating the method containing the code with the @SuppressWarnings annotation.
Here is an example:
@SuppressWarnings
public void methodWithWarning() {


}


Creating Your Own Annotations

It is possible to create your own annotations. Annotations are defined in their own file, just like a Java class or interface. Here is an example:
@interface MyAnnotation {

    String   value();

    String   name();
    int      age();
    String[] newNames();

}
This example defines an annotation called MyAnnotation which has four elements.
Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.
To use the above annotation, you do like this:
@MyAnnotation(
    value="123",
    name="Jakob",
    age=37,
    newNames={"Jenkov", "Peterson"}
)
public class MyClass {


}
As you can see, I have to specify values for all elements of the MyAnnotation annotation.


Element Default Values

You can specify default values for an element. That way the element becomes optional and can be left out. Here is an example of how the annotation definition looks with a default value for an element:
@interface MyAnnotation {

    String   value() default "";

    String   name();
    int      age();
    String[] newNames();

}
The value element can now be left out when using the annotation. If you leave it out, it will be considered as if you had used the default value for the value element. Here is an example:
@MyAnnotation(
    name="Jakob",
    age=37,
    newNames={"Jenkov", "Peterson"}
)
public class MyClass {


}
Notice that the value element is no longer present.


@Retention

You can specify for your custom annotation if it should be available at runtime, for inspection via reflection. You do so by annotating your annotation definition with the @Retention annotation. Here is how that is done:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)

@interface MyAnnotation {

    String   value() default "";

}
Notice the annotation added above the MyAnnotation definition:
@Retention(RetentionPolicy.RUNTIME)
This is what signals to the compiler and JVM that the annotation should be available via reflection at runtime. Accessing annotation at runtime is covered in my Java Reflection and Annotations tutorial, which is part of my Java Reflection Tutorial.
The RetentionPolicy class contains two more values you can use:
RetentionPolicy.CLASS means that the annotation is stored in the .class file, but not available at runtime. This is the default retention policy, if you do not specify any retention policy at all.
RetentionPolicy.SOURCE means that the annotation is only available in the source code, and not in the .class files and not a runtime. If you create your own annotations for use with build tools that scan the code, you can use this retention policy. That way the .class files are not poluted unnecessarily.


@Target

You can specify which Java elements your custom annotation can be used to annotate. You do so by annotating your annotation definition with the @Target annotation. Here is an example:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
public @interface MyAnnotation {

    String   value();
}
This example shows an annotation that can only be used to annotate methods.
The ElementType class contains the following possible targets:
  • ElementType.ANNOTATION_TYPE
  • ElementType.CONSTRUCTOR
  • ElementType.FIELD
  • ElementType.LOCAL_VARIABLE
  • ElementType.METHOD
  • ElementType.PACKAGE
  • ElementType.PARAMETER
  • ElementType.TYPE
Most of these are self explaining, but a few are not. Therefore is here an explanation of the few that are not obvious.
The ANNOTATION_TYPE target means annotation definitions. Thus, the annotation can only be used to annotate other annotations. Like the @Target and @Retention annotations.
The TYPE target means any type. A type is either a class, interface, enum or annotation.


@Inherited

The @Inherited annotation signals that a custom annotation used in a class should be inherited by subclasses inheriting from that class. Here is an example:
java.lang.annotation.Inherited

@Inherited
public @interface MyAnnotation {

}
@MyAnnotation
public class MySuperClass { ... }
public class MySubClass extends MySuperClass { ... }
In this example the class MySubClass inherits the annotation @MyAnnotation becauseMySubClass inherits from MySuperClass, and MySuperClass has a @MyAnnotation annotation.


@Documented

The @Documented annotation is used to signal to the JavaDoc tool that your custom annotation should be visible in the JavaDoc for classes using your custom annotation. Here is an example:
java.lang.annotation.Documented

@Documented
public @interface MyAnnotation {

}
@MyAnnotation
public class MySuperClass { ... }
When generating JavaDoc for the MySuperClass class, the @MyAnnotation is now included in the JavaDoc.
You will not use the @Documented annotation often, but now you know it exists, if you should need it.

Thanks to  Jakob Jenkov.

Thursday, September 13, 2012

Issue in Setting HTTP Proxy for SVN!!!

For setting the HTTP proxy for SVN the regular setting of http_proxy environment variable would not work.

i.e. export http_proxy=http://my-proxy-server.com:8080/ would not work.
There is a “servers” file in svn which is present at the following location

Win : C:\Documents and Settings\krishna\Application Data\Subversion\servers
Linux: /etc/subversion/servers or /home/krishna/.subversion/servers

Here you need to set the proxy server and port settings so that command line SVN can access the external world form the proxy. Uncomment and change the lines necessary

[global]
# http-proxy-exceptions = *.exception.com, www.internal-site.org
http-proxy-host = myproxy.us.com
http-proxy-port = 8080

# http-proxy-username = defaultusername
# http-proxy-password = defaultpassword
# http-compression = no
# http-auth-types = basic;digest;negotiate
# No http-timeout, so just use the builtin default.
# No neon-debug-mask, so neon debugging is disabled.
# ssl-authority-files = /path/to/CAcert.pem;/path/to/CAcert2.pem

If you get something like
svn:/home/krishna/.subversion/servers:73: Option expected

then it means that you have a space at the start of the property which you have un-commented. Make sure that there is no space in the beginning of the property in the servers file.

I've struggled alot for few mins ... then came to know that, this is an issue with xml parsing in svn!!! It is very Picky!!!

Monday, September 10, 2012

SSH Problem: ssh_exchange_identification: Connection closed by remote host


Are you tired of getting the exception ssh_exchange_identification: Connection closed by remote host even if the key is correct !?????? 

Then here are few tips to rectify that ...!!

1) Check the permission of /var/log/btmp, it must be 600 
    chmod 600 /var/log/btmp

now
ll /var/log/btmp
-rw------- 1 root utmp 73026817 Jan 11 11:13 btmp

Check now....!!! Still not solved !!?????

2) /var/empty/sshd must be owned by root and not group or world-writable
chown -R root:root /var/empty/sshd

Now  
ll  /var/empty/sshd 
-rw------- 1 root utmp 73026817 Jan 11 11:13 sshd

Then Try, U must be logged-in !!!

Have FUN!!!

Sunday, September 2, 2012

FTP Server config on linux

FTP Server

File Transfer Protocol (FTP) is a TCP protocol for uploading and downloading files between computers. FTP works on a client/server model. The server component is called an FTP daemon. It continuously listens for FTP requests from remote clients. When a request is received, it manages the login and sets up the connection. For the duration of the session it executes any of commands sent by the FTP client.
Access to an FTP server can be managed in two ways:
  • Anonymous
  • Authenticated
In the Anonymous mode, remote clients can access the FTP server by using the default user account called "anonymous" or "ftp" and sending an email address as the password. In the Authenticated mode a user must have an account and a password. User access to the FTP server directories and files is dependent on the permissions defined for the account used at login. As a general rule, the FTP daemon will hide the root directory of the FTP server and change it to the FTP Home directory. This hides the rest of the file system from remote sessions.

vsftpd - FTP Server Installation

vsftpd is an FTP daemon available in Ubuntu. It is easy to install, set up, and maintain. To install vsftpd you can run the following command:
sudo apt-get install vsftpd

Anonymous FTP Configuration

By default vsftpd is configured to only allow anonymous download. During installation a ftp user is created with a home directory of /home/ftp. This is the default FTP directory.

If you wish to change this location, to /srv/ftp for example, simply create a directory in another location and change the ftp user's home directory:
 
sudo mkdir /srv/ftp
sudo usermod -d /srv/ftp ftp 

After making the change restart vsftpd:
sudo /etc/init.d/vsftpd restart

Finally, copy any files and directories you would like to make available through anonymous FTP to /srv/ftp.

User Authenticated FTP Configuration

To configure vsftpd to authenticate system users and allow them to upload files
edit /etc/vsftpd.conf:
local_enable=YES
write_enable=YES

Now restart vsftpd:
sudo /etc/init.d/vsftpd restart

Now when system users login to FTP they will start in their home directories where they can download, upload, create directories, etc.
Similarly, by default, the anonymous users are not allowed to upload files to FTP server. To change this setting, you should uncomment the following line, and restart vsftpd:
 
anon_upload_enable=YES
[Warning]
Enabling anonymous FTP upload can be an extreme security risk. It is best to not enable anonymous upload on servers accessed directly from the Internet.
The configuration file consists of many configuration parameters. The information about each parameter is available in the configuration file. Alternatively, you can refer to the man page, man 5 vsftpd.conf for details of each parameter.

Securing FTP

There are options in /etc/vsftpd.conf to help make vsftpd more secure. For example users can be limited to their home directories by uncommenting:
 
chroot_local_user=YES
 
You can also limit a specific list of users to just their home directories:
 
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list

After uncommenting the above options, create a /etc/vsftpd.chroot_list containing a list of users one per line. Then restart vsftpd:
 
sudo /etc/init.d/vsftpd restart

Also, the /etc/ftpusers file is a list of users that are disallowed FTP access. The default list includes root, daemon, nobody, etc. To disable FTP access for additional users simply add them to the list.

FTP can also be encrypted using FTPS. Different from SFTP, FTPS is FTP over Secure Socket Layer (SSL). SFTP is a FTP like session over an encrypted SSH connection. A major difference is that users of SFTP need to have a shell account on the system, instead of a nologin shell. Providing all users with a shell may not be ideal for some environments, such as a shared web host.

To configure FTPS, edit /etc/vsftpd.conf and at the bottom add:
ssl_enable=Yes

Also, notice the certificate and key related options:
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key

By default these options are set the certificate and key provided by the ssl-cert package. In a production environment these should be replaced with a certificate and key generated for the specific host. For more information on certificates see the section called “Certificates”.

Now restart vsftpd, and non-anonymous users will be forced to use FTPS:
sudo /etc/init.d/vsftpd restart
To allow users with a shell of /usr/sbin/nologin access to FTP, but have no shell access, edit /etc/shells adding the nologin shell:
 
# /etc/shells: valid login shells
/bin/csh
/bin/sh
/usr/bin/es
/usr/bin/ksh
/bin/ksh
/usr/bin/rc
/usr/bin/tcsh
/bin/tcsh
/usr/bin/esh
/bin/dash
/bin/bash
/bin/rbash
/usr/bin/screen
/usr/sbin/nologin

 This is necessary because, by default vsftpd uses PAM for authentication, and the /etc/pam.d/vsftpd configuration file contains:
auth    required        pam_shells.so

The shells PAM module restricts access to shells listed in the /etc/shells file.
Most popular FTP clients can be configured connect using FTPS. The lftp command line FTP client has the ability to use FTPS as well.

References

Friday, August 24, 2012

Take Rest for JIRA!!!


Yesterday when I was going through some article, I saw lots requests and comments for JIRA REST JAVA Client!!!

I wondered and decided to provide the REST JAVA API for JIRA, and this is the one.

Connecting to JIRA using JAVA REST API is really a very easy thing like Ice Cream Sandwich ;) :)  and can be written in a plain vanilla flavor.

Today I'm providing you the search operation functionality to get the tickets.


/**
     * Gets all the issues based on the query and displays .... !!!!
     *
     * @param username the username
     * @param password the password
     * @param url the url
     * @return the all issues
     * @throws AuthenticationException the authentication exception
     * @throws JSONException the jSON exception
     */
    private static void getAllIssues(String username, String password, String url)    throws AuthenticationException, JSONException
    {
        final String auth = new String(Base64.encode(username + ":" + password));
        final Client client = Client.create();
        final WebResource webResource = client.resource(url);
        final ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
                .accept("application/json").get(ClientResponse.class);
        final int statusCode = response.getStatus();
        if (statusCode == 401)
        {
            throw new AuthenticationException("Invalid Username or Password");
        }
        final String stringResponse = response.getEntity(String.class);
        System.out.println("sr: " + stringResponse);
    }

Usage of the above method:
1) getAllIssues("krishna", "krishna", "http://server:8080/rest/api/latest/search?jql");

fetches all the issues.. !!!

2)  getAllIssues("krishna", "krishna", " http://server:8080/rest/api/latest/issue/Issue-84?expand=schema,names,transitions");

It gets all the issue whose key is Issue-84.... !!!

Have FUN...!!!!

Wednesday, March 28, 2012

Asynchronous Web Service Call in Android Native Application


Recently I was exploring ways of calling a web service asynchronously in Android. I was looking for an option that would work along the lines of XMLHttpRequest AJAX request in Javascript.
Following is one way of doing it
To execute an asynchronous task, Android OS itself provides a class called AsyncTask<Params, Progress, Result> which enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Having said that we can extend the class like  below
public class RemoteCallTask extends AsyncTask<String, Void, ArrayList<String>>
{
RemoteCallListener listener = null;
private final HttpClient httpClient = new DefaultHttpClient();
private String responseText;
public RemoteCallTask(RemoteCallListener listener)
{
this.listener = listener;
}
@Override
protected ArrayList<String> doInBackground(String… urls)
{
ArrayList<String> arrayList;
// Call the webservice and assume the response is JSONArray
// Construct the array list and return
return arrayList;
}
protected void onPostExecute(final ArrayList<String> arrayList)
{
// The returned arraylist in doInBackground() will be sent as an input
parameter here
// Now call the listener’s onRemoteCallComplete method and set the value.
listener.onRemoteCallComplete(arrayList);
}
}
The RemoteCallListener referred in the above code is an interface which looks like below
public interface RemoteCallListener
{
public void onRemoteCallComplete(ArrayList<String> arrayList);
}
Now wherever you need to call the web service do the following things
1) Implement the RemoteCallListener interface.
2) Provide an implementation for onRemoteCallComplete() method.
3) Call the AsyncTask like below
new RemoteCallTask(this).execute(url);
Now the webservice response will be received in onRemoteCallComplete() method.
That’s all.  Please let me know if there is any other better method to achieve this.

Creating Web Application in Android


The following article talks about creating an offline web application in Android using android.webkit package.

Android – application debug logging


Following content is referenced from
http://www.winksaville.com/blog/programming/debug-logging-in-android/
Here are a couple of places that got me started. First the standard java logging mechanism doesn’t work. In addition System.out.print doesn’t work. You need to use the android.util.log.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
@StateMachine
public class test extends Activity
{
/** Called with the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
Log.v(TAG, “onCreate: E”);
setContentView(R.layout.main);
Log.v(TAG, “onCreate: X”);
}
private static final String TAG = “test”;
}
The Log class supports various levels (VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT) the low-level routine is Log.println(int priority, String tag, String msg). But typically the v, d, i, w, e and a convince routines would be used. So that’s half the game, the other half is to be able to see the output. For that you use “logcat”. In Eclipse if you goto menu “Window/Show View/other/Android/logcat” or if your in the Debug perspective it will be in “Window/Show View/logcat”. Apparently, its not very reliable in Eclipse and executing:
adb logcat
Allows you to see it from a command line, but in Eclipse the log also includes a Date stamp which makes it nice. I was able to get the Eclipse/logcat going by closing than reopening. Of course you mileage may very:) If you look at the links above it appears you can use ddms, but I haven’t used that yet.

Enabling Internet Connection Through Proxy in Android in Windows


Steps for Android 1.5
Following content is referenced from
In the earlier versions of Android emulators (up to version 1.1r2), you were required to make an entry in the system table of“com.android.provider.setting.db” database and/or start the emulator with –http-proxy switch supplying it the IP address and port number of your proxy.
These methods however, have become obsolete and don’t work with SDKv1.5.
Step 1: On emulator, go to:
Home->Menu->Settings->WirelessControls->MobileNetworks->Access Point Names->T-mobile US->set Proxy IP and Port#
Step 2: Now the next time you go to a web address, the browser will prompt for your user-id and password. Enter your credentials and you should be good to go.
Steps for Android 2.2
1) Create an emulator with name say android_2.2_emulator using AVD manager in eclipse.
2) Create a batch file (.bat) with following command and a keep a handy shortcut.
emulator -avd “android_2.2_emulator” -http-proxy “your_proxy_url”:”port”
3) Run the batch file before starting the eclipse IDE, so that the emulator session will have internet connection.
That’s it.