Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Tuesday, 30 July 2013

Strecks 1.0 released

Strecks a set of Java 5-specific extensions Struts framework, was released from beta on friday. Strecks, is annotation based and adds a number of modern features to Struts-based applications, including POJO actions, dependency injection, declarative validation and data binding, interceptors, pluggable views, as well as seamless Spring integration. It is also highly extensible and amenable to test driven development. The following is a brief list of features available in Strecks 1.0:
  • Pure POJO action beans with zero framework dependencies
  • Annotation-based dependency injection (typed request parameters, session attributes, Spring beans, and many others)
  • Converters and validators type-parameterized using Java 5 generics
  • Mechanisms for facilitating use of redirect after post pattern
  • Support for rendering using Spring MVC Views and View Resolvers
  • Pre- and post- action interceptors, with access to dependency resolved action beans as well as full runtime context
  • Works on the unchanged Struts 1.2.x and 1.3.x code bases.
  • Actions, form validation and data conversion easily testable with plain unit tests, with no additional test libraries required.

Struts: Paging and Sorting with Displaytag

In the previous post, I described the use of Displaytag to implement paging in a simple JSP. In this example, I describe the use of Displaytag to implement sorting along with paging in Struts.
Skip to Sample Code
In this example, we take a single input field, which is used to filter the employee list based on the minimum salary. Follow these steps to implement the solution.
  1. Start by importing struts-blank.war file into Eclipse.
  2. Follow the configuration steps 1, 2, 4, 5, and 6 in from the "Pagination with Displaytag" post.
  3. Create the search page as shown below
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
    <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
    <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
    <%@ taglib uri="http://displaytag.sf.net" prefix="display"%>
    <%@ page import="beans.Employee,data.DAO,java.util.List,org.displaytag.tags.TableTagParameters,org.displaytag.util.ParamEncoder"%>
    <html:html>
    <head>
    <title>Search page</title>
    <link rel="stylesheet" type="text/css"
    href="/StrutsPaging/css/screen.css" />
    </head>
    <body bgcolor="white">
    <html:form action="/search.do">
    <table>
    <tr>
    <td>Minimum Salary:</td>
    <td><html:text property="minSalary"></html:text></td>
    </tr>
    <tr>
    <td colspan="2"><html:submit property="submit" /></td>
    </tr>
    </table>
    </html:form>
    <logic:notEqual name="empList" value="null">
    <jsp:scriptlet>
    if (session.getAttribute("empList") != null) {
    String sortBy = request.getParameter((new ParamEncoder("empTable")).encodeParameterName(TableTagParameters.PARAMETER_SORT));
    DAO.sort((List) session.getAttribute("empList"), sortBy);
    }
    </jsp:scriptlet>

    <display:table name="sessionScope.empList" pagesize="4" id="empTable" sort="external" defaultsort="1" defaultorder="ascending">
    <display:column property="empId" title="ID" sortable="true" sortName="empId" headerClass="sortable" />
    <display:column property="empName" title="Name" sortName="empName" sortable="true" headerClass="sortable" />
    <display:column property="empJob" title="Job" sortable="true" sortName="empJob" headerClass="sortable" />
    <display:column property="empSal" title="Salary" sortable="true" headerClass="sortable" sortName="empSal" />
    </display:table>
    </logic:notEqual>
    </body>
    </html:html>
    pages/search.jsp
    Note that
    1. The display:table tag has the sort attribute defined as "external".
    2. Since the sort type is external, we have to provide for the actual sorting, which I implemented in the DAO class itself (see below).
    3. The column to sort by is obtained by the following peice of code
      request.getParameter((new ParamEncoder("empTable")).encodeParameterName(TableTagParameters.PARAMETER_SORT))
  4. Create the Action class and Form bean as shown below.
    public class SearchAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse httpservletresponse) throws Exception {
    if (form == null) {
    return mapping.findForward("success");
    }
    try {
    SearchForm searchForm = (SearchForm) form;
    if (searchForm.getMinSalary().equals("")) {
    return mapping.findForward("success");
    }
    long minSal = Long.parseLong(searchForm.getMinSalary());
    List data = DAO.getData(minSal);

    request.getSession().setAttribute("empList", data);

    } catch (Exception e) {
    e.printStackTrace();
    }
    return mapping.findForward("success");
    }
    }
    actions.SearchAction
    public class SearchForm extends ActionForm {
    private String minSalary;
    public String getMinSalary() {
    return minSalary;
    }
    public void setMinSalary(String minSalary) {
    this.minSalary = minSalary;
    }
    }
    forms.SearchForm.java
  5. Modify the struts-config.xml to include the action and actionform as shown below
    <form-beans>
    <form-bean name="searchForm" type="forms.SearchForm" />
    </form-beans>
    <action-mappings>
    <action path="/Welcome" forward="/pages/Welcome.jsp" />
    <action name="searchForm" path="/search"
    type="actions.SearchAction" scope="session">
    <forward name="success" path="/pages/search.jsp"></forward>
    </action>
    </action-mappings>
  6. Create the DAO class as shown below
    public class DAO {
    public static List getData(long minSal) {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.getCurrentSession();
    List result = null;
    try {
    session.beginTransaction();
    result = session.createQuery("from Employee as emp where emp.empSal >=?").setLong(0, minSal).list();
    System.out.println("Result size : " + result.size());
    session.getTransaction().commit();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }

    public static List sort(List<Employee> list, String sortBy) {
    Comparator comp = getComparator(sortBy);
    Collections.sort(list, comp);
    return list;
    }

    private static Comparator getComparator(String sortBy) {
    System.out.println("Sort by : " + sortBy);
    if (sortBy ==null) {
    return new NameComparator();
    }
    if (sortBy.equals("empName"))
    return new NameComparator();
    if (sortBy.equals("empId"))
    return new IdComparator();
    if (sortBy.equals("empSal"))
    return new SalComparator();
    if (sortBy.equals("empJob"))
    return new JobComparator();

    return null;

    }

    private static class NameComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return employee1.getEmpName().compareTo(employee2.getEmpName());
    }
    }

    private static class IdComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return new Long(employee1.getEmpId()).compareTo(new Long(employee2.getEmpId()));
    }
    }

    private static class SalComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return new Long(employee1.getEmpSal()).compareTo(new Long(employee2.getEmpSal()));
    }
    }

    private static class JobComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return employee1.getEmpJob().compareTo(employee2.getEmpJob());
    }
    }

    }
    DAO.java
    Note here that
    1. The list sorting is done in this class itself.
    2. The Comparators are used to compare order the list based on each individual field (there may be scope for improvement here).

Reverse Ajax with Direct Web Remoting (DWR)

Direct Web Remoting (DWR), is an open source Java library that can be used to implement Ajax in Java web applications with minimal Javascript coding. Using DWR, we can invoke server-side Java methods from Javascript in the browser. DWR 2.0 introduces a new feature, dubbed "Reverse Ajax", using which server-side Java can "push" updates to the browser. In this post, I tried to use a simplistic web application that will demonstrate the use of DWR for "Reverse Ajax".
In this example, I use a servlet that will be pushing information to the browser clients. Here is how to implement the example.
  1. Download DWR 2.0 from here, dwr.jar file has to be included in the classpath.
  2. Create the Service: This service generates messages which will be written to the browser. Here is the code for the Service.
    package utils;

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;

    import org.directwebremoting.ServerContext;
    import org.directwebremoting.proxy.dwr.Util;

    public class Service {

    private int count = 0;

    public void update(ServerContext wctx) {
    List<Data> messages = new ArrayList<Data>();
    messages.add(new Data("testing" + count++));

    // Collection sessions = wctx.getAllScriptSessions();
    Collection sessions = wctx.getScriptSessionsByPage("/ReverseAjax/index.html");
    Util utilAll = new Util(sessions);
    utilAll.addOptions("updates", messages, "value");
    }
    }
    Service.java
  3. Create the Message Container: The message container is a simple Java bean that holds the message.
    package utils;

    public class Data {
    private String value;

    public Data() {
    }

    public Data(String value) {
    this.value = value;
    }

    public String getValue() {
    return value;
    }

    public void setValue(String value) {
    this.value = value;
    }
    }
    Data.java
  4. Create the Servlet: Here is the code for the Servlet.
    package servlets;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.directwebremoting.ServerContext;
    import org.directwebremoting.ServerContextFactory;

    import utils.Service;

    public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Service service = new Service();
    ServerContext wctx = ServerContextFactory.get(this.getServletContext());
    for (int i = 0; i < 10; i++) {
    service.update(wctx);
    try {
    Thread.sleep(1000);
    }
    catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    PrintWriter writer = response.getWriter();
    writer.println("Done");
    writer.close();

    }}
    TestServlet.java
    • The ServerContext is used by DWR to get information of the clients that have open sessions on the server.
  5. The Web Page: This is the code for the Web Page (index.html).
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>index</title>
    <script type='text/javascript' src='dwr/engine.js'></script>
    <script type='text/javascript' src='dwr/interface/Service.js'></script>
    <script type='text/javascript' src='dwr/util.js'></script>
    </head>
    <body onload="dwr.engine.setActiveReverseAjax(true);">
    <ul id="updates">
    </ul>

    </body>
    </html>
    index.html
    • engine.js handles all server communications.
    • util.js helps you alter web pages with the data you got from the server.
    • The path to the scripts is relative to the root of the web content. The DWR servlet (defined in the web.xml file) will provide these scripts.
    • dwr.engine.setActiveReverseAjax(true); is used to activate Reverse Ajax
    • The id of the list is the same as the parameter set in the Service.
  6. The Web Deployment Descriptor:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>ReverseAjax</display-name>

    <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
    <param-name>debug</param-name>
    <param-value>true</param-value>
    </init-param>
    <init-param>
    <param-name>activeReverseAjaxEnabled</param-name>
    <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>servlets.TestServlet</servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/testServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
    WEB-INF/web.xml
    • The DWR Servlet has to be loaded on startup
    • Setting activeReverseAjaxEnabled to true sets Reverse Ajax to be active. In this case Reverse Ajax used will be through polling or comet requests (extended http requests). If this is false, then inactive Reverse Ajax (piggybacking) will be used. In this case, the server waits for requests from the client and piggybacks the updates with the response.
  7. The DWR Configuration: The DWR configuration is defined in the dwr.xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd">
    <dwr>
    <allow>
    <create creator="new" javascript="Service" scope="application">
    <param name="class" value="utils.Service" />
    </create>
    <convert converter="bean" match="utils.Data" />
    </allow>
    </dwr>
    WEB-INF/dwr.xml
    • "create" is used to define a Java object as being available to Javascript code.
    • The "javascript" attribute is the one that will be used in case of invoking the server-side methods from Javascript.
    • The converter definition allows utils.Data to be used as a parameter.

  8. Environment: This example was tested using DWR 2.0 RC 3, on Tomcat 5.5

Pagination with DisplayTag

Displaytag is an opensource tag library that can be used to display tables on JSPs. Apart from being able to display tables, the displaytag library also has support for JSR-168 compliant portals through the "Display portal compatibility library", and also supports exporting tables to Excel through the "Excel export module". The following example demonstrates the use of DisplayTag to display a long list as a multi-page table. For this example, I used the default EMP table from the sample database which will be built at during Oracle installation. This example uses Oracle 10g R2, Java 5, Tomcat 5.5 and Hibernate 3.2.
Skip to Sample Code
To run the example, follow these steps:
  1. Download Displaytags from here, and include the displaytag-1.1.jar file in your classpath.
  2. Download the latest version of hibernate from hibernate.org, and include all the required jars in your classpath.
  3. Create the pagingEmp.jsp page as shown below
    <jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:display="urn:jsptld:http://displaytag.sf.net">
    <jsp:directive.page contentType="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="css/screen.css" />
    <jsp:scriptlet>
    session.setAttribute( "EmpList", data.DAO.getData());
    </jsp:scriptlet>
    <h2 align="center">Emp Table with Display tag</h2>
    <display:table name="sessionScope.EmpList" pagesize="4">
    <display:column property="empId" title="ID" />
    <display:column property="empName" title="Name" />
    <display:column property="empJob" title="Job" />
    <display:column property="empSal" title="Salary" />
    </display:table>
    </jsp:root>
    pagingEmp.jsp
  4. Create the Employee class, which is the bean that will hold the Employee data as shown below:
    public class Employee {
    public long empId;
    public String empName;
    public String empJob;
    public long empSal;
    public long getEmpId() {
    return empId;
    }
    public void setEmpId(long empId) {
    this.empId = empId;
    }
    public String getEmpJob() {
    return empJob;
    }
    public void setEmpJob(String empJob) {
    this.empJob = empJob;
    }
    public String getEmpName() {
    return empName;
    }
    public void setEmpName(String empName) {
    this.empName = empName;
    }
    public long getEmpSal() {
    return empSal;
    }
    public void setEmpSal(long empSal) {
    this.empSal = empSal;
    }
    }
    Employee.java
  5. Define the styles for displaying the table. Displaytag renders the tables as simple HTML tables, with the standart tr,td,th and table tags. The css file is shown below
    td {
    font-size: 0.65em;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 11px;
    }
    th {
    font-size: 0.85em;
    border-top: 2px solid #ddd;
    border-right: 2px solid #ddd;
    border-left: 2px solid #666;
    border-bottom: 2px solid #666;
    }
    table {
    border: 1px dotted #666;
    width: 80%;
    margin: 20px 0 20px 0;
    }
    th,td {
    margin: 0;
    padding: 0;
    text-align: left;
    vertical-align: top;
    background-repeat: no-repeat;
    list-style-type: none;
    }
    thead tr {
    background-color: #bbb;
    }
    tr.odd {
    background-color: #fff;
    }
    tr.even {
    background-color: #ddd;
    }
    screen.css
  6. Configure Hibernate for accessing database
    1. Create the Employee.hbm.xml file to map the Employee bean with the database table as shown below
      <?xml version="1.0"?>
      <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
      <hibernate-mapping>
      <class name="beans.Employee" table="Emp">
      <id name="empId" column="EMPNO" type="long">
      <generator class="native"/>
      </id>
      <property name="empName" column="ENAME" />
      <property name="empJob" column="JOB" />
      <property name="empSal" column="SAL" type="long"/>
      </class>
      </hibernate-mapping>
      Employee.hbm.xml

      This file is placed in the same directory as the Employee.java class.
    2. Create the Hibernate Configuration file hibernate.cfg.xml in the root directory of the classes.
      <?xml version='1.0' encoding='utf-8'?>
      <!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
      <hibernate-configuration>
      <session-factory>
      <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
      <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
      <property name="connection.username">scott</property>
      <property name="connection.password">tiger</property>
      <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
      <mapping resource="beans/Employee.hbm.xml"/>
      <property name="hibernate.current_session_context_class">thread</property>
      </session-factory>
      </hibernate-configuration>
      hibernate.cfg.xml
  7. Create a class for Data access as shown below
    public class DAO {
    public static List getData() {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.getCurrentSession();
    List result = null;
    try {
    session.beginTransaction();
    result = session.createQuery("from Employee").list();
    session.getTransaction().commit();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }
    }
    DAO.java
Running this example on tomcat shows the Emp table data in a table with 4 records per page, as set in the pagesize attribute of the display:table tag.

Marker Interfaces In Java

Something wrong with JDBC implementation : ojdbc14.jar

BigDecimal
(Problem with oracle jdbc implementation(java 1.4) )
Few days before, I stumbled upon an intriguing defect. It was related to update of number(13,10) column in oracle database. The same piece of jdbc sql update was working good while debugging my project in eclipse workbench setup. But same code was generating random output while running it in Jboss server. That was surprising for me. But it was not true. Same code was not working.

Busy debugging:
I tried all possible permutations and combinations for debugging,  I could not identify reason. Java is platform independent and should behave same every where(:-) though in my case the JDK and OS was same). Then I wrote simple test program to get meta data information about jdbc implementation. Metadata results are not confusing. It says jdbc major version is 11 and minor is 2. Which is definitely something specific to oracle implementation. It does not give me any detail for jdbc version it implements. This is not a problem though. I have already got oracle jdbc implementation version as 11.2.x(ojdbc6.jar).


Solution: 
My sample code was working good with this jdbc implementation. Now I changed it to(ojdbc14.jar). This change started its ugly behavior for updating BigDecimal.

ojdbc6.jar    ------- JDBC implementation of oracle (in Java 6)
ojdbc5.jar    ------- JDBC implementation of oracle (in Java 5)
ojdbc14.jar  ------- JDBC implementation of oracle (in Java 1.4 , mea-culpa)
  
 

java interview with Investment bank -4

This is another set of investment bank java interview questions. This interview was not attended by me but I got this these questions from one of my team mate, who passed these interviews to receive the IB job offer. Here the main focus area were again java collections, memory model, java 1.5 concurrency and design pattern.

1) Tell me about career profile and describe your one of the main project?
   then deep drive on my current project.. why u are using these technology? what feathers of java 1.6 you are using? how you r managing concurrency? how the exceptions are handled?

2) Java collections - when to use ArrayList and Linked list?

3) what is soft reference, weak reference, phantom reference?

4) How is memory managment in java? how the heap is divided in different area?

5) where String literals are stored in heap?

6) How to handle out of memory error and what tools we can use to figure out memory leaks?

7) what is synchronization and locks in java 1.5?

8) news feathers in java 1.5 and java 1.6

9) how to do thread scheduling in java 1.5?

10) con-currency classes in java 1.5?

11) expalin Singltion design pattern and what is double check locking (DCL)  and how to do it with volatile?

Puzzle :

1) you are in one room at 5'th floor of building and it has 3 bulbs and the switch for these bulbs are in ground floor and you can go down only 1 time and tell me how you know particular switch for each bulb? ,, tip --use bub heating funda**

2) you have 1000 teams and each team plays knock out with each other, how many minimum matches you need to figure out winner?

3) write the pragramme to get square root of 100? do not use java math functions?

Management Round:
1) tell me about yourself?

2) Why you want to leave current job?
3) Why you want to join this bank? ..[Get the history of bank and current CEO details and latest mergers]
4) Your key strengths and weakness?
5) tell me how you were managing team?


HR Round:
1) Why would you like to leave current role?
2) What is your long term plan, how you would you like to growth your career?

Thread Creation in Java by Implement Runnable interface

Hi

To create Multiple thread by implement runnable interface in java
Code:


public class Threadtest implements Runnable{
   
    public static void main(String [] args)

    {
        Threadtest t= new Threadtest();
        Thread t1= new Thread(t);
        Thread t2=new Thread(t);
        Thread t3= new Thread(t);
        t1.setName("kumud1");
        t2.setName("kumud2");
        //t3.setName("kumud3");
        t1.start();
        t2.start();
        //t3.start();
       
    }

    public void run() {
        for (int a=0; a<4;a++)
       
        System.out.println("The Current Thread is"+Thread.currentThread().getName());
        try{
        Thread.sleep(5*60*1000000000);
        }
        catch(Exception ex)
        {
           
        }
    }
   
   

}

Searching button using Ajax | How Ajax use in Search and combo list populate in application in Java

Hi Friend
There is Scenario in my application where in Jsp page there is Search button and two combo list ,when we search for department by entering any starting  value populate the all department starting from enter string, and when we select the department . all doctor list will populate doctor list in particular department,
when we select doctor name from list detail of doctor list display in Jsp page



Code:
    DoctorDetail.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var httpRequest;
function getDepartment()
    {
   
    var searchDep=document.loginform.attachToCaseNo.value;
    if (searchDep==""){
        alert("Please enter Departement to search..");
        document.loginform.attachToCaseNo.focus();
        return;
    }
    var searchKey = "mac";
    searchDep = searchDep.toUpperCase();
    //alert(searchDep);
    var url = "getDep?fano="+searchDep+"&searchKey="+searchKey;
//alert (url);
    if (window.ActiveXObject)
    {

        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {

        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function() {processRequest(); } ;
    httpRequest.send(null); 

    }
 function processRequest()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
       
        {
//alert(httpRequest.responseText)
         var FanoListXML = httpRequest.responseXML.getElementsByTagName("FanoList")[0];
         var comboSize=FanoListXML.childNodes.length;
           
            if (comboSize==0) {
                alert("Please Enter Departement Number");
              
                document.loginform.attachToCaseNo.value="";
                document.loginform.attachToCaseNo.focus();
               var CrListXML = new Array();
                    //updateHTML4(CrListXML);
                FanoListXML=new Array();
                updateHTML(FanoListXML);

                return;
            }
            updateHTML(FanoListXML);
           
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}
 

function updateHTML(FanoListXML)
{

   var len = window.document.loginform.case_id_in_temp.options.length;

    while(len>0) {
        len = len -1;
        window.document.loginform.case_id_in_temp.options[len] = null;
    }//end while       

var CrListXML = new Array();
window.document.loginform.case_id_in_temp.options[0] = new Option("Select","0");

      for (loop = 0; loop < FanoListXML.childNodes.length; loop++) {

       var SNS = FanoListXML.childNodes[loop];
       var fanoId = SNS.getElementsByTagName("FanoId")[0];
       var fanos = SNS.getElementsByTagName("Fano")[0];

        eval(window.document.loginform.case_id_in_temp).options[loop+1] = new Option(fanos.childNodes[0].nodeValue,fanoId.childNodes[0].nodeValue);
 

      
       }
    window.document.loginform.case_id_in_temp.value=window.document.loginform.case_id_in_temp.options[1].value ;
    updateHTML4(CrListXML);
}

//for complainant_respondent name filter
function getDoclist()
    {

    var searchFano=document.loginform.case_id_in_temp.value;
            //searchFano = searchFano.toUpperCase();

         var cr = "C";
           var url = "getDoc?fano="+searchFano+"&cr="+cr;


     if (window.ActiveXObject)
    {
   // alert("jegan");
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
    //alert("jegan1");
        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function() {processRequest1(); } ;
    httpRequest.send(null); 

    }
 function processRequest1()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
       
        {

            var CrListXML = httpRequest.responseXML.getElementsByTagName("CrList")[0];

            updateHTML1(CrListXML);
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}
   
function updateHTML4(CrListXML)
{


   var len = window.document.DealAssistForm.complntNameTemp.options.length;

    while(len>0) {
        len = len -1;
        window.document.DealAssistForm.complntNameTemp.options[len] = null;
}//end while       
// alert(StateNamesXML.childNodes.length);

  window.document.loginform.complntNameTemp.options[0] = new Option("Select","0");
   document.loginform.complntName.value="";
   document.loginform.complntEmail.value="";
   document.loginform.complntFaxNo.value="";
  

return;
}



function updateHTML1(CrListXML)
{

   var len = window.document.loginform.complntNameTemp.options.length;

    while(len>0) {
        len = len -1;
        window.document.loginform.complntNameTemp.options[len] = null;
    }//end while       
// alert(StateNamesXML.childNodes.length);

window.document.loginform.complntNameTemp.options[0] = new Option("Select","0");

      for (loop = 0; loop < CrListXML.childNodes.length; loop++) {

       var SNS = CrListXML.childNodes[loop];
       var crId = SNS.getElementsByTagName("CrId")[0];
       var crn= SNS.getElementsByTagName("CrName")[0];

    eval(window.document.loginform.complntNameTemp).options[loop+1] = new Option(crn.childNodes[0].nodeValue,crId.childNodes[0].nodeValue);
    //window.document.DealAssistForm.fano.options[loop+1] = new Option(fanos,fanoId);

       }
   document.loginform.complntName.value="";
   document.loginform.complntEmail.value="";
   document.loginform.complntFaxNo.value="";
   document.loginform.complntAddress.value="";
  
   
}


//For Getting details of Complainant and Respondent
function getDoclistdetail()
    { //alert("kumud");
    //document.loginform.case_id_in.value=document.loginform.case_id_in_temp.value;
    var fano = document.loginform.case_id_in_temp.value;
    var crSeq=document.loginform.complntNameTemp.value;
            //searchFano = searchFano.toUpperCase();
//alert(crSeq);
if (crSeq=="0") {
alert("Please Select Doctor Name");
return;
}
         var cr = "C";
           var url = "getDocDetail?fano="+fano+"&crSeq="+crSeq+"&cr="+cr;


     if (window.ActiveXObject)
    {
   // alert("jegan");
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
    //alert("jegan1");
        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function() {processRequest2(); } ;
    httpRequest.send(null); 

    }
 function processRequest2()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
       
        {
//alert(httpRequest.responseText)
            var CrListXML = httpRequest.responseXML.getElementsByTagName("CrList")[0];

            updateHTML2(CrListXML);
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}
   

function updateHTML2(CrListXML)
{


       for (loop = 0; loop < CrListXML.childNodes.length; loop++) {

       var SNS = CrListXML.childNodes[loop];

       var crName = SNS.getElementsByTagName("CrName")[0];
               crName = crName.childNodes[0].nodeValue;

     
       var crMail = SNS.getElementsByTagName("CrMail")[0];
            crMail=crMail.childNodes[0].nodeValue;          
       var crFax = SNS.getElementsByTagName("CrFax")[0];
               crFax = crFax.childNodes[0].nodeValue;
           
      
                if (crName == "N/A") {
                        window.document.loginform.complntName.value = "";
                        } else {
                        window.document.loginform.complntName.value = crName;
                        }
       
                if (crMail=="N/A") {
                        window.document.loginform.complntEmail.value = "";
                        } else {
                        window.document.loginform.complntEmail.value = crMail;
                        }
                if (crFax=="N/A") {
                    window.document.loginform.complntFaxNo.value = "";
                } else {
                    window.document.loginform.complntFaxNo.value = crFax;
                }
               
               

       }
   
   
}       

</script>

</head>
<body>


<form name="loginform" method="post">

<table align="center">

<tr>
<td align="center">Enter Departement: <input type="text" name="attachToCaseNo"/><a href="javascript:getDepartment()"><b>Search</b></a> <br/>
                   Select Department:<select name="case_id_in_temp" onchange="getDoclist()">
                                    <option value="">select</option>
                                    </select> <br/>
                 Select Doctor: <select name="complntNameTemp" onchange="getDoclistdetail()">
                                 <option value="">select</option>
                                </select>
</td>                             

</tr>

<tr>
<td align="center">
Doctor Name :<input type="text" name="complntName" value=""/><br/>
Doctor Dep :<input type="text" name="complntFaxNo" value=""/><br/>
Doctor Email :<input type="text" name="complntEmail" value=""/><br/>

</td>


</tr>

</form>



</body>
</html>


Now we create a servlet for every call mention in Jsp page through using AJAX
getDep.java

package com.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class getDep
 */
public class getDep extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public getDep() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(
            HttpServletRequest requestObj,
            HttpServletResponse responseObj)
            throws IOException {
            //set the content type
            responseObj.setContentType("text/xml");

            responseObj.setHeader("Cache-Control", "no-cache");

            //get the PrintWriter object to write the html page
            PrintWriter writer = responseObj.getWriter();

            //get parameters store into the hashmap
            HashMap paramsMap = new HashMap();
            Enumeration paramEnum = requestObj.getParameterNames();
            while (paramEnum.hasMoreElements()) {
                String paramName = (String) (paramEnum.nextElement());
                paramsMap.put(paramName, requestObj.getParameter(paramName));
            }

            String fano = (String) paramsMap.get("fano");
            // for Daily Order, Court Hearing Modification, ,Cause Title, deal Assist , Notices search key
            String searchKey = (String) paramsMap.get("searchKey");
           
            String cond = "";

            ArrayList fanoDtoh = new ArrayList();
            ArrayList caseNos = new ArrayList();
            ArrayList dtoh = new ArrayList();
            ArrayList comboList = new ArrayList();
            Connection con = null;
            //ArrayList districtList=new ArrayList();
            try {
                DAO crDao = new DAO();

                caseNos = crDao.loadCaseListAjax(fano, searchKey);
//                if (caseNos.size()==0) {
//                    requestObj.setAttribute("CasesCombo",comboList);
//                }
            } catch (Exception e) {
                System.out.println(e);
            }

            Iterator it = caseNos.iterator();

            writer.println("<FanoList>");
            while (it.hasNext()) {

                org.apache.struts.util.LabelValueBean l = (org.apache.struts.util.LabelValueBean) it.next();
                String temp = l.getValue();
                writer.println("<FanoD>");

                writer.println("<FanoId>" + l.getValue() + "</FanoId>");
                //writer.println("<Fano>" + l.getLabel() + "</Fano>");
                writer.println("<Fano><![CDATA["+ l.getLabel()+"]]></Fano>");
                writer.println("</FanoD>");

            }
            //    writer.println("<Profile><![CDATA[" + "Jegan1" + "]]></Profile>");
            //close the write
            writer.println("</FanoList>");
            writer.close();
        }

}

getDocDetail.java
package com.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class getDocDetail
 */
public class getDocDetail extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public getDocDetail() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(
            HttpServletRequest requestObj,
            HttpServletResponse responseObj)
            throws IOException {
            //set the content type
            responseObj.setContentType("text/xml");

            responseObj.setHeader("Cache-Control", "no-cache");

            //get the PrintWriter object to write the html page
            PrintWriter writer = responseObj.getWriter();

            //get parameters store into the hashmap
            HashMap paramsMap = new HashMap();
            Enumeration paramEnum = requestObj.getParameterNames();
            while (paramEnum.hasMoreElements()) {
                String paramName = (String) (paramEnum.nextElement());
                paramsMap.put(paramName, requestObj.getParameter(paramName));
            }
            String fano = (String) paramsMap.get("fano");
            String crSeq = (String) paramsMap.get("crSeq");
            String cr = (String) paramsMap.get("cr");
            String cond = "";

            ArrayList fanoDtoh = new ArrayList();
            ArrayList caseNos = new ArrayList();
            ArrayList dtoh = new ArrayList();
           
            try {
            DAO daDao = new DAO();

            DocForm da=daDao.loadCaseListAjax2(fano, crSeq);
                   
                   
                String crname = da.getDocName();
                if (crname==null) {
                    crname="";
                }
               
               
               
                String crmail = da.getDocMail();
                if (crmail==null) {
                    crmail="";
                }
               
                String crfax = da.getDocFax();
                if (crfax==null) {
                    crfax="";
                }
               
  
                if (crname.equals("")) {
                    crname = "N/A";
                }
               
               
                if (crmail.equals("") ) {
                    crmail = "N/A";

                }
                if (crfax.equals("")) {
                    crfax = "N/A";
                }
               
               
                writer.println("<CrList>");
               
                writer.println("<CrDesc>");
               
                writer.println("<CrName><![CDATA[" + crname + "]]></CrName>");
               
               
                writer.println("<CrMail><![CDATA[" + crmail + "]]></CrMail>");
               
                writer.println("<CrFax><![CDATA[" + crfax + "]]></CrFax>");
               
               
                writer.println("</CrDesc>");
                writer.println("</CrList>");
                writer.close();
               
            } catch (Exception e) {
                System.out.println(e);
            }
                finally
                {
                   
                   
                }
             
        }
}


GetDoc.java
package com.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.util.LabelValueBean;

public class getDoc extends HttpServlet {

    protected void doGet(HttpServletRequest requestObj, HttpServletResponse responseObj)
       throws IOException
{
//set the content type
responseObj.setContentType("text/xml");
responseObj.setHeader("Cache-Control", "no-cache");
PrintWriter writer = responseObj.getWriter();
HashMap paramsMap = new HashMap();
Enumeration paramEnum = requestObj.getParameterNames();
while(paramEnum.hasMoreElements())
{
String paramName = (String)(paramEnum.nextElement());
paramsMap.put(paramName, requestObj.getParameter(paramName));
}

String fano= (String)paramsMap.get("fano");
String cr = (String)paramsMap.get("cr");
ArrayList dtoh = new ArrayList();


//ArrayList districtList=new ArrayList();
try
{
DAO   daDao = new DAO();               
dtoh = daDao.loadCaseListAjax1(fano,cr);
}
catch(Exception e)
{
System.out.println(e);
}

Iterator it =dtoh.iterator();

writer.println("<CrList>");
while(it.hasNext())
{
   
LabelValueBean l=(LabelValueBean)it.next();
String temp=l.getValue();
writer.println("<CrDesc>");

writer.println("<CrId>"+ l.getValue()+"</CrId>");
writer.println("<CrName><![CDATA["+ l.getLabel()+"]]></CrName>");
writer.println("</CrDesc>");


}
writer.println("</CrList>");
writer.close();                    
}        

}



LinkWithin

Related Posts Plugin for WordPress, Blogger...