Tuesday, August 21, 2012

Problem using c:set of jstl

The problem was that i was not able to set the value of a variable defined in a scriptlet.
<c:set var="test" value="yogesh"/>

Root cause: The tag lib i was using was perhaps of an older version.

Older version:
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

Newer version:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/jsp/core" %>

Please do post more information if you have more knowledge about this problem.

Sunday, May 27, 2012

How to put time restriction on web service function call?

Add the following 2 imports

import com.sun.xml.ws.developer.JAXWSProperties;
import javax.xml.ws.BindingProvider;

Just add this before the function call where you call web service.


((BindingProvider)port).getRequestContext()
                          .put(JAXWSProperties.CONNECT_TIMEOUT, 100);
        ((BindingProvider)port).getRequestContext()
                           .put(JAXWSProperties.REQUEST_TIMEOUT, 100);

Saturday, May 26, 2012

How to put a time restriction on a method in java?

I have a specific requirement where in I am calling a method and I want to get the response within a specific duration.
For example, I am trying to fetch the contents of a web-page.

If within 3 seconds, I get the response, its good, otherwise, I want to give a message to the user that internet is too slow.

Now, how do I do this?

You could make use of the ExecutorService and its timeout facilities. The idea is to execute the method you want to call in a different thread, and let the ExecutorService cancel it after a specific time. Here is a simple example, using two fixed threads. You'd have to adapt this to your needs.

Make a class MyTask implements Callable<Void>


Use this as is done here

Sunday, May 20, 2012

How to upload file using struts and hiberate?

How to upload file using struts and hibernate?

I spent 5-6 hours figuring out how can I upload a file into Blob in a database. So I decided to write a short article.

Add enctype="multipart/form-data" in the form tag (in JSP)

<html:form method="POST" action="/solution.do" enctype="multipart/form-data">


Add 2 fields in ActionForm, one which is populated via struts framework.
Second one which is read by hibernate i.e. uploadedBlob

// This is filled by the code written in Action Class.
    // This has to be done manually and is not done automatically.
    private Blob uploadedBlob;
    public Blob getUploadedBlob() {
        return uploadedBlob;
    }

    public void setUploadedBlob(Blob uploadedba) {
        this.uploadedBlob = uploadedba;
    }
    
    // This is the actual FormFile which gets populated into the ActionForm
    // by struts framework.
    private FormFile uploadedfile;
    public FormFile getUploadedfile() {
        return uploadedfile;
    }

    public void setUploadedfile(FormFile uploadedfile) {
        this.uploadedfile = uploadedfile;
    } 

Add the following in formbean.hbm.xml

<property column="uploadedfile" name="uploadedBlob" type="blob"/>

In Action Class, convert FormFile to Blob and set it in FormBean (while saving)

// Convert FormFile to a byte Array
        byte[] byteArray=formbean.getUploadedfile().getFileData();
        // Convert this byteArray to a blob
        Blob myblob=Hibernate.createBlob(byteArray);
        formbean.setUploadedBlob(myblob);

For saving this formbean to database use
private boolean saveOrUpdate(SolutionFormBean formbean) 
{
        Session session = null;

        //Transaction object
        // Nothing happens without transaction in hibernate.
        Transaction transaction = null;
        try {
            // This step will read hibernate.cfg.xml
            // and prepare hibernate for use
            SessionFactory sessionFactory = new Configuration()
                                             .configure().buildSessionFactory();
            session = sessionFactory.openSession();
            // Using a transaction is mandatory.
            transaction = session.beginTransaction();
            session.saveOrUpdate(formbean);
            // Commit it
            transaction.commit();
            System.out.println("Done");
            return true;
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        } finally {
            // Actual row insertion will happen at this step
            if(session!=null)
            {
                session.flush();
                session.close();
            }
            return true;
        }
    }

While reading Blob from database, you would have to do the reverse, i.e.
convert Blob to byteArray and write to ServletOutputStream

Blob dbBlob = dbBean.getUploadedBlob();
        int bloblength=(int)dbBlob.length();
        byte[] tempByte = dbBlob.getBytes(1, bloblength);
        // Now we have converted blob to byte array.
        ServletOutputStream out = response.getOutputStream();
        // For reading more about this header do check out the following link
        // http://javakafunda.blogspot.com/2011/10/forcing-saveas-using-http-header.html
        response.setHeader("Content-Disposition", "attachment; filename="
                                                       +formbean.getFilename());
        out.write(tempByte);
        out.flush();
        out.close();

Sunday, May 6, 2012

How to configure end point WSDL URL at runtime?

Configure WSDL URL at run-time :

http://biemond.blogspot.in/2009/04/changing-wsdl-url-endpoint-in-jax-ws.html

Saturday, May 5, 2012

A perfect example to understand wait and notify in threads

class myWriterThread implements Runnable
{
    private mClass userInput;
    public myWriterThread(mClass userInput) {
        this.userInput = userInput;
    }
    public void run() {
        userInput.waitForInput();
    }
}
class myReaderThread implements Runnable
{
    private mClass userInput;

    public myReaderThread(mClass userInput) {
        this.userInput = userInput;
    }


    public void run() {
        userInput.ReadInput();
    }
}
class mClass 
{
    public synchronized void waitForInput() 
    {
        while(!userInput.equals("Y"))
        {
            try
            {
                System.out.println("Going to wait");
                wait();
            }
            catch(InterruptedException e)
            {
                System.out.println(e.getMessage());
                System.out.println("Got interrupted");
            }
        }
        System.out.println("Wait for Input notified");
    }
    public synchronized void ReadInput()
    {
       try
        {
             userInput="Y";
             System.out.println("Reader has set userInput to Y");
             notify();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        System.out.println("I am exiting ReadInput");
    }        
    private String userInput;

    public mClass(String userInput) {
        this.userInput = userInput;
    }
}
public class CustomClass
{
    public static void main(String args[])
    {
        mClass m = new mClass("N");
        Thread t1 = new Thread(new myWriterThread(m));
        Thread t3 = new Thread(new myWriterThread(m));
        t3.start();
        t1.start();
        Thread t2 = new Thread(new myReaderThread(m));
        t2.start();
    }
}

Sunday, April 22, 2012

How to format an XML String in java

Generally we get XMLs as string in java and that is highly unreadable and unformatted.

How do I format it ??

I am just presenting one of the many ways to do that.

Thanks to http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java

You would need to import these:

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

Pretty straight forward function is available:

public static String prettyFormat(String input, int indent) {
        try
        {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            // This statement works with JDK 6
            transformerFactory.setAttribute("indent-number", indent);
            
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        }
        catch (Throwable e)
        {
            // You'll come here if you are using JDK 1.5
            // you are getting an the following exeption
            // java.lang.IllegalArgumentException: Not supported: indent-number
            // Use this code (Set the output property in transformer.
            try
            {
                Source xmlInput = new StreamSource(new StringReader(input));
                StringWriter stringWriter = new StringWriter();
                StreamResult xmlOutput = new StreamResult(stringWriter);
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
                transformer.transform(xmlInput, xmlOutput);
                return xmlOutput.getWriter().toString();
            }
            catch(Throwable t)
            {
                return input;
            }
        }
    }

    public static String prettyFormat(String input) {
        return prettyFormat(input, 2);
    }

How to log SOAP Request and response XML in log file

Thanks to http://www.coderanch.com/t/549539/Web-Services/java/Convert-SOAP-response-SOAP-XmL
http://qa.netbeans.org/modules/j2ee/promo-g/end2end/hello_ws.html

It is mostly desired to log the SOAP request and response XML into log file.
But there is no direct way, using which you can log the XML, because the XML generation part is in the control of the webservice framework. But the good news that you can configure it to print the XML where ever you like it to.

Configure logging of XML on server side using Netbeans

Configure logging of XML on client side using Netbeans

How to convert SOAPMessage to a String

Tuesday, April 17, 2012

Providing a default exception handling strategy in Java applications

Source : http://blog.smartkey.co.uk/2012/03/providing-a-default-exceptoin-strategy/comment-page-1/

When writing a Java application you may need to consider how that application should react when an uncaught exception is encountered. Generally, when an exception is not handled, the threads stack trace is printed to the error stream and the throwing thread dies; potentially causing the application to shut down if there are no other active (or daemon) threads running.

If your application runs as a server, then there will likely be multiple threads (created by the IO libraries) which are used to respond to the incoming requests. This makes it hard to implement a consistent strategy that can handle all uncaught exceptions in a uniform way.

The following program illustrates how to register a default policy for handling uncaught exceptions

public class TestMain 
{
 public static void main(String[] args) 
 {
  Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() 
  {
   @Override
   public void uncaughtException(Thread t, Throwable e) 
   {
    if (e instanceof InvocationTargetException) 
    {
     e = e.getCause();
    }
    //handle all uncaught exceptions here
    System.out.println("Got exception with message: " + e.getMessage());
   }
  });
  throw new RuntimeException("Gonna die!");
 }
}

Setting the default exception handler (line 3) will alter the default behavior for handling uncaught exceptions in the JVM. The implementation of the uncaughtException method (lines 6-10) will now determine what should be done. In this case just the message from the exception will be printed to standard out. A more real-world application of this might be to send a warning message to an operations team, or to take some other remedial action.

The caveat to this approach is that the default exception handler will only be used in cases where neither the offending Thread, or the ThreadGroup that it belongs to, have had their uncaught exception handlers set. If your application manages its own threads, then this will likely not be a problem for you. If your application runs in an application server, then you might well find that the application server has set these handlers already.

Sunday, April 15, 2012

Sample program to test SSL Connection with certicates

Keywords : ssl sample program, test program to test ssl, How can I check connectivity to ssl using java, test connectivity with ssl, Ssl connectivity testing programs.


I was looking for a sample program in java, using which I can test the connectivity to SSL.

Then I found http://www.herongyang.com/JDK/SSL-Socket-Server-Example-SslReverseEchoer.html

There are two programs

SslReverseEchoer.java (Running on server side)

SslSocketClient.java (running on client side)

How to test these programs

How to make my browser trust my server certificate?

Hi Guys,

I was exploring the SSL thing, and wanted to know what are the steps involved in making my browser trust the server certificate that server is sending.

First of all you need to generate a keystore (This needs to be done on server side).

Now convert this into a server certificate (and send it to client side)

Make the changes in server.xml

Check untrusted certificate on client side

How to add this certificate to Trusted Root Certification Authorities on Google Chrome??


Saturday, April 14, 2012

Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object

I was getting the following error in the logs of the tomcat, when I try to start the tomcat server.

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

Things I tried but didn't work
=========================
1) I used class finder to find that which jar contains this class java.lang.Object, and it was rt.jar.
I added rt.jar in the classpath. But of no use.
2) I made a Environment variable CATALINA_HOME, JAVA_HOME, but didn't help.
3) I tried rebooting the machine every time, after I set the paths specified in step 2.
4) Uninstalling and re-installing the tomcat didn't help.


ROOT CAUSE AND SOLUTION:
=========================
During installation of tomcat, the default jre directory that was coming on the installation screens of tomcat didn't had rt.jar
I realized this when I checked the jre folder.

Then I decided to uninstall and re-install tomcat and while re-installation I took care while specifying the jre folder. And the new jre folder had rt.jar

This solution made it work. :)

I m happy :)


How to configure Tomcat to support SSL or https

Thanks to http://www.mkyong.com/tomcat/how-to-configure-tomcat-to-support-ssl-or-https/


1. Generate Keystore

Check your certificate details

2. Connector in server.xml

Saved it and restart Tomcat, access to https://localhost:8443/



Wednesday, April 4, 2012

How to create dynamic trigger in Oracle?

Thanks to http://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:59412348055

Problem:

I'm trying to create a generic before update trigger
which will compare all :old.column_values to all
:new.column_values. If the column_values are different, then I
would like to log the change to a separate table. When I try to
compile :old., Oracle return an
"(1):PLS-00049: bad bind variable 'NEW." Can you recommend a
dynamic way to accomplish this? Thanks in advance.

Solution:

:new and :old are like bind variables to the trigger, they are not 'regular' variables.
you cannot dynamically access them, only 'statically'.

I suggest you consider writing a stored procedure or sql*plus script to write a trigger
that statically references the new/old values. For example, if you wanted to save in a
table the time of update, who updated, table updated, column modified and new/old values,
you could code a sql*plus script like:

--------------------------------------------------------------------
create table audit_tbl
(    timestamp    date,
    who            varchar2(30),
    tname        varchar2(30),
    cname        varchar2(30),
    old            varchar2(2000),
    new            varchar2(2000)
)
/

create or replace package audit_pkg
as
    procedure check_val( l_tname in varchar2, 
                             l_cname in varchar2, 
                 l_new in varchar2, 
                             l_old in varchar2 );

    procedure check_val( l_tname in varchar2, 
                             l_cname in varchar2, 
                     l_new in date, 
                             l_old in date );

    procedure check_val( l_tname in varchar2, 
                             l_cname in varchar2, 
                 l_new in number, 
                             l_old in number );
end;
/


create or replace package body audit_pkg
as

procedure check_val( l_tname in varchar2,
                     l_cname in varchar2,
             l_new in varchar2,
                     l_old in varchar2 )
is
begin
    if ( l_new <> l_old or
         (l_new is null and l_old is not NULL) or
         (l_new is not null and l_old is NULL) )
    then
        insert into audit_tbl values
        ( sysdate, user, upper(l_tname), upper(l_cname),
                             l_old, l_new );
    end if;
end;

procedure check_val( l_tname in varchar2, l_cname in varchar2,
             l_new in date, l_old in date )
is
begin
    if ( l_new <> l_old or
         (l_new is null and l_old is not NULL) or
         (l_new is not null and l_old is NULL) )
    then
        insert into audit_tbl values
        ( sysdate, user, upper(l_tname), upper(l_cname),
          to_char( l_old, 'dd-mon-yyyy hh24:mi:ss' ),
          to_char( l_new, 'dd-mon-yyyy hh23:mi:ss' ) );
    end if;
end;

procedure check_val( l_tname in varchar2, l_cname in varchar2,
             l_new in number, l_old in number )
is
begin
    if ( l_new <> l_old or
         (l_new is null and l_old is not NULL) or
         (l_new is not null and l_old is NULL) )
    then
        insert into audit_tbl values
        ( sysdate, user, upper(l_tname), upper(l_cname),
                                 l_old, l_new );
    end if;
end;

end audit_pkg;
/


set serveroutput on
set feedback off
set verify off
set embedded on
set heading off
spool tmp.sql

prompt create or replace trigger aud#&1
prompt after update on &1
prompt for each row
prompt begin

select '    audit_pkg.check_val( ''&1'', ''' || column_name ||
          ''', ' || ':new.' || column_name || ', :old.' || 
             column_name || ');'
from user_tab_columns where table_name = upper('&1')
/
prompt end;;
prompt /

spool off
set feedback on
set embedded off
set heading on
set verify on

@tmp
-------------

That will build the generic table and package plus generate a trigger that would look 
like:

SQL> @thatscript dept


create or replace trigger aud#dept
after update on dept
for each row
begin
    audit_pkg.check_val( 'dept', 'DEPTNO', :new.DEPTNO, :old.DEPTNO);
    audit_pkg.check_val( 'dept', 'DNAME', :new.DNAME, :old.DNAME);
    audit_pkg.check_val( 'dept', 'LOC', :new.LOC, :old.LOC);
end;
/

Thursday, March 8, 2012

Formatting your HTML Document using Notepad++ !!

Formatting your HTML Document !!

I always wished I had a tool that could format my ugly looking HTML document. The feature is provided by Notepad++

The version of Notepad++ that has this feature


How to format HTML using Notepad++


Wednesday, March 7, 2012

Reading CSV made easy

How to use CSV Reader


CSV Reader

Tuesday, February 21, 2012

How to invoke a web service using JDeveloper (given a WSDL)

How to call a web service from Jdeveloper (provided WSDL file or URL)

Create a New Empty Project















Thursday, February 9, 2012

The prefix "jaxb" for element "jaxb:globalBindings" is not bound.

I'm using xjc to compile XML Schema into JAXB objects and the
compiling is fine unless I try to define jaxb bindings. For instance,
if I try adding this code in the schema:

<xs:annotation>
<xs:appinfo>
<jaxb:globalBindings generateIsSetMethod="true">
bindingStyle="modelGroupBinding"
choiceContentProperty="true" >

<xjc:serializable uid="12343"/>
<jaxb:javaType name="short"
xmlType="xs:long"
printMethod="javax.xml.bind.DatatypeConverter.printShort"
parseMethod="javax.xml.bind.DatatypeConverter.parseShort"/>
</jaxb:globalBindings>
</xs:appinfo>
</xs:annotation>

xjc complains with:
[ERROR] The prefix "jaxb" for element "jaxb:globalBindings" is not
bound.

SOLUTION
========

Missing namespace declaration. There should be something like this:
xmlns:jaxb="URI"
Just look for the other namespace definitions (i.e. xmlns:s) and
add the above attribute to the end.

Source : http://www.velocityreviews.com/forums/t137983-problem-in-xjc-with-recognizing-jaxb-prefix.html

xsd:date maps to java.util.Calendar

My schema has an element of type xs:date, which jaxb maps to a java.util.Calendar. If I create a Calendar object with Calendar.getInstance(), it marshalls to "2003-11-24-05:00".

How can I get it to marshall to just "2003-11-24"?

SOLUTION:
Write a converter class (see MyConverter below) and added an annotation/appinfo to the xml schema, also shown below.


public class MyConverter
{
    static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    static public String printCalendar(Calendar c)
    {
        return df.format(c.getTime());
    }

    static public Calendar parseCalendar(String c) throws ParseException
    {
        Date d = df.parse(c);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        return cal; 
    }
}

<xsd:schema ...>
<xsd:annotation>
<xsd:appinfo>
<jaxb:globalBindings 
<jaxb:javaType name="java.util.Calendar" xmlType="xsd:date"
printMethod="MyConverter.printCalendar"
parseMethod="MyConverter.parseCalendar"
/>
</jaxb:globalBindings>
</xsd:appinfo>
</xsd:annotation>
...
</xsd:schema>

Source : https://forums.oracle.com/forums/thread.jspa?threadID=1624090

Sunday, February 5, 2012

What's the difference between display: none and visibility: hidden?

Question: What's the difference between display: none and visibility: hidden?
The display: none and visibility: hidden CSS properties appear to be the same thing, but they aren't.

Answer:
These two style properties do two different things.

visibility: hidden hides the element, but it still takes up space in the layout.

display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code.

You can see the effect of these style properties on this page. I created three identical swatches of code, and then set the display and visibility properties on two so you can see how they look.

Source: http://webdesign.about.com/od/css/f/blfaqhidden.htm

Sunday, January 22, 2012

Removing scriptlets from a JSP

I have read on internet that it is a very bad idea to use scriplets in a JSP.
Even if you need to use scriplets in a JSP, that is most likely because you are doing something in JSP, which should be better handled in a Action class.

So, I am trying to gather few tips, how to convert an existing JSP with scriplet to a JSP without scriplet.

Guys please comment and add more, i'll keep on adding it to the main post :)
There could be multiple ways of doing the same thing, you guys can add your knowledge to this, so that we can come up with a post, that we can re-use.

Most of the help has been taken from http://www.roseindia.net/jstl/jstlcoretags.shtml

You might like to read a discussion on WHY to avoid scriplets


Scriplet code Without scriplet code
<%=request.getContextPath()%> ${pageContext.request.contextPath}
<%= request.getRequestURI().contains("/events/")%> ${fn:contains(pageContext.request.requestURI, '/events/')}
<%= request.getRequestURI().contains("/events/") ? "class='selected'" : ""%> ${fn:contains(pageContext.request.requestURI, '/events/')? 'class="selected"' : ''}
<% if(request.getRequestURI().contains("/events/")) { %>

...

<%}%>
<c:if test="${fn:contains(pageContext.request.requestURI, '/events/')}">
...
</c:if>
<% String s = request.getParameter("text1"); %> <c:set var="s" value="${param.text1}" >
<% out.println(s);%> <c:out value="${s}" />
<% if(s.equals("sam"))
{
out.println("Good Morning...SAM!");
}
%>
<c:if test="${s eq 'sam'}">
<c:out value="Good Morning...SAM!" />
</c:if>

<%
switch(s)
{
case 1: out.println("Sunday");
case 2: out.println("Monday");
...
}
%>

<c:choose>
<c:when test="${s==1}">Sunday </c:when>
<c:when test="${s==2}">Monday</c:when>
<c:when test="${s==3}">Tuesday</c:when>
<c:when test="${s==4}">Wednesday</c:when>
<c:when test="${s==5}">Thursday</c:when>

<c:otherwise>
select between 1 & 5
</c:otherwise>
</c:choose>

<%
HttpSession session = request.getSession();
out.println(

(Questions)

session.getAttribute("Questions").getQuestionPaperID());

%>
<c:out value="${sessionScope.Questions.questionPaperID}" />

<%request.getSession().getAttribute("my_var") %>

Can be accessed using JSTL with the sessionScope keyword. To access my_var, call sessionScope.myvar

Remember to use sessionScope

<c:out value="${sessionScope.my_var}"/>

To make it easier, this link would help you understand the JSTL tags better...

Thursday, January 12, 2012

Basic fundas about using float or double

Think again if you are going to use float or double for amount/currency field.

Reason behind this is

Floats have a fixed number of total bits of precision, which must be shared among the integer and fractional parts. If you use more of those bits to store a larger integer portion (123456 vs. just 12), that leaves fewer for the fractional portion (.4 vs. .45678).

Also, you should be aware that since float and double are base-2 formats, rather than base-10, many values that can be represented with a small, finite number of digits in base-10 cannot be stored in a double or float. For instance, it is impossible to store exactly 1/10 (0.1) in a double or float, just as it's impossible to store 1/3 (0.333...) exactly in a finite number of digits in base-10.

Demonstration code:

    public static void main(String args[]) {  
        double d = 1997500.43;  
        String s = "1997500.43";  
        float f = (float) d;  
        System.out.println(f);//1997500.4  
  
        float f3 = Float.parseFloat(s);  
        System.out.println(f3);//1997500.4  
  
        float f4 = Double.valueOf(s).floatValue();  
        System.out.println(f4);//1997500.4  
  
        float f5 = new Double(s).floatValue();  
        System.out.println(f5);//1997500.4  
  
        float xFloat;  
        Double x = new Double("63.8644951");  
        xFloat = x.floatValue();  
        System.out.println(xFloat);// 63.864494  
  
        float xFloat2;  
        Double x2 = new Double("3333263.8644951");  
        xFloat2 = x2.floatValue();  
        System.out.println(xFloat2);// 3333263.8  
}  

Detailed information about floats and doubles is available at : http://www.coderanch.com/t/564234/java/java/Precision-loss-String-Float-double

Best Practices while writing Java code

Usually many of us write the java code in a try-catch block as follows

try
{
       // some code here
}
catch(Exception e)
{
    // log exception here
}

Better way to do it is

try
{
       // some code here
}
catch(Exception e)
{
    // log exception here
}
catch(Throwable ex)
{
     // One must add throwable clause always
     // because in case of some error also, you can
     // log it and see, what error has occured.
}


If you do not add Throwable clause, and in production, some error occurs, Then nothing will be logged in your logs, you may end up breaking your head, why the hell it is not working.

Make it a habit to use try-catch-Throwable in place of try-catch-Exception

Classes not being generated in WEB-INF/classes folder

Posting this on behalf of Vaibhav Garg..

The settings in the Eclipse were perfect to store the output in the output folder as WEB-INF/classes folder. But, still the classes were not being generated in this folder when the code was built. 

Reason:

There were a couple of dependent projects included in the build path. And, there were errors in those projects. Due to this reason, the project was not getting built. And, the error list was huge around 2500 errors in the entire workspace. So, it was difficult to get the exact reason whether the project has some errors or not.

Once the errors in dependent projects were resolved, it got built successfully and the class files got generated in the WEB-INF/classes folder.

Monday, January 2, 2012

How to check which application is using a particular port?

Source : http://oolacola.blogspot.com/2009/04/how-to-find-out-which-application-is.html

Let's say that we are looking for port 80 -- IIS, Apache and other web servers listen in port 80, so when you are having problems starting Apache, this technique will be useful. Here is the command.

C:\>netstat -aon | findstr 80

-a means list all active connections and their ports. -o means include their process IDs. -n means display the port numbers numerically.


The pipe symbol ( | ) means, that instead of the result of netstat being displayed on the screen, feed it's result to the findstr process -- we are looking specifically for the line which has 0.0:80 -- you actually don't need findstr, but I don't want to scroll down and hunt down manually which app is using port 80. You might see something like this.

TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 560

Aha! now we know that process 560 is using port 80 (that last column right there, is the process ID), you could press CTRL-ALT-DEL now to show the process window, and manually look up which app has the process ID 560, or you could enter ..

C:\>tasklist | findstr 560