Saturday, 21 April 2012

Java Data Objects (JDO)

Reading: http://java.sun.com/developer/technicalArticles/J2SE/jdo/
The JDO Programming Model
The Development Life Cycle: Using JDO in Your Applications


JDO as part of Google App Engine (GAE):
https://developers.google.com/appengine/docs/java/datastore/jdo/overview

Lifecycle of GAE datastore writes:
https://developers.google.com/appengine/articles/life_of_write



Spring Web MVC step by step tutorial


Steps to setup a Spring Web MVC project on eclipse Helios:

1. Create a new Dynamic Web Project name "SpringWebMVC".

2. Create a JSP, 'SpringWebMVC/WebContent/index.jsp' with contents:
<html>
  <head><title>Example :: Spring Application</title></head>
  <body>
    <h1>Example - Spring Application</h1>
    <p>This is my test.</p>
  </body>
</html>

3. Create 'SpringWebMVC/WebContent/WEB-INF/web.xml', with contents:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

  <welcome-file-list>
    <welcome-file>
      index.jsp
    </welcome-file>
  </welcome-file-list>

</web-app>

4. Run the web app on any server and access it through URL: "http://localhost:8080/SpringWebMVC/"

5. Modify 'web.xml' to add the spring's servlet  DispatcherServlet (also known as a 'Front Controller').
 It is going to control where all our requests are routed.

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

We have decided to let any URL with an '.htm' extension be routed to the 'springapp' servlet (the DispatcherServlet).

6. Create a file called 'springapp-servlet.xml' in the 'SpringWebMVC/WebContent/WEB-INF' directory. This file contains the bean definitions (plain old Java objects) used by the DispatcherServlet. It is the WebApplicationContext where all web-related components go. The name of this file is determined by the value of the <servlet-name/> element from the 'web.xml', with '-servlet' appended to it (hence 'springapp-servlet.xml'). This is the standard naming convention used with Spring's Web MVC framework.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <!-- the application context definition for the springapp DispatcherServlet -->

  <bean name="/hello.htm" class="springapp.web.HelloController"/>

</beans>

Added a bean entry named '/hello.htm' and specify the class as springapp.web.HelloController. This defines the controller that our application will be using to service a request with the corresponding URL mapping of '/hello.htm'. The Spring Web MVC framework uses an implementation class of the interface called HandlerMapping to define the mapping between a request URL and the object that is going to handle that request (the handler). Unlike the DispatcherServlet, the HelloController is responsible for handling a request for a particular page of the website and is also known as a 'Page Controller' (Fowler). The default HandlerMapping that the DispatcherServlet uses is the BeanNameUrlHandlerMapping; this class will use the bean name to map to the URL in the request so that the DispatcherServlet knows which controller must be invoked for handling different URLs.

7. Copy Spring libraries to the 'WEB-INF/lib' folder:
commons-logging.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
org.springframework.web.servlet-3.1.1.RELEASE.jar

8. Create the controller, 'src/springapp.web.HelloController'.

public class HelloController implements Controller {

    protected final Log logger = LogFactory.getLog(getClass());

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        logger.info("Returning hello view");

        return new ModelAndView("hello.jsp");
    }

}

 In Spring Web MVC, the Controller handles the request and returns a ModelAndView - in this case, one named 'hello.jsp'/
 The model that this class returns is actually resolved via a ViewResolver. Since we have not explicitly defined a ViewResolver, we are going to be given a default one by Spring that simply forwards to a URL matching the name of the view specified.

Reading:
About using a view resolver and annotation based configuration.
http://blogs.sourceallies.com/2010/02/taking-advantage-of-spring-mvcs-default-behavior/


Monday, 16 April 2012

Change grub boot order

Edit the file: "/boot/grub/menu.lst" from linux and set the "default 0" to the appropriate number you want to startup by default.

If you can't find the above file, you need to edit the file "/boot/grub/grub.cfg".

Sunday, 15 April 2012

Using Strace in linux

The following article explains the usage of strace command for troubleshooting in linux:
http://www.hokstad.com/5-simple-ways-to-troubleshoot-using-strace.html

strace is a tool for tracing system calls and signals. It intercepts and records the system calls made by a running process. strace can print a record of each system call, its arguments, and its return value. You can use strace on programs for which you do not have the source since using strace does not require recompilation. It is often useful in instances where a program freezes or otherwise fails to work and offers few clues as to the problem.


Strace Output: Each line starts with a system call name, is followed by its arguments in parenthesis and then has the return value at the end of the line. Errors (which typically have a return value of -1) have the symbolic error name (such as ENOENT in the first line in the example above) as well as a more informative error string appended.



Spring container in java

The idea behind spring, inversion of control or dependency injection as explained by Martin Fowler
http://martinfowler.com/articles/injection.html

The spring reading:
http://static.springsource.org/spring/docs/1.2.x/reference/beans.html

Thursday, 12 April 2012

SCP and SSH without password

To setup the password-less logging from one box 'Source' to another box 'Dest'.
You need to generate the 'Source' user's public/private key pair, and then append the public key of this user to 'Dest' user's ".ssh/authorized_keys" file.
Important thing to note is that destination and source users can be different. However, the ".ssh" folder inside 'Dest' user's home directory needs to have unix permissions '700' for this to work (Because otherwise anyone can write their public key into this folder and gain access to the destination user's account).

The following article explains the setup of password less ssh or scp setup between two systems.
It provides the troubleshooting for common problems as well.

http://homepage.mac.com/kelleherk/iblog/C1901548470/E20061128145420/index.html

Monday, 9 April 2012

Find all files recursively in the current directory and process them one by one

Finding all files in the current directory, and execute a command on each file:


find ./ -mtime +1 -exec rm -vf {} \;


the command executed on each file is in italics in the above line, and '{}' is replaced by the file name during the command execution.

Check the memory used by a unix process


To see the memory used by the process, ps can be used with flags -AH
ps -AH v | grep 3408
where 3408 is the PID of process.

Check the column RSS (resident set size). It is the non-swapped physical memory that a task has used (in kiloBytes). (alias rssize) rsz).

Java Heap analysis using jdk tools

To take a heap dump of a java process using the jdk tools, use jmap:
jmap -dump:format=b,file=heap.bin <pid>
where pid is the process id of the java process.


After taking the heap dump, you can use the jhat (Java Heap Analyzer tool) provided by jdk to analyse te heap dump:
jhat -port 7777

Saturday, 7 April 2012

WeakReferences in Java/Android

How to access the android UI thread from other threads


Android offers several ways to access the UI thread from other threads. You may already be familiar with some of them but here is a comprehensive list:
When using a handler, you can pass a single object as part of the Message to the Handler using msg.obj field.

Source: http://developer.android.com/resources/articles/painless-threading.html

Andorid Service vs AsyncTask vs Handler


  • A service is an Android component that lives independently from any other components. Activities may come and go, but services can stick around, if you wish. They serve a number of roles, from managing state that multiple activities rely upon to serving as cron jobs to handling longer app widget updates.
  • AsyncTask is a class that arranges to do some work off the main application thread. From the implementer and user of the AsyncTask, how it performs that bit of magic is not generally important. In reality, it uses a thread pool and work queue. AsyncTask uses a Handler to help arrange for select bits of work to be done on the main application thread (e.g., notifying the user of progress updates).
  • Handler is a class that is tied tightly into the message queue and loop that forms the backbone of the main application thread. The primary purpose of a Handler in application code is to arrange for messages to be sent from background threads to the main application thread, mostly to arrange for updates to the UI, which cannot be done from background threads.

Universally unique identifier (UUID)


Background:
The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. In this context the word unique should be taken to mean "practically unique" rather than "guaranteed unique". Since the identifiers have a finite size it is possible for two differing items to share the same identifier. The identifier size and generation process need to be selected so as to make this sufficiently improbable in practice. Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.

The time based UUID generation algorithm supports very high allocation rates of up to 10 million per second per machine if necessary, so that they could even be used as transaction IDs.



Java Class: java.util.UUID
Methods you cans use to generate UUID are:

  • UUID.randomUUID();
  • UUID.nameUUIDFromBytes(bytesArray);
Reading: http://www.javapractices.com/topic/TopicAction.do?Id=56