Pages

Dynamically change the window size on virtual box

I was working on this project where the task was to add some code for the test automation of the product. The whole system was on linux, so I had to prepare all the system on ubuntu. I set up an ubuntu instance on the virtualbox-4.3.12. The problem was that the size of the screen was static where it had scroll bars and so it was uncool. I also use virtualbox in my work with redhat as guest os, but there, the screen size of guest machine dynamically changes as I resize the virtual-box window.
So I thought, there must be some way to do this in ubuntu as well. I researched and found an amazingly simple solution. In the window where the guest OS is running, there is an option Devices->Install guest additions CD image. Click on the link and install the image in the guest os. Now restart it. That should do the work.
However in my case, the virtual box started to crash and could not open. I tried different things but it didnot work. Finally, I copied the .vdi file of the image to another location, and deleted all the references to the instances in the virtual box. Then I created another instances pointing to the same vdi file, and it worked properly.
Do enjoy virtualizing.

Prime check Algorithm

#include <stdio.h>
#include <stdlib.h>
int isPrime(int num);
int main(int argc, char* argv[])
{
int arg = 5;
if(argc > 1)
{
arg = atoi(argv[1]);
}
printf("The argument is %d\n", arg);
if(isPrime(arg))
{
printf("The number %d is prime\n", arg);
}
else
{
printf("The number %d is not prime\n", arg);
}
}
int isPrime(int num)
{
int i=2;
int mod=0;
for ( ; i<=(int)(num/2); i++)
{
mod=num%i;
printf("The modulus is %d\n", mod);

if(mod==0)
{
printf("%d divisible by %d\n", num, i);
return 0;
}
}
return 1;
}

Multi-Processing in bash

Advanced programmers and script writers must have been familier with the concepts  of multi threading/multi processing. Many of the high level commands support them. However, scripting languages also support them. Recently, I have been dealing with one of such interesting problem in bash scripts.
Given is an example of a script that spawns a new child process in the background and the main process continues.

#!/bin/sh
print_info(){
PROCESS_MESSGAE=$1
LAST_SPAWNED_PID=$!
DATE_TIME=`date`
echo "Process Info : $PROCESS_MESSGAE, TIME=$DATE_TIME ,PID=$LAST_SPAWNED_PID"
}
(
i=0
while [ "$i" -lt 100 ]
do
echo $i
sleep 2
i=$((i+1))
done
) &
PID_LAST_SPAWNED=$!
print_info "While loop and process info check"
sleep 10
kill $PID_LAST_SPAWNED
The block of code that is written between single braces “()”, will run in the new process. Any command followed by an ampersant “&” will run on background, independent with the parent process. So the program is creating a background process which prints the values of $i in a while loop.
The main process grabs the process_id ie “PID” of the process, and then kills it after 10 seconds. So the background process could only print up to 5.

Configure Jetty to trust a self signed certificate

I was having a problem connecting jasig-cas server from my local installation.
The cas server was in https, with a self signed certificate. My local application is in http mode running on maven.
Now I dont have the admin previliges to add the certificate to the java’s cacerts file as trusted file. So my application was failing.
Steps.
1. Download the certificate from browser to local computer.
2. use the java keytool to create a truststore file.
“%JAVA_HOME%\bin\keytool” -import -alias tomcat -file “D:\certificates\nvscmlinq1-cas.crt” -keystore nvscmlinq1-cas.jks
NOTE: this will create the nvscmlinq1-cas.jks file which is the truststore file.
3. Run the maven with command line java arguments to specify the truststore file and password.
mvn jetty:run -Djavax.net.ssl.trustStore=”D:\certificates\nvscmlinq1-cas.jks” -Djavax.net.ssl.trustStorePassword=changeit

Text Replacement through bash script

Normally, in Code-Projects, we write generic codes with hard coaded Variables whose values are known at the deployment time. For example, we may write START_PORT, STOP_PORT in pom.xml and these ports may very as per the environments are being deployed on.
Linux based build system have Makefile, where you type something like
make init profile=dev && make run profile=dev
and as per the profile supplied, the internal values in the project has to adjust.
One way of doing it is by using the linux sed command. sed is a command for editing io-streams.
Example:
Create a file named file1.txt
Write some content. (My name is <Name>)
Now with a command prompt, type
cat file1.txt |sed s/""/Rajan/g |cat > file2.txt
First check the content of file2.txt.
Now let me explain you what the command is doing.
First the cat command in left extracts the content of file1.txt and gives it to sed command. The sed command is taking an input stream and replacing the pattern “” with “Rajan” text. Not the stream is again piped to cat command as an input which outputs to the file2.txt file.

Tunneling | a trick

Sometimes in some environment, some of the websites may be restricted. There are lots of softwares eg. mcafee, which acts as a proxy of your network in your company network and restricts some category sites to be browsed.
What you could do is, you could tunnel the request to some remote machine and browse the contents from there. This will work if the proxy filtering is not applied in that network where the remote machine is located.
Steps
1. Open your putty, type the server where you want to connect
2. Click the “Tuenneling” link in Putty, select “Dynamic” as the option
3. Enter a port number in the port sectioin, and add. eg : 8080
4. Hit enter, enter username and password in the terminal. Connect to the machine
5. In the browser, set the proxy as “localhost:8080″
6. Browse and enjoy.

My online Work on oDesk

Hello everyone out there reading my blog.
I am a computer programmer and a very ambitious one. Apart of working on my daily job I was trying to find a job online, not only because of money, but I want to expand my options. Working for someone else, doing everything they told to do, hoping that they would notice my hard work and grant me bonus or other benefits, haaaah. Not my thing. I tried for nearly six months on odesk and finally got one job.

Java: Comparator class for different ways of sorting custom objects' collection

Suppose you have a simple class called Book which has attributes title, author, and price. You may need to sort them according to each attribute and both in ascending and descending order. Now you may implement your own method, but the really simple and efficient way is to use the inbuilt Comparator Interface. This is the in-built generic interface in java which you can implement on any object. Just override its compare method and write the logic to return the -1, 0 and 1.

Example.

package odesk;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @author Rajan Prasad Upadhyay
 * works fine
 */
public class Book {
    private String title;
    private String author;
    private double price;

    public Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public double getPrice() {
        return price;
    }

    public String toString() {
        return title + ": " + author + ": " + price;
    }
    
    public boolean equals(Book book2){
        return author.equals(book2.getAuthor());
    }

    public static void main(String[] args) {
        List<Book> booksList = new ArrayList<Book>();
        booksList.add(new Book("Book1", "Rajan", 100));
        booksList.add(new Book("Book2", "Dummy2", 10));
        booksList.add(new Book("Book3", "Dummy", 17));
        booksList.add(new Book("Book4", "Rajan2", 90));
        System.out.println(booksList);
        
        Bookstore bs = new Bookstore(booksList);
        
        int order = 1;
        System.out.println( bs.getBooksSortedByPrice(order));
        
        System.out.println(bs.getBooksByAuthor("Rajan"));
    }
}

//<editor-fold defaultstate="collapsed" desc="comparators">
class PriceComparatorASC implements Comparator<Book> {

    @Override
    public int compare(Book t, Book t1) {
        if (t.getPrice() < t1.getPrice()) {
            return -1;
        } else if (t.getPrice() == t1.getPrice()) {
            return 0;
        } else {
            return 1;
        }
    }
}

class TitleComparatorASC implements Comparator<Book> {

    @Override
    public int compare(Book t, Book t1) {
        return t.getTitle().compareTo(t1.getTitle());
    }
}

class AuthorComparatorASC implements Comparator<Book> {

    @Override
    public int compare(Book t, Book t1) {
        return t.getAuthor().compareTo(t1.getAuthor());
    }
}

class PriceComparatorDESC implements Comparator<Book> {

    @Override
    public int compare(Book t1, Book t) {
        if (t.getPrice() < t1.getPrice()) {
            return -1;
        } else if (t.getPrice() == t1.getPrice()) {
            return 0;
        } else {
            return 1;
        }
    }
}

class TitleComparatorDESC implements Comparator<Book> {

    @Override
    public int compare(Book t1, Book t) {
        return t.getTitle().compareTo(t1.getTitle());
    }
}

class AuthorComparatorDESC implements Comparator<Book> {

    @Override
    public int compare(Book t1, Book t) {
        return t.getAuthor().compareTo(t1.getAuthor());
    }
}
//</editor-fold>

class Bookstore {

    List<Book> books = new ArrayList<Book>();

    public Bookstore(List<Book> books) {
        this.books = books;
    }

    public List<Book> getBooksSortedByPrice(int order) {
        // implement this method:
        // if order is 0, return the list of books sorted by price in ascending order,
        // if order is 1, return the list of books sorted by price in descending order
        //Collections.sort(books);
        if (order == 0) {
            Collections.sort(books, new PriceComparatorASC());
        } else if (order == 1) {
            Collections.sort(books, new PriceComparatorDESC());
        }
        return books;
    }

    public List<Book> getBooksSortedByTitle(int order) {
        // implement this method:
        // if order is 0, return the list of books sorted by title in ascending order,
        // if order is 1, return the list of books sorted by title in descending order
        if (order == 0) {
            Collections.sort(books, new TitleComparatorASC());
        } else if (order == 1) {
            Collections.sort(books, new TitleComparatorDESC());
        }
        return books;
    }

    public List<Book> getBooksByAuthor(String author) {
        // this method returns the list of books for a given author
        // do not make any changes to this method
        // change the Book class to make sure this method will work correctly
        List<Book> result = new ArrayList<Book>();
        Book helperBook = new Book("Dummy", author, 0.0);
        for (Book b : books) {
            if (b.equals(helperBook)) {
                result.add(b);
            }
        }
        return result;
    }
}


Maven command to create a webapp project

mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Write a pdf document from Spring controller.

In this article, I am going to demonstrate a simple way that we could support pdf download from server. We will generate a pdf document in the server using itextpdf api. And then we will write the pdf document in the output stream.

First add the dependency in the pom.xml
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.0.6</version>
  </dependency>

Next step, define a method where you write the functionality to write a pdf document.

@RequestMapping(value="/getpdf", method=RequestMethod.GET)
 public ResponseEntity<byte[]> getPdf(@RequestBody String json){
  String text = json;
  
        if (text == null || text.trim().length() == 0) {
             text = "You didn't enter any text.";
        }
        // step 1
        Document document = new Document();
        // step 2
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
   PdfWriter.getInstance(document, baos);
    // step 3
         document.open();
         // step 4
         document.add(new Paragraph(String.format(
             "You have submitted the following text using the %s method:",
             "getpdf")));
         document.add(new Paragraph(text));
         // step 5
         document.close();
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

       
        
     // retrieve contents of "C:/tmp/report.pdf"
     byte[] contents = baos.toByteArray();

     HttpHeaders headers = new HttpHeaders();
     headers.setContentType(MediaType.parseMediaType("application/pdf"));
     String filename = "output.pdf";
     headers.setContentDispositionFormData(filename, filename);
     headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
     ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
     return response;
 }

Reference:
http://stackoverflow.com/questions/16652760/return-generated-pdf-using-spring-mvc
http://itextpdf.com/examples/iia.php?id=173

Jetty | Define context path and port

Jetty default, runs on the port 8080 and no context path. Well, while developing projects, we often want to define context path and some other port to occupy. Here's how we could do it.

          <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <configuration>
                    <webApp>
                        <contextPath>/custom-path</contextPath>
                    </webApp>
                    <connectors>
                        <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
                            <port>PLACEHOLDER_CAS_HTTP_PORT</port>
                        </connector>
                    </connectors>
                    <stopPort>PLACEHOLDER_CAS_STOP_PORT</stopPort>
                    <stopKey>foo</stopKey>
                </configuration>
            </plugin>

Oracle query to break one row into multiple rows in sql

There are often the requirement of writing complex queries where one row needs to be divided into multiple rows in one sql statements. The "connect by" keywords could be used in such cases.

select level from dual connect by level < 10;

CAS client and Server configuration | Java

How to set up a CAS Server/Client Web application

The full form of CAS is Central Authentication Service. What it does is that, it provides authentication service to the client applications.

Well, I will describe my experience with the web applications. I started making simple web applications and build some functionality in it. Then I added security to the same application by creating login pages, storing passwords in the database and validating them against the user provided ones. Now, working in a IT-Company, where there are many applications. Normally the user who had taken three applications will have to have three different accounts in the web applications of the same company. Now, With the concept of cas, what you could do it build the authentication web application in one place, and point all you other web applications to use this service to authenticate.

Now lets move the place where we set up CAS 4.0 with Cas client version 3.2.1.
Jasig CAS is the most used version.

What do you need to do.

Install your cas Server

- Download CAS from this location
- Extract it, go inside the folder cas-server-webapp and build the project with maven.(mvn clean package)
- Copy it in the webapps folder of your Tomcat.
- (Optional) If you want to configure your tomcat to https, follow this link, otherwise configure your cas to work with non-secure version by
changing the p:cookieSecure="true" to p:cookieSecure="false" under /WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml of cas Server
- Start your tomcat, and browse to the location [http://localhost:8080/cas or https://localhost:8443/cas](if you have not changed the port of tomcat)

Install your cas Client

- Download the cas client dependencies from this location
- Run the pom.xml and add the jars created in the java web application
- Create a simple web application with web.xml, if you don't have your own application.
- Copy these libraries to the lib folder of WEB-INF
cas-client-core-3.1.1.jar (from cas-client 3.1.1)
commons-logging-1.1.jar (from cas-client 3.1.1)
xercesImpl.jar (from Apache Xerces release 2.9.1)
xml-apis.jar (from Apache Xerces release 2.9.1)
xmlsec-1.3.0.jar (from cas-client 3.1.1)
- Add the following filters in your web.xml. Change the locations

<filter>
  <filter-name>CAS Authentication Filter</filter-name>
  <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
  <init-param>
   <param-name>casServerLoginUrl</param-name>
   <param-value>http://localhost:8080/cas/login</param-value>
  </init-param>
  <init-param>
   <param-name>serverName</param-name>
   <param-value>http://localhost:8080</param-value>
  </init-param>
  <init-param>
   <param-name>renew</param-name>
   <param-value>false</param-value>
  </init-param>
  <init-param>
   <param-name>gateway</param-name>
   <param-value>false</param-value>
  </init-param>
 </filter>
 <filter>
  <filter-name>CAS Validation Filter</filter-name>
  <filter-class>org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>
  <init-param>
   <param-name>casServerUrlPrefix</param-name>
   <param-value>http://localhost:8080/cas/</param-value>
  </init-param>
  <init-param>
   <param-name>serverName</param-name>
   <param-value>http://localhost:8080</param-value>
  </init-param>
  <init-param>
   <param-name>proxyCallbackUrl</param-name>
   <param-value>http://localhost:8080/webappcas2/proxyCallback</param-value>
  </init-param>
  <init-param>
   <param-name>proxyReceptorUrl</param-name>
   <param-value>/webappcas2/proxyCallback</param-value>
  </init-param>
 </filter>
 <filter>
  <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
  <filter-class>org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class>
 </filter>
 <filter>
  <filter-name>CAS Assertion Thread Local Filter</filter-name>
  <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>
 </filter>
 <!-- ************************* -->
<!-- Sign out not yet implemented -->
<!-- 
 <filter-mapping>
  <filter-name>CAS Single Sign Out Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
-->
 <filter-mapping>
  <filter-name>CAS Authentication Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>CAS Validation Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
  
 <filter-mapping>
  <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>CAS Assertion Thread Local Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>CAS Validation Filter</filter-name>
  <url-pattern>/proxyCallback</url-pattern> 
 </filter-mapping>

- My web.xml look like this
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>CasClientSimple</display-name>
<filter>
<filter-name>CAS Authentication Filter</filter-name>
<filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
<init-param>
<param-name>casServerLoginUrl</param-name>
<param-value>https://localhost:1443/cas/login</param-value>
</init-param>
<init-param>
<param-name>serverName</param-name>
<param-value>https://localhost:2443</param-value>
</init-param>
<init-param>
<param-name>renew</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>gateway</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter>
<filter-name>CAS Validation Filter</filter-name>
<filter-class>org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>
<init-param>
<param-name>casServerUrlPrefix</param-name>
<param-value>https://localhost:1443/cas/</param-value>
</init-param>
<init-param>
<param-name>serverName</param-name>
<param-value>https://localhost:2443</param-value>
</init-param>
<init-param>
<param-name>proxyCallbackUrl</param-name>
<param-value>https://localhost:1443/cas/proxyCallback</param-value>
</init-param>
<init-param>
<param-name>proxyReceptorUrl</param-name>
<param-value>/cas/proxyCallback</param-value>
</init-param>
</filter>
<filter>
<filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
<filter-class>org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class>
</filter>
<filter>
<filter-name>CAS Assertion Thread Local Filter</filter-name>
<filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>
</filter>
<!-- ************************* -->
<!-- Sign out not yet implemented -->
<!-- <filter-mapping> <filter-name>CAS Single Sign Out Filter</filter-name>
<url-pattern>/*</url-pattern> </filter-mapping> -->
<filter-mapping>
<filter-name>CAS Authentication Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CAS Validation Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CAS Assertion Thread Local Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CAS Validation Filter</filter-name>
<url-pattern>/proxyCallback</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

Edit your deployerConfigContext.xml, registeredservices list  of CAS-server
<bean class="org.jasig.cas.services.RegexRegisteredService"
              p:id="0" p:name="HTTP and IMAP"
  p:description="Allows HTTP(S) and IMAP(S) protocols"
              p:serviceId="^(https?|imaps?)://.*"
  p:evaluationOrder="10000001"
  p:enabled="true"
  p:allowedToProxy="true"
  p:ssoEnabled="true"
/>

- Now try browsing your web application. You will be directed to the cas url.
- If you are redirected to wrong url, try reconfiguring the corresponding url in your client, restart the tomcat and try again.

 Some common errors you could run into

- Authentication validatin exception
- You have not configured the Registered services list in deployerconfigcontext.xml of the cas server.
- SSL validation exception
- you probably have not registered the certificate.cer in your jre's cacerts file.




References:
- http://www.javaroots.com/2013/05/configure-cas-server-and-client-in-java.html
- http://jasig.github.io/cas/4.0.0/installation/Service-Management.html

SSL tomcat

The problem I was facing was of CAS implementation. I had to test the implementation in my local environment. The CAS implementation is such that it will require HTTPS protocol to work properly. So I have to configure my tomcat for SSL.

How Certificate works

  • First the server needs a private key which it keeps itself
  • Then it generates the certificate(which also contains the public key, i think)
  • on first page request, server sends certificate(user has to accept and trust it if it is not signed by trusted associations)
  • Then a SSL handshake is made (server has private key and the user has the public key, each can decrypt others message)
  • REF: http://security.stackexchange.com/questions/20803/how-does-ssl-tls-work

The steps you should follow to configure a Security certificate to your tomcat are as follows.
  • Create a self signed certificate(keystore, eg common.jks)
  • Create a certificate file from the keystore(eg. common.cer).
  • Add the certificate to the trust store of java.
I was using same instance of jdk for CAS-Server and Client application so I did not have to create two certificates and add them to the trust stores of two JDK's. I used single certificate for both the application.

1. To create a new keystore from scratch, containing a single self-signed Certificate, execute the following from a terminal command line:
   
"%JAVA_HOME%\bin\keytool" -genkey -alias tomcat -keyalg RSA -keystore D:\Tomcats\common.jks

   
Note: creates file named abc.jks
/*
2. To create a CSR as follows
   
"%JAVA_HOME%\bin\keytool" -keystore "D:\Tomcats\common.jks" -certreq -alias tomcat -keyalg rsa -file "D:\Tomcats\common.csr"
*/

3. OR (export the generated certificate to a file)
 
"%JAVA_HOME%\bin\keytool" -export -alias tomcat -storepass changeit -file "D:\Tomcats\common.cer" -keystore "D:\Tomcats\common.jks"
   
4. To create the trust store file cacerts.jks and add the certificate to the truststore
   
"%JAVA_HOME%\bin\keytool" -import -v -trustcacerts -alias tomcat -file "D:\Tomcats\common.cer" -keystore "D:\Tomcats\cacerts.jks" -keypass changeit
   
    - to add the certificate to the trust of java
   
"%JAVA_HOME%\bin\keytool" -import -alias tomcat  -file "D:\Tomcats\common.cer" -keystore  "%JAVA_HOME%\jre\lib\security\cacerts"
5. Delete an already present certificate
   
keytool -delete -alias tomcat -keystore "D:\Tomcats\common.jks" -storepass changeit

After the certificate stuff, you have to configure the <tomcat-home>/conf/server.xml to use the certificate just generated. Its optional to keep or comment out the http port but its better to comment it out because allowing both https port and http port would slow down your application and consume more resources.

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="1005" shutdown="SHUTDOWN">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html , commented by rajan-->
  <!--<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />-->
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
   <!-- <Connector port="1111" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="1443" />
    -->
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->
 <!--<Connector port="1443" maxThreads="150" scheme="https" 
  secure="true" SSLEnabled="true" keystoreFile="conf/ssoServer.jks" 
  keystorePass="changeit" clientAuth="false" keyAlias="tomcat" 
  sslProtocol="TLS"/>
 -->
 
 <Connector port="1443" maxThreads="150" scheme="https" 
    secure="true" SSLEnabled="true" keystoreFile="D:/Tomcat/common.jks" 
    keystorePass="changeit" clientAuth="false" keyAlias="tomcat" sslProtocol="TLS"/>
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="1009" protocol="AJP/1.3" redirectPort="1443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

How to print long text in oracle

Sometimes it is necessary to print and have a look at the strings when we are doing dynamic works on the programming and querying world. In oracle/plsql, unluckily the Dbms_output.put_line(), function does not support more then 255 characters.

Well, we can create an additional procedure just for the purpose of printing the long text for such purpose.
CREATE OR REPLACE PROCEDURE SP_PRINT(longText VARCHAR2)
AS
  querylength        INT:= 0;
  ind                 INT := 1;
  leng                INT := 200;
BEGIN
  querylength := Length(longText);
   WHILE (ind <= querylength)
   LOOP
       Dbms_Output.Put_Line(SubStr(longText, ind, leng));
       ind := ind + leng;
   END LOOP;

END;

How to load a configuration file in java from resources directory | java | maven

While writing a software, its quiet often phenomenon that we want to put some of our configurations in easily editable configuration files rather then hard-coding everything in the application itself. It reduces the overhead of compiling the code with every little changes. Often in the production environment, its not even feasible to change compile it.
Maven projects have a definite directory structure where the class files are in one directory and the resources relating to the class files are in another. While loading the properties object with a *.properties file, the input stream expects the file to be in the same directory. Naturally this leads to an error, if our properties file is in the resources/ directory.
Well, here's the code for how you do it.
location.properties
## location.properties

INDEX_DIR=url_index
TEST=text_parameter

Configuration.java
package com.gazecode.config;

import java.io.InputStream;
import java.util.Properties;

public class Configuration {
 private Properties properties = new Properties();

 public Configuration() {
  try {
   
//   System.out.println("Working Directory = " +
//                System.getProperty("user.dir"));
   properties.load(Configuration.class.getResourceAsStream("/location.properties"));
   
  } catch (Exception e) {
   System.out.println("Error while loading");
   e.printStackTrace();
  }
 }

 public String getProperty(String key) {
  return properties.getProperty(key);
 }

 public void setProperty(String key, String value) {
  properties.setProperty(key, value);
 }
 
 public static void main(String[] args) {
  System.out.println("Starting the process");
  Configuration config = new Configuration();
  System.out.println(config.getProperty("INDEX_DIR"));
  System.out.println(config.getProperty("TEST"));
 }
}

Different types of objects | ORACLE

There are different types of objects in oracle database. Normally what happens is that you create a schema and then compile your object scripts which will create the objects like tables, procesures, packages, links, synonyms, views etc.
When there is change in the codebase, you could just simply compile the scripts. This could miss something time and again and you will have problem in the production. What I prefer is to delete all the objects, ie clean the schema and then compile it and do the processing.

Here is a simple script/query in oracle which will generate queries to delete different objects in oracle.

select drop_objects from (
 SELECT 
  CASE object_type WHEN 'TABLE' THEN 'DROP table '||object_name||' CASCADE CONSTRAINTS;'
  WHEN 'VIEW' THEN 'DROP VIEW '||object_name||';'
  WHEN 'SEQUENCE' THEN 'DROP SEQUENCE '||object_name||';' 
  WHEN 'SYNONYM' THEN 'DROP SYNONYM '||object_name||';'
  WHEN 'FUNCTION' THEN 'DROP FUNCTION '||object_name||';'
  WHEN 'PROCEDURE' THEN 'DROP PROCEDURE '||object_name||';'
  WHEN 'PACKAGE' THEN 'DROP PACKAGE '||object_name||';'
  WHEN 'PACKAGE BODY' THEN 'DROP PACKAGE BODY '||object_name||';'
  WHEN 'TYPE' THEN 'DROP TYPE '||object_name||';'
  WHEN 'TYPE BODY' THEN 'DROP TYPE BODY '||object_name||';'
  WHEN 'MATERIALIZED VIEW' THEN 'DROP MATERIALIZED VIEW '||object_name||';' 
  END drop_objects
 FROM USER_objects
) 
where 1=1
 and drop_objects is not null
;

Screen, do your work in the background | linux

For computer programmers, working remotely with Putty through ssh connections is pretty common. Normally, what we do is that we connect to putty to a remote linux (or windows(cygwin)) server, hit some commands to do some instantaneous work. But the problem may arise when we hit a long running command. For example, you connect to oracle user and start using the sqlplus in oracle. You have a long running engine to run in oracle. Suppose it takes two hours, and after one hour of running of the procedure, the network connection is our for a few minutes. What happens is that you session will be destroyed and the process will be in undetermined state.

Now the solution.

What you could have done is that you could have run your process in the background, independent of the active ssh session. You could do that with VNC or other technologies but I am going to talk about screen here.

You should have screen installed on your server. There are different commands to install screen on different versions of linux.
What screen does is generate a background session where your actual work is done, and it is independent of the ssh sessions.
The concept of screen is to create a session, attach to a screen session, and detach from a screen session.

1) Start a screen session
screen -S <new_session_name>
2) See the list of Active Screen sessions
screen -ls or -list
3) To reattach to a detached screen session
screen -r <existing_session_name>
4) To detach an attached screen session
for another remote user
screen -d <session_name
detach from ones screen and get out of screen
CTRL + a + d
5) To attach a screen session that someone else is attached.
screen -dr <session_name>


6) How do i know if i am in a screen session
echo $STY 


If the above commands outputs any value, then you are in a screen session. If the output is empty, you are not in a screen session.


Or if you simply press the backspace button for a long time the screen starts flickering in white color, if you are in a screen session


7) How do I kill a screen session

screen -X -S [session # you want to kill] quit

Thats it.

How to Disable images in Google Chrome Browser

Disabling the images, not only loads the images faster, it also saves your bandwidth. So it is very useful especially when you are in a limited data plan. In most of the browsers, it is straight forward but for chrome it is little bit tricky to find the image settings location itself.

Here's what I did to disable images in my browser.


  • Click on and go to the settings.
  • Click the link which says "show advanced settings"
  • Under the Privacy title, click on the area which says "Content Settings..."
  • Now you could actually see the image settings location. Click on "Do not show images" radio button to disable the images on your browser.

Excel | How to create a drop down list on a cell

Every time I try to do this, I got stuck for a few minutes trying to remember from where to do it. For example i want to create a list of tasks and their corresponding statuses like (Not started, In progress, Completed, Accepted) etc. So this is how it is done.

One line solution

  • Go to the data validation section. Choose type = List and then provide a list of values you want to appear in the drop down separated by comma.
Well, for me one line solution will do. So I am skipping the multiple lines solution. May be you could figure it out yourself.

An application to check the validity of email address

I was stuck with a problem to verify whether an email address has the proper format of an email address or not. I came up with an application which you could just save in your computer , open in a browser and test the string whether it is a valid email address or not.

Here is the application itself.


Validation Check






Enter an email addresses.
Emails:






The code that made it possible is this one.
<!DOCTYPE html>
<html>
<head>
 <title>Validation Check</title>

 <script type="text/javascript"  >  
  function validateRandom() { 
   //var value = $('#emails').val();;
   var value = document.getElementById("emails").value;
   //alert(value);
   //var re = new RegExp("pattern");
   var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
   
   if( re.test(value) ){
    alert('The text is a valid email address, in terms of its pattern');
   }else{
    alert('The pattern of the text do not match as a valid email address.');
   }
   return false;
  } 
 </script>

</head>
<body>

Enter an email addresses.
<form method = "post" id="email_form" >
 Emails:<br/>
 <input name="emails" id="emails" value = 'rajan'/><br/>
 <button type="submit" name="email_form_submit" onclick="return validateRandom()">Submit</button>
</form>

</body>
</html>

Browser based Test Automation Tool

Today I am going to write about one of my own part time development, I have been working on for a few weeks. I have been working in this project in our company where the task was to automate the browser based functionality testing with the help of a Web-Driver API(selenium). We developed a framework for that particular application. I have created a simple application with the same knowledge in my free time, and its still under progress. The Product's name is "Snapshots".
Well as the title suggests, its a tool to automate your browser based click, and regress test. The tool is a simple Desktop application, where you could

  • Create a test plan(open a url, click, type, snapshot etc)
  • Save the test plan for later use
  • Load the saved test plan
  • See the results.



If you are interested to use the software, here is a link.

Git tagging and recovering tag

There are two kinds of tagging in git.
1. Annotated/signed tag
2. LightWeight tag

In lightweight tag, it is just a pointer to a commit, and no extra information. This one is used for temporary purpose.
Annotaged tag, creates a unmodifiable branch of the state of the repo.

To see the list of tags
git tag

To create light Weight tag

git tag <tag_name>
eg
git tag version_1.0

To check which commit the following tag points to

git rev-parse version_1.0

Reset the current branch to the specific tag

git reset --hard <tagname>

Byte Stream and Character Stream | Java

Recently a need arises, which made me notice the difference between the byte stream and character stream in java. As you recall, in java, byte is a primitive data type whose size is 8-bits, where character is a datatype which holds uni-code character(ie 16 bits). So, the byte Stream could only read/write ASCII characters(0-255). That means, It can only work with english letters and not other languages. Character stream operates on unicode character and so can deal with other language character as well. It is only supported prior to java 1.1.

Byte Stream has two classes

  • Input Stream Class
  • Output Stream Class
Character Stream has also two classes

  • Reader Classes
  • Writer Classes

15 most challenging programming assignments | Java

The best way to learn is to do.

Its fun to learn a programming language and concepts by solving challenges. I have been teaching programming to some of the students, and I collected these assignments for them. These should help others too.

Here goes the questions.

1. Write a program to check if a number is even or odd. The program should ask for an integer input, and then check if the input is even or odd
and print the appropriate message.(Hint: divided by 2 if the remainder is 0 then its even)

2. Write a program to find if a number is prime in java.(Division up to the square root is enough)

3. Find if a number is power of 2 in java. (Hint: one possible solution is using bit shift operator)

4. Write a program to sort an integer array without using the inbuilt methods provided by java.

5. Write a program in java to check if a number is an armstrong number.
(Hint: An armstrong number is a number whose sum of the cube of its digits is equal to the number.
eg 153 = 1*1*1 + 5*5*5+3*3*3)

6. Write a program to reverse any string in java.(you could use iterative method or recursive method. Try implementing both)

7. Write a program in Java to print Fibonacci series up to given number? Try both iterative and recursive version.

8. Write a program in java to calculate factorial of an integer number.(Iterative, Recursive)

9. Write a program in java that will ask for an integer input and then print a pattern.
(for eg. if the input is 5)
*
**
***
****
*****
****
***
**
*
10. Write a program that displays the temperatures from 0 degrees Celsius to 100 degrees Celsius and its Fahrenheit equivalent. Note that the conversion from Celsius to Fahrenheit uses the following formula: F = C * 9/5 + 32;

11. Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7.

12. Write a number guessing game. The program will ask for an input(1 to 5). Then it should generate a random number and check if its matches with the users input. The program should do this ten times for a user, and then finally prints the score of the user.

13. In the above program, add a method to save the final score in a file if it is the highest one. The next time another user plays the game, the program should read the previous score from the file. if the current score is greater than the previous score, the program should print "You are the new winner", and then save the new highest score in the file before exiting. If the file is not present, the program should create a new one.

14. Write a program that will prompt "Enter a command".
- If you enter "pwd", it should print the current directory's location.
- if you enter "ls", it should print the name of all the files and directory's in the current directory.
- if you enter "exit", the program should exit.
- if you enter "help", it should print a help text about the commands it support and what they do.

15. Write a program that will prompt "Enter a command".
- if you enter "ls", it should print the name of all the files and directory's in the current directory.
- if you enter "ls | grep <pattern>", the program should print all the files and directories that match the <pattern>
- if you enter "exit" the program should exit.

Reading Input from Console | Java

In java, for reading the input from console, there are two options.

  1. Scanner
  2. BufferedReader
There are however some basic differences in the use of them.

Scanners treat the given input as tokens(can tokenize the input using regex). It provides methods like
nextInt()
and
next()
and so it support parsing capabilities. A bufferedReader however is not capable of this and can only read the characters from an inputStream and store as string to the buffer.

Scanners are a little bit slower then bufferedReader.

BufferedReaders are synchronized but Scanners are not. If the scanners are to be used in multiple threads, synchronization should be done manually.

Scanner has a little buffer(1kB) compared to BufferedReader(8kB).

A BufferedReader could be passed to the scanner as the source of characters to parse.

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a line");
        
        //String next = scanner.next();
        String text;
        
        while(( text = scanner.next())!= null){//
            System.out.println(text);
        }
    }

How to insert code in the article | Blogger | Formatting

While writing articles about programming, you have to write codes frequently in the articles. The problem is that you could not write code simply using the font and formatting of the text that the rest of your blog is using. Otherwise it won't look cool. But its kind of tricky to format the codes in your blogger article compared to the wiki or something else.
Well here's what I do for my formatting. Its not great, but I like the simplicity and separation both.
Suppose you have to write this article.

Hello World, Below is my code
Integer i = 1;

First of all, open your blogger and in the place to write the article, Write all the non-code article. Now blogger has two modes(Compose, Html). Go to the compose mode and Just in the place where you want to write your code, write this line
<code>code</code>

Now come back to the Compose mode. You can see the text "code" is actually in the format of a code. You could now copy your actual code, and then select the text "code" in the article editor and then paste it. You could also add custom CSS to make it different, like add border, background etc.

There are also custom javascripts and css syntax Highlighter out there in the internet. But I personally don't like them because they are a little bit big work in the beginning and they also kind of degrade the response time and add the volume of data to be transferred on each page load.

Simplicity is Beauty

Quick Guide to Java logging | log4j


Logging is a very important feature of any software. You could see the problem in your software through logs, trace the error, fix them etc. It is not only helpful in the development phase but in the Production as well.
If the logging module is not properly planned, in an enterprise software, it could cause all sorts of disadvantages.

Log4j is one of the most used logging api for java.

The various components of Log4j are
1. Loggers
These are hierarchical. For example com.abc and com.abc.def will have different hierarchy of log when you pass their class names while instantiating the logger. In the configuration file, you could configure particular module to one level of logging while the Root to the other, with the hierarchy.

static Logger log = LogManager.getLogger(LogTest.class.getName());

2. Appenders
Console appenders, File appenders, database appenders and more. Appenders define where the output will be. Appenders needs to be registered in a Logger. Then any log message in the logger is forwarded to all the appenders.

3. Layouts
This is responsible for formatting the log messages.
Pattern layout, html layout etc. You can have your own formator or you could simply use Pattern layout and append timestamp, etc in the front of the log message.

4. Priorities
(DEBUG < INFO < WARN < ERROR < FATAL)

5. Configuration
(log4j 2+ will find log4j.xml in the classpath). You could configure it through the code, but its a good idea to configure it through xml's or jsons. It could also auto renew the configuration when the configuration file is changed, without having to recompile or restart the application.

An Example of the log4j.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorinterval="30">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File1" fileName="output.log">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    
    <Loggers>
        <logger name="tutorials.LogTest" level="TRACE" additivity="false" >
            <AppenderRef ref="Console"/>
        </logger>
        <Root level="debug">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File1"/>
        </Root>
    </Loggers>
</Configuration>

The Logger is configure to refresh its settings every 30 seconds. There are two appenders, console and File.
The root logger is set to level debug, and both the appenders are registered to it. However for the class tutorials.LogTest, its level is Trace and so its TRACE messages will also be logged. The additivity=false code will prevent any duplicate logging(when the appenders are registered to it as well).

The Example of using the Logger
package tutorials;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author Rajan Prasad Upadhyay
 */
public class LogTest {

    static Logger log = LogManager.getLogger(LogTest.class.getName());

    public static void main(String[] args) {
        log.trace("Trace Message!");
        log.debug("Debug Message!");
        log.info("Info Message!");
        log.warn("Warn Message!");
        log.error("Error Message!");
        log.fatal("Fatal Message!");
    }
}

How to create a separate folder for resources | Netbeans

Well, there are different IDE's out there in the internet and all of them have different features. They provide some unique awesome features whereas even the best of them could be missing some basic stuffs.

Lets get to the point. When you create a Java Application Project in Netbeans, it creates the SourcePackages folder where you are supposed to create your packages and java classes. Now what if you require other stuffs like images, bitmaps, configuration files, xml's etc. you could create a package and put these stuffs there, but I personally don't like it. You could also put your resources in a different part of the disk than your project folder and reference it, but it will only work until the program is in your computer and it won't be packaged in the jar file. Now I researched on this problem and found a solution. It still may not be the best solution but I like it better than I have found yet.

I will point out the steps.

First create a project

Creating a project is easy and so I am not going to bother with the details. The folder structure that the netbeans create is like this.
I have deleted the default package, and created another one called tutorials, as you could see in the above picture.

Now add a Class

Click on the package tutorial, and add a class called TreeTest. Add the below code.

package tutorials;

/**
 *
 * @author Rajan Prasad Upadhyay
 */
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Rajan Prasad Upadhyay
 */
public class TreeTest {

    String name = "name";

    public static void main(String[] args) {
        javax.swing.JFrame topFrame = new JFrame();
        javax.swing.JPanel topPanel = new JPanel();
        javax.swing.JScrollPane leftScrollPane = new JScrollPane();
        javax.swing.JTree leftTree = new JTree();
        
        //for the cell renderer
        leftTree.setCellRenderer(new CustomCellRenderer());

        topFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        //layouts
        topFrame.setLayout(new BorderLayout());
        topPanel.setLayout(new BorderLayout());

        // addition of components
//        topPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE,Integer.MAX_VALUE));
        topPanel.add(leftScrollPane);

        leftScrollPane.getViewport().add(leftTree);

        addExperimentEvents(leftTree);

        topFrame.setSize(600, 500);
        topFrame.setContentPane(topPanel);
        topFrame.setVisible(true);
    }

    public static void addExperimentEvents(JTree tree) {
        MouseAdapter ma = new MouseAdapter() {
            private void myPopupEvent(MouseEvent e) {
                final int x = e.getX();
                final int y = e.getY();
                final JTree tree = (JTree) e.getSource();
                TreePath path = tree.getPathForLocation(x, y);
                if (path == null) {
                    return;
                }

                tree.setSelectionPath(path);

                Object obj = (Object) path.getLastPathComponent();

                String label = "Add:";// + obj.toString();
                JPopupMenu popup = new JPopupMenu("Menu");

                JMenu sectionsMenu = new JMenu("Sections");
                JMenuItem menuItem1 = new JMenuItem("Item1");
                sectionsMenu.add(menuItem1);
                JMenuItem menuItem2 = new JMenuItem("Item2");
                sectionsMenu.add(menuItem2);

                JMenuItem item = new JMenuItem(label);
                item.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        System.out.println("Editing the tree");
                        DefaultMutableTreeNode selNode = (DefaultMutableTreeNode) tree
                                .getLastSelectedPathComponent();
                        TreeNode root = (TreeNode) tree.getModel().getRoot();
                        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();//new DefaultTreeModel(root);

                        if (selNode != null) {
                            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node" + (selNode.getChildCount() + 1));
                            model.insertNodeInto(newNode, selNode, selNode.getChildCount());//
                            //model.insertNodeInto(newNode, (MutableTreeNode) root, root.getChildCount());
                            //tree.expandPath(new TreePath(model.getPathToRoot(newNode.getParent())));

                            TreeNode[] nodes = model.getPathToRoot(newNode);
                            TreePath path = new TreePath(nodes);

                            System.out.println(selNode.getChildCount() + ", " + path);
                            tree.scrollPathToVisible(path);
                            tree.setSelectionPath(path);
                            tree.startEditingAtPath(path);
                            //model.reload((TreeNode) model.getRoot());
                        } else {
                            System.out.println("selNode is null");
                        }
                    }
                });
                //addHoverAction(item);//
                //item.add(new JMenuItem("page"));

                popup.add(item);
                JMenuItem delete = new JMenuItem("Delete");
                delete.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        
                        TreePath path = tree.getPathForLocation(x, y);
                        final DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                        DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent();

                        int childNodeIndex = parentNode.getIndex(node);

                        System.out.println("Index of node deleted, wrt its parent is : " + childNodeIndex);

                        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

                        if (node.getParent() != null) {
                            model.removeNodeFromParent(node);
                        }
                    }
                });
                popup.add(delete);
                popup.add(new JMenuItem("Move: "));
                popup.add(sectionsMenu);
                popup.show(tree, x, y);
            }

            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    myPopupEvent(e);
                }
            }

            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    myPopupEvent(e);
                }
            }
        };
        tree.addMouseListener(ma);
    }

    // <editor-fold defaultstate="collapsed" desc="hoverAction">
    public static void addHoverAction(final JComponent com) {

        MouseAdapter adapter = new MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                System.out.println("mouse Entered: ");
                if (true) {
                    JPopupMenu pop = new JPopupMenu();
                    pop.add(new JMenuItem("Node"));

                    pop.show(com.getParent(), com.getWidth(), com.getHeight());
                }
            }
        };
        com.addMouseListener(adapter);
    }
    // </editor-fold>

    //static methods
    
        
    
}

class CustomCellRenderer extends DefaultTreeCellRenderer{
    Icon cup;
    Icon triangle;
    Icon page;
    
    public CustomCellRenderer(){
        cup = createImageIcon("/image/cup.GIF");
        triangle = createImageIcon("/image/middle.GIF");
        page = createImageIcon("/image/cup.GIF");
    }
    
    public Component getTreeCellRendererComponent(
                JTree tree,
                Object value,
                boolean sel,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {

            super.getTreeCellRendererComponent(
                    tree, value, sel,
                    expanded, leaf, row,
                    hasFocus);
            
            if(value.toString().equalsIgnoreCase("colors")){
                setIcon(cup);
            }else if(value.toString().equalsIgnoreCase("sports")){
                setIcon(triangle);
            }else if (value.toString().equalsIgnoreCase("food")){
                setIcon(page);
            }

            return this;
        }
    protected static  ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = TreeTest.class.getResource(path);
//        System.out.println(CustomCellRenderer.class.g);
        System.out.println("The image uri is : " + imgURL + " " + path);
        if (imgURL != null) {
            System.out.println("returning new image icon.");
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

}

Now you could see that in the method CustomCellRenderer(), the code is trying to load some image files. Until now It could not find it because we have not added it. Create a package called image and put two GIF files in it called cup.GIF and middle.GIF.

Create a resource folder in eclipse

Right click on the project and click Properties. On the section "Source Package Folders" click Add Folder and create a resources folder in the same location as the src folder is located. The resources will be seen along with src in the panel. Now click ok. Go to the projection location in the file explorer and create a physical folder named resources in the path. Also create a folder called image inside the resources folder and put two small GIF files inside it. You could just cut and paste the image file from your src directory to this directory. Now see the netbeans project explorer. The project must be looking like this.

Now run the project. The gif files you have added will appear in the icon of the tree nodes.
Thats all, thanks for watching my tutorial. Keep coding. Enjoy!!!