Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, October 22, 2013

Searching multiple words in multiple files in eclipse

There are times when we have to search for the occurrences of multiple words in multiple files. In eclipse you can perform this search using File Search with regex expressions.

  • Open Search > File dialog.
  • In the Containing text: field enter (?<!^\s*(//|\*).*)(jack|jim)
  • Select the Regular expression check box and hit the search button.
The above steps shall parse thru all the files selected in the File name patterns section and list all the files with either jack or jim or both.

To understand the expression above, you can refer to http://www.eclipse.org/tptp/home/downloads/installguide/gla_42/ref/rregexp.html

Tuesday, May 21, 2013

Temporary environment variables precedence in Windows

The user environment variables always have precedence over the system environment variables for the process run by the particular user.

In relation to the temporary folders, the TMP environment variable has a precedence over the TEMP environment variable (legacy reasons dating to DOS). So to sum up the temporary folders environment variable precedence (top to bottom) for the currently logged in user is:
  • User %TMP%  (Highest precedence)
  • System %TMP%
  • User %TEMP%
  • System %TEMP% (Lowest precedence)
You can verify the precedence using:
  • Command prompts echo %ENVIRONMENT VARIABLE%
  • Java's [System.getProperty("java.io.tmpdir")]
  • C# [Path.GetTempPath()]

Saturday, October 31, 2009

Java 5 EOSL

Java 5 has reached End Of Life. Most of the bigger organization in the service industry are still using Java 1.4 and are not willing to migrate as they anticipate migration issues and feel that its a risk and unjustifiable. Java 6 has been out for a long and its time to take advantage of the new features, especially the web services stack (JAX-WS). There are lot of performance improvements which might be one reason to migrate.

On a personal note migration is little to do with technical, but more often political.

http://java.sun.com/products/archive/eol.policy.html

Monday, February 23, 2009

Executing the code while JVM shuts down

A number of times we have encountered a situation where we want a particular piece of code to be executed when our application is exiting. More necessarily we need such a mechanism when we have developed a server and want the code to be executed for any System.exit(0) call or a CTRL + C key combination on the console. A shutdown hook is the way out for this problem. Writing it is very simple. All the code we need to be executed should be written in a Thread and its object should be registered with the Runtime of the JVM. The code is as below.
Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        System.out.println("Executing the code while closing down.");
    }
});
A detailed explanation of the above method is provided in the Javadocs for the Runtime class.

Tuesday, November 11, 2008

Checking network connection using Java

At times it is required to check whether the machine is still connected to network or not. One way to find it using JDK1.6 by using the code is as below.
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface nic = interfaces.nextElement();
    System.out.print("Interface Name : [" + nic.getDisplayName() + "]");
    System.out.println(", Is connected : [" + nic.isUp() + "]");
}
Additionally several new useful methods such as isLoopBack(), isPointToPoint() and many more have been added in JDK 1.6 release. Refer to the Javadocs for more information on NetworkInterface class in java.net package.

Tuesday, October 21, 2008

Best way to check for all alphabetic, alphanumeric or numeric strings

The best way of checking whether the string is a pure alphabetic, alphanumeric or numeric is to use the String class's matches method by using the regex pattern as a parameter.
  if ("!abc123".matches("[a-zA-Z]*")) {
      System.out.println("Pure alphabetic string");
  } else {
      System.out.println("Not pure alphabets");
  }

Sunday, September 7, 2008

Java Socket client issue on Linux

In the case that the socket client is on the windows and server on linux & the server goes down, the client on windows identified immediately and gives an exception. For a scenario vice versa i.e. socket client on linux and server on any other machine (currently tested on windows), the client waits for too long for a timeout. To deal this situation instead of opening a socket client like:
 Socket socket = new Socket(“10.1.25.186”, 8080);
You should use:
InetAddress inetAddr = InetAddress.getByName(“navnit.tempo.local”);  
SocketAddress socAddr = new InetSocketAddress(inetAddr, 8080);  
Socket socket = new Socket();  socket.connect(socAddr, 5000); // 5000 is the timeout in millis.

Precision subtraction of floats

The normal subtraction of the double values in java result in a very long answer e.g. System.out.println(0.123 - 0.100); will result in 0.022999999999999993 as opposed to the expected 0.023. The Math.round function won't work here as it Returns the closest long/int to the argument.This precision problem can be fixed using the BigDecimal class.
BigDecimal first = new BigDecimal(0.123);
BigDecimal second = new BigDecimal(0.100);
System.out.println(first.subtract(second, new MathContext(2)));
The above program rounds off the answer to a precision of 2. i.e. the result will be 0.023.

Socket connection via proxy

To make the hits to internet programmatically via a proxy, you need to launch the program with the following JVM arguments. The program ConnectionTest contains the code to connect to some server on the internet and if in order to do so it needs to go via a proxy then run it as follows.
 
>java -Dhttp.proxyHost=proxy2.temp.org -Dhttp.proxyPort=8888 pack.ConnectionTest

Running the above code without the JVM arguments, it won't connect.

Generating same hashcode for similiar objects

Always override hashCode method if you are overriding the equals method of a java class. A POJO containing the same values in the properties can generate different hashCodes by default. If you need a way to generate the same hashCodes for POJO’s with same properties, instead of writing your own logic like adding properties or any other method, consider using apache’s commons-lang class HashCodeBuilder. This is specially worth considering if the objects are being added to data structures that use hashing mechanism for storing objects e.g. HashSet, HashMap, etc.

@Override  
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}

Friday, July 4, 2008

Singleton In Different Way

public class Singleton {
    private Singleton() {
    }
    private static class SingletonHolder {
        private static final Singleton singleton = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.singleton;
    }
}
Whenever a class is first loaded by JVM it's static variable and static initialiser bloacks are executed. In the above example when the class Singleton is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables and initializer blocks, the initialization completes simply. The JVM will not load the static class definition SingletonHolder within Singleton class until you touch something in the SingletonHolder class. Hence the static variable is not initialized until the JVM determines that SingletonHolder must be loaded or executed. The static class SingletonHolder is only executed when the static method getInstance is invoked on the class Singleton.
The first time when this class will be loaded by the JVM the static variable singleton will be initialized by executing the (private) constructor for the outer class Singleton. As per the Java Language Specification (JLS) the class initialization phase is guaranteed to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization. As the initialization phase initializes the static variable singleton in synchronized manner, all subsequent concurrent invocations of the getInstance will return the same correctly initialized singleton without incurring any additional synchronization overhead.