Friday, August 21, 2009

Enable remote desktop on LINUX system using VNC

set up required for enabling the remote desktop on LINUX machine using VNC

NOTE1: Enter all commands without the double quotes (")
NOTE2: if you encounter an error saying "command not found", just enter the full path of the executable and you should be fine.
NOTE3: Use your roor login for the entire set up

1. Open terminal and type "vncpasswd". It prompts for your password and also prompts for the password verification again. This ensures the password set up for the remote access for the current use.

2. Login as root using "su root"

3. Open the file /etc/sysconfig/vncservers. File can be opened in two ways:
a. "vi /etc/sysconfig/vncservers" OR
b. "gedit /etc/sysconfig/vncservers"

4. Look for the line that starts with # VNCSERVERS="1:myusername"
5. Uncomment the line (remove the #). This ensures the enabling of remote access to the user "myusername". If you want to enable more users for remote access, you can just have it something like "1:user1 2:user2 3:user3..."
6. save the file.
7. Now, you have to enable the VNC server on your machine using the command: "chkconfig vncserver on"
8. Start the VNC server using the command: "service vncserver start"
note: if the server is already running, you can restart using the command "server vncserver restart"
9. Now the set up is finished for the remote access. Make sure your firewall settings are in compliance to remote access.
Open Application => System Setting => Security level. and add "5901:tcp" to the other ports.
OR
Open system => administration => security and firewall and add "5901:tcp" to the other ports.

With this, installtion on LINUX machine is complted for enabling the remote access.

Set up to do in Windows machine:
1. Download VNC viewer at www.realvnc.com and install the same
2. Open vnc viewer, and it prompts for the server address:
enter ur server address the Server text box as "ipaddress:1" (xxx.xxx.xxx.xxx:1) here 1 is the number before username as shown in step4. You need to use the number that exists in that line of the vncservers file and click ok.
3. enter the password that you choose in step1.

With all this set up, You Are Ready to Access Your Redhat Linux machine from Windows machine.

After connecting to the redhat server, if the interface looks different, you just have to something more to get the real interface accessible through remote connection.
1. In your linux machine, open terminal and type "gedit /home/username/.vnc/xstartup"
2. uncomment (remove #) the two lines that starts with "unset" and "exec"
# unset SESSION_MANAGER
# exec /etc/X11/xinit/xinitrc
and save the file.
3. restart vncserver using the command "service vncserver restart" to apply changes
4. Now, reconnect using VNC viewer from windows machine and everything is ready to use on the Linux machine.

Saturday, August 15, 2009

ORM warnings: fail-safe cleanup messages

You often endup seeing the following warnings in the logs:
01:03:00,001 WARN [LoadContexts] fail-safe cleanup (collections) :
org.hibernate.engine.loading.CollectionLoadContext@103583b


OR

00:04:40,918 WARN [LoadContexts] fail-safe cleanup (collections) : org.hibernate.engine.loading.CollectionLoadContext@12f6fe9
<rs=com.ibm.db2.jcc.c.j@5a6c69>
These messages are expected and can simply ignore these warnings. These message related to the ORM technology you are using in the application and shows that how it cleanup up after itself avoid memory leaks.

Fix: You can even avoid these messages being displayed in the log by Upgrading your Hibernate jars to 3.x.x.

Difference between Set and List (Set vs List)

Set: an Interface available in "java.util" package.
  • a collection that cannot contain duplicate elements
  • generally order of the elements does not matter
  • models the mathematical set abstraction and is used to represent sets, such as the card comprising a poker hand
List: an Interface available in "java.util" package
  • a collection that can contain duplicate elements
  • it is an ordered collection, also called as a sequence
  • user of a List generally has control over where in (at what index) the List the user want to insert an element and access it using its index
When you access the Set using its Iterator, it doesn't guarantee the order of elements, whereas when you access the List using its Iterator, it gives you a sequential access to the elements in the list one by one.

For the better understanding, you can just execute the example program in my previous post "How Do I Convert Set into List".

Convert Calendar to Date

In one of the previous, date to calendar conversion was discussed. Following is the program to convert a Calendar (java.util.Calendar) object to Date (java.util.Date) object. The program can easily be understood by looking at the comments. You can even test drive the program directly.

Conversion from Calendar to Date is pretty easy:
1. given a calendar object, you just need to use the getTime() methos available in calendar class as the following:
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
That's it.

package com.blog.javaexposure.util;

import java.util.Date;
import java.util.Calendar;

public class Calendar2Date {
public static void main(String[] rags){
//get the current date as Calendar object
Calendar cal = Calendar.getInstance();
// returns the date object represented by Calendar object
Date date = cal.getTime();
System.out.println("Current date using \n calendar object: "+cal);
System.out.println("date object: "+date);
// if you want to a get tomorrow's date and calendar object, do the following
cal.add(Calendar.DATE, 1);
date = cal.getTime();
System.out.println("Tomorrows date using \n calendar object: "+cal);
System.out.println("date object: "+date);
}
}

Note: Wheh you look at the calendar object value in the output, you see all properties of the calendar object.

Jboss Error message while accessing the web service from client

I have recently encountered the following error. Rrror message looks something like this: "setProperty must be overridden by all subclasses of SOAPMessage". I did not understand what the Issue was. I bing it for a while, and came up with the solution. I just had to place the jboss-saaj.jar in "../jboss-home/lib/endorsed" directory. This library exists in "jboss-home/server/default/lib" directory
ERROR MESSAGE:
java.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage
at javax.xml.soap.SOAPMessage.setProperty(SOAPMessage.java:441)
at org.jboss.ws.core.soap.SOAPMessageImpl.(SOAPMessageImpl.java:82)
13:02:47,366 ERROR [RequestHandlerImpl] Error processing web service request
org.jboss.ws.WSException: java.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage
at org.jboss.ws.WSException.rethrow(WSException.java:68)
at org.jboss.wsf.stack.jbws.RequestHandlerImpl.handleRequest(RequestHandlerImpl.java:336)
RESOLUTION: copy "jboss-saaj.jar" from /jboss-home/server/default/lib to .../jbosshome/lib/endorsed folder

Monday, August 10, 2009

Convert Date to Calendar

Convert date to calendar:

Both Date and Calendar are availabel in java.util package. Date object represents the
specific instant of time. Calendar class is an abstract calss used for converting
between a Date object and a set of integer fields.. YEAR, MONTH,DAY, HOUR...etc.

Following example program converts a Date object into Calendar object.

This is achieved in the following steps:
1. getting the calendar instance.
Calendar cal = Calendar.getInstance();
2. getting the date object which you want to convert to Calendar object.
Assuming that we are going to convert the current date into calendar object,
Date d = new Date();
3. use the setTime(date) method available in Calendar class to convert the date to calendar object.
cal.setTime(d);

import java.util.Date;
import java.util.Calendar;

public class Date2Calendar {
public static void main(String[] rags){
Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date)
System.out.println("Current date is:"+cal);
}
}

Saturday, August 08, 2009

String versus StringBuffer



Generally, we use the String and StringBuffer classes for manipulating the character data. Both, String and StringBuffer are available in "java.lang" package.


String class is used to represent the character strings that cannot be changed. In other words, String type objects are read-only and immutable. StringBuffer objects represent the character strings that can be changed.

The other difference between the two is the performance. StringBuffer is much faster than that of String class when performing concatenations. Following lines of code is used to perform the concatenation.

String:
String string = new String("Java ");
string += "Language";

As String class is immutable, the initial string is first converted into StringBuffer and append the second string, then converts it back to String object using the toString() method.

StringBUffer: String buffer class has an "append()" method to concatenate the string data.
StringBuffer strBuf = new StringBuffer("Java ");
strBuf.append("Language");

First method - created three objects. initial String object, temporary StringBuffer and String object to hold the converted StringBuffer data.

Second method - everything is done with just one object creation, i.e. StringBuffer, and appends the data to the StringBuffer.

Overall, Using the StringBuffer there is no need of conversion from String->StringBuffer, and converting back to String, which is an expensive operation. So StringBuffer is a best option for developers to choose when they want to manipulate the character string data.

ArrayList vs Vector

Internally, Vector and ArrayList holds their contents using an array. From API point of view, vector and arraylist are very similar. Vectors are synchronized, where as ArrayList are not. Sometimes its better to use Vector, sometimes its better to user ArrayList. Your choice depends upon the needs. Following are the similarities and differences between the two.

Similarities between ArrayLists and Vectors

  • Both can grow up during run time.
  • Both implement List interface.
  • With both, it is easier to remove or add elements at the end or start, but if you try to add or remove elements somewhere at middle of collection, they suffer performance wise. (Use LinkedLists if your programme need to do that a lot, but LinkList requires more memory and computation)

Differences between ArrayLists and Vectors

  • The major difference is just that vectors are synchronized. This means that if more than one thread in your code is to use that data, you are in trouble with ArrayList as the data is asynchronous. Though there are ways by which you can make your ArrayLists synchronous, but by default they are not. The obvious downside with vectors is the additional computation to handle threads.
  • Vector contains many legacy methods that are not part of collection framework. With Java2 release, Vector reengineered to extend the class AbstractList and implements List interface, now it is fully compatible with collections framework.
  • The other difference is that with vectors, you can specify the incremental value, which is the amount with which the data structure will grow during the runtime. But with ArrayLists you have no option but to accept default that is the list will grow up 50% of original size everytime it needs additional space. It is advisable in both the cases to choose the initial size carefully.

Thursday, August 06, 2009

Converting an Array to a Set

To my knowledge we do not have any direct methods to convert from an array to a set. this To achieve this, we have to do the conversion process in two steps.
1. Converting an array to List
2. Converting the resulting List to a Set

Following program constructs an array with strings, String array is converted into a List using the asList method available in Arrays. Then the resulting list is converted into a Set.

---
package com.blog.javaexposure.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Array2Set {
public static void main(String rags[]){
// Creating a string array
String[] str = {"One","Two","Three","Four","
Five"};

// Convert array to List
List list = Arrays.asList(str);

System.out.println("Elements in the list are:");
//Checking the elements in the list
for(String s : list){
System.out.println(s);
}

// Convert list to set
Set set = new HashSet(list);

System.out.println("Elements in the set are:");
//Checking the elements in the set
for(String s : set){
System.out.println(s);
}
}
}

Converting an Array to a List

Java Collections API has very useful methods to play with all the data structures. Conversion between the collections made so easy.

following line of code converts an array into a list.
List list = Arrays.asList(str); // str is an array

Following program converts an array of strings into a List.

package com.blog.javaexposure.util;

import java.util.Arrays;
import java.util.List;

public class Array2List {

public static void main(String rags[]){
// Creating a string array
String[] str = {"One","Two","Three","Four","Five"};

// Convert array to List
List list = Arrays.asList(str);

System.out.println("Elements in the list are:");
//Checking the elements in the list
for(String s : list){
System.out.println(s);
}
}
}

Tuesday, August 04, 2009

How do I convert Set into List?

Conversion between the collections made pretty easy in Java.

Converting from a Set/List to List/Set can be done by passing the Set/List instance to the constructor of List/Set such as ArrayList/HashSet respectively.

Following line of code performs the conversion (from Set to List):

Set strSet = new HashSet();
strSet.add("one")
.
.
.
strSet.add("xxx");

List strList = new ArrayList(set);

Above List can be converted back to Set using the following line of code:

Set setObject = new HashSetst(strList);

Following is the example program that does the entire same thing we discussed above:
-----
package com.blog.javaexposure.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Set2List {

public static void main(String rags[]) {
// Creating a Set object
Set set = new HashSet();
// Adding elements to the Set object
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");

// Checking the elements in the Set
System.out.println("Elements in the set are:");
for (Object obj : set) {
System.out.println(obj);
}

// Creating a list object
List list = new ArrayList(set);

// Checking the elements in the list
System.out.println("Elements in the list are:");
for (Object obj : list) {
System.out.println(obj);
}
// Removing elements from the set
set.clear();
System.out.println("Number of elements in the set are: "+set.size());

// Converting list to set
set = new HashSet(list);

// Checking the elements in the Set
System.out.println("Elements in the set are:");
for (Object obj : set) {
System.out.println(obj);
}
}
}
-----

Monday, August 03, 2009

Accessing properties file for efficient read/write










In previous post, we did not use any third party libraries for accessing the properties file. Here, we will be using the apache commons configuration API. You have to download the jar file and add it to the classpath.

Reading from a properties file:

Use the following line of code if you just want to read the properties file.

Configuration config = new PropertiesConfiguration(propertiesFileName);

Then you need to use the various methods available to read the propeties. It has some flexible methods such as to get the string type of values, or integer or a list of values.

Detailed information about Configuration Interface can be found here: org.apache.commons.Configuration

Writing to a properties file:

You have to use the PropertiesConfiguration object to write to the properties file.

Detailed information about PropertiesConfiguration can be found here: org.apache.commons.configuration.PropertiesConfiguration

Use the following code:

PropertiesConfiguration config;
try{
config = new PropertiesConfiguration(propertiesFileName);
config.setProperty(propertyName, propertyValue); //to update properties
config.save(); //writes the changes to the file
}
Catch(ConfigurationException e){
System.out.println("Configuration exception");
}

When you write/update the properties this way,
1. properties order in the file doesn't change
2. comments stays the same

Other Uses: We can save a back up of the properties file using the following method.

config.save(backupFileName). //backupFileName is the name of the back up file to be created

Some useful info from apache website can be found here

Sunday, August 02, 2009

Accessing properties file in a java apps

Properties file is a simple text file. It contains a set of key-value pairs. Each key is associated with a key. We use properties file to store the configuration properties so that we dont need to touch the code again n again and recompile n run the entire app. just editing the properties file should be enough.

I used the following code to load properties from a properties file in J2EE application. Following code shows how to read the properties file and load the available properties into Java.Util.Properties Object.

/* Reading a properties file */

Properties props = new Properties();

//loading the properties from file into "props"
try{
props.load(new FileInputStream(fileName);
//filename should be a string. for ex, abc.properties
}
Catch(IOException e){
System.out.println("IO Exception occurres while accessing the properties file"+fileName);
}

"props" contains all the properties available in the file. i.e. key/value pairs. It simply ignores the comments, if any, available in the file.

Following code shows how to write the properties into a file.
try{
props.store(new FileOutputStream(fileName), null);
}
Catch(IOException e){
System.out.println("IO Exception while accessing the properties file"+fileName);
}

PROS: no use of third party libraries and is easy to read and write from the properties file.
CONS: With this way of reading and writing to the files, all your comments will show at the starting of the file and then shows up the properties. So the comments (if any specific to the property will be gone and all comments mess up at the top of the file)
When to use: I recommend this way to use when your properties file doesn't have any comments. i.e. your properties file just contains key value pairs.

To know more about Java.Util.Properties: Java.Util.Properties

In my next post, I will discuss the efficient way to edit the properties file without affecting the comments and order of the properties.
È