Friday, 19 October 2012

My Log Start and End Templates for Eclipse

I would like to share my eclipse templates.. to show log start and end



<?xml version="1.0" encoding="UTF-8"?><templates><template autoinsert="true" context="java" deleted="false" description="Log End will be written" enabled="true" name="lnd">log.logDebug("${enclosing_method}(${enclosing_method_arguments}) :End");
</template><template autoinsert="true" context="java" deleted="false" description="Log Start will be written" enabled="true" name="lst">log.logDebug("${enclosing_method}(${enclosing_method_arguments}) :Start");
</template></templates>
Inside Eclipse as shown in below image:


Tuesday, 11 September 2012

Use System property inside log4j config preperties/xml


---------------------------------------------------------------
  <appender name="DAILY_FILE" class="org.apache.log4j.DailyRollingFileAppender">
  <param name="Threshold" value="debug" />
  <param name="File" value="${MY_SYS_VAR}/Logs/xyz.log"/>
  <param name="ImmediateFlush" value="true"/>
  <param name="Append" value="true"/>
  <param name="DatePattern" value="'.'yyyy-MM-dd"/>
  <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="PFS- [%t]-[%d][%-5p][%-25c][%t]: %m\n" />
      </layout>
  </appender>
  ----------------------------------------------------


---------------------------------------------------------------

  <appender name="DAILY_FILE" class="org.apache.log4j.DailyRollingFileAppender">
  <param name="Threshold" value="debug" />
  <param name="File" value="/opt/Logs/xyz.log"/>
  <param name="ImmediateFlush" value="true"/>
  <param name="Append" value="true"/>
  <param name="DatePattern" value="'.'yyyy-MM-dd"/>
  <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="PFS-[%d][%-5p][%-25c][%t]: %m\n" />
      </layout>
  </appender>


  ----------------------------------------------------

Tuesday, 21 August 2012

Java Linux Console print colours






Here's a Java snippet that prints color output to the console (in a VT100 emulating terminal, i.e., in linux only):



public class ColorTest {

   public static void main (String args[]) {
      for (int i = 30; i < 38; i++) {
System.out.println("\033[" + i + "mHello " + "\033[1;" + i + "mWorld!\033[m");
      }

   }
}




It works by "printing" special terminal control commands that change the color. There are other VT100 terminal control commands that let you move the cursor around, clear the screen, and other things.

Who needs Swing, when you can make old-school ASCII interfaces, right? No fancy libraries required either.

Monday, 6 August 2012

Best ways to learn programming

Ref: http://lucas.cis.temple.edu/docs/labs/general/GoodProgramming.html

  1. DO NOT COPY FROM OTHER PEOPLE. When you do this you do not learn what you are supposed to learn by doing the assignment. You then cannot solve the same kinds of problems later. More information.
  2. Keep up with your assigned readings and/or homework assignments. In many classes the lab assignments illustrate or extend what you are supposed to be learning in the class. Once you understand the concepts in use the programs become much easier. If you do not understand what you are meant to be coding how can you do it correctly? Click More information.
  3. Use good programming style. This will help to make your code more readable. This greatly helps when you need to go back and debug your own program or need to change the code from one assignment to another. Poorly written code is hard to follow and leads to stupid errors in logic. It is also not easily portable from one program to another. More information.
  4. Put good comments into the code, including algorithm description and comments for input and output for each function. This is done for the same reason as the previous suggestion. It makes your code more readable when you understand what the code is meant to do and what is input and output from each function. More information.
  5. Break up your code into well-named and useable functions.By doing this you can easily port code from one assignment to another. You may not even need to change any code in many areas to move from one assignment to the next saving yourself a lot of time and effort better spent on the rest of the assignment. More information.
  6. Design what your program needs to do ( break it down into algorithms and steps ) before you start coding. You will save yourself a lot of time by having a clear path for programming development. It also makes defining functions easier if they are defined first. Start with the complete program's defined task, break it down into course steps. These are your big functions. Then break these down again into helper functions and continue until you have small, easy to code blocks. More Information.
  7. Use good descriptive variables in your functions. By doing this you make your code more easier to read and thus easier to debug. When naming the function's variables, give good names for what the variables do in the function, not the functionality of the variable in the complete program. This will make it more transportable. More Information.
  8. Make backups of your work often. As much as we try to make computers as stable as possible, they still are prone to errors. So, if you backup your programs and any data that you cannot easily re-build to a subdirectory or to another storage location before you start to work, and every so often even while you are working, when something goes wrong you at least have something to go back to. More Information.
  9. K.I.S.S. = Keep It Simple Stupid. This is an old programmer's adage. It reminds us not to do too much at one time. Break it down into steps and handle each problem in turn. If you try too much at once you cannot be sure which step failed. You then take more time going back and testing each thing than if you had proceeded more cautiously.

Friday, 3 August 2012

Which Java collection to use?

Ref: http://www.janeve.me/articles/which-java-collection-to-use


Introduction

Java collections are one of the most commonly used data-structures by all Java professionals. But are you using the right collection class that would best suits your need. Most programmers usually use Vectors, ArrayList, HashMap or the Hashtable. There are many other collection classes available with the JDK that you can use instead of re-inventing logic to suite your needs.
We will be trying to understand the different types of classes and when each Collection class could be used. We wouldn't be looking into the implementation details of any collection, for that please refer the latest Java Collection API docs.

Friday, 6 January 2012

Timeout on Console Input readlineTillTimeout(long timeOut)

Ref: http://www.javaspecialists.eu/archive/Issue153.html


Timeout on Console Input

The problem that was trying to solve was to have a simple console based application that would give users a certain time to answer the question. It would then timeout and retry a few times.
The reason this was a difficult problem to solve was that System.in blocks on the readLine() method. The thread state is RUNNABLE when you are blocking on IO, not WAITING or TIMED_WAITING. It therefore does not respond to interruptions. Here is some sample code that shows the thread state of the Thread:
import java.io.*;

public class ReadLineTest {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(
        new InputStreamReader(System.in)
    );
    in.readLine();
  }
}
  
The thread dump clearly shows the state (I have stripped out unnecessary lines from the stack trace):
"main" prio=10 tid=0x08059000 nid=0x2e8a runnable
   java.lang.Thread.State: RUNNABLE
  at java.io.BufferedReader.readLine(BufferedReader.java:362)
  at ReadLineTest.main(ReadLineTest.java:8)
  
Since blocking reads cannot be interrupted with Thread.interrupt(), we traditionally stop them by closing the underlying stream. In our Java Specialist Master Course, one of the working examples is how to write a non-blocking server using Java NIO. (Told you it was a comprehensive course :-)) However, since System.in is a traditional stream, we cannot use non-blocking techniques. Also, we cannot close it, since that would close it for all readers.
One little method in the BufferedStream will be able to help us. We can call BufferedStream.ready(), which will only return true if the readLine() method can be called without blocking. This implies that the stream not only contains data, but also a newline character.
The first problem is therefore solved. However, if we read the input in a thread, we still need to find a way to get the String input back to the calling thread. The ExecutorService in Java 5 will work well here. We can implement Callable and return the String that was read. Unfortunately we need to poll until something has been entered. Currently we sleep for 200 milliseconds between checks, but we could probably make that much shorter if we want instant response. Since we are sleeping, thus putting the thread in the TIMED_WAITING state, we can interrupt this task at any time. One last catch was that we do not want to accept an empty line as a valid input.
import java.io.*;
import java.util.concurrent.Callable;

public class ConsoleInputReadTask implements Callable<String> {
  public String call() throws IOException {
    BufferedReader br = new BufferedReader(
        new InputStreamReader(System.in));
    System.out.println("ConsoleInputReadTask run() called.");
    String input;
    do {
      System.out.println("Please type something: ");
      try {
        // wait until we have data to complete a readLine()
        while (!br.ready()) {
          Thread.sleep(200);
        }
        input = br.readLine();
      } catch (InterruptedException e) {
        System.out.println("ConsoleInputReadTask() cancelled");
        return null;
      }
    } while ("".equals(input));
    System.out.println("Thank You for providing input!");
    return input;
  }
}
  
The next task is to call the ConsoleInputReadTask and timeout after some time. We do that by calling get() on the Future that is returned by the submit() method on ExecutorService.
import java.util.concurrent.*;

public class ConsoleInput {
  private final int tries;
  private final int timeout;
  private final TimeUnit unit;

  public ConsoleInput(int tries, int timeout, TimeUnit unit) {
    this.tries = tries;
    this.timeout = timeout;
    this.unit = unit;
  }

  public String readLine() throws InterruptedException {
    ExecutorService ex = Executors.newSingleThreadExecutor();
    String input = null;
    try {
      // start working
      for (int i = 0; i < tries; i++) {
        System.out.println(String.valueOf(i + 1) + ". loop");
        Future<String> result = ex.submit(
            new ConsoleInputReadTask());
        try {
          input = result.get(timeout, unit);
          break;
        } catch (ExecutionException e) {
          e.getCause().printStackTrace();
        } catch (TimeoutException e) {
          System.out.println("Cancelling reading task");
          result.cancel(true);
          System.out.println("\nThread cancelled. input is null");
        }
      }
    } finally {
      ex.shutdownNow();
    }
    return input;
  }
}
  
We can put all this to the test with a little test class. It takes the number of tries and the timeout in seconds from the command line and instantiates that ConsoleInput class, reading from it and displaying the String:
import java.util.concurrent.TimeUnit;

public class ConsoleInputTest {
  public static void main(String[] args)
      throws InterruptedException {
    if (args.length != 2) {
      System.out.println(
          "Usage: java ConsoleInputTest <number of tries> " +
              "<timeout in seconds>");
      System.exit(0);
    }

    ConsoleInput con = new ConsoleInput(
        Integer.parseInt(args[0]),
        Integer.parseInt(args[1]),
        TimeUnit.SECONDS
    );

    String input = con.readLine();
    System.out.println("Done. Your input was: " + input);
  }
}
  
This seems to satisfy all the requirements that we were trying to fulfill. To be honest, when I first saw the problem, I did not think it could be done.
There is at least one way you could potentially get this program to fail. If you call the ConsoleInput.readLine()method from more than one thread, you run the very real risk of a data race between the ready() andreadLine() methods. You would then block on the BufferedReader.readLine() method, thus potentially never completing.