Thursday, May 10, 2012

A complete JAXB Example


package com.jaxb;

import generated.Envelope;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBTest{

public static void main(String[] args) {
try {

InputStream stream = JAXBTest.class.getResourceAsStream("/test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Envelope.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Envelope envelope = (Envelope) jaxbUnmarshaller.unmarshal(stream);
 } catch (JAXBException e) {
e.printStackTrace();
 }
}
}

test.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Envelope version="01.00">
<Sender>
<Id>HRXMLEMPID</Id>
<Credential>25515</Credential>
</Sender>
<TimeStamp>4/11/2012 6:36:21 PM</TimeStamp>
<Manifest>HRB_PSID_CANDIDATE</Manifest>
<CANDIDATE>
<CANDIDATEID>12345</CANDIDATEID>
<!--Could be blank if there is no Req identifier sent from client -->
<REQUISITIONNUMBER/>
<BRREQNUMBER>123BR</BRREQNUMBER>
<JOBCODE>TestCode</JOBCODE>
<STATUS>Passed - Background Check</STATUS>
<FIRSTNAME>Rachel</FIRSTNAME>
<LASTNAME>Smith</LASTNAME>
<CONTACTMETHOD>Home</CONTACTMETHOD>
<!--Could be blank if there is no home phone no. for candidate. Format will be what end user has put in. -->
<HOMEPHONE>321/909-3003</HOMEPHONE>
<COUNTRY>United States</COUNTRY>
<!--Format will be what end user has put in. -->
<SSN>111-11-1111</SSN>
<!--1766 = HRB Seasonal Req Template; 1768 = HRB Corporate Req Template. Production values will be provided once the forms are created there.-->
<REQTEMPLATE>1766</REQTEMPLATE>
<!--Could be blank.-->
<PSIDCANDSTACKINGFIELD>12345</PSIDCANDSTACKINGFIELD>
</CANDIDATE>
</Envelope>

test.xsd

<?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <xsd:element name="Envelope" type="envelope"/>  
     <xsd:complexType name="envelope">
<xsd:sequence>
<xsd:element name="Sender" type="sender"/>
<xsd:element name="TimeStamp" type="xsd:string" />
<xsd:element name="Manifest" type="xsd:string" />
<xsd:element name="CANDIDATE" type="candidate"/>
</xsd:sequence>
<xsd:attribute name="version" type="xsd:string"/>
     </xsd:complexType>
     <xsd:complexType name="sender">
<xsd:sequence>
  <xsd:element name="Id" type="xsd:string" />
  <xsd:element name="Credential" type="xsd:string" />
  </xsd:sequence>
     </xsd:complexType>
 
     <xsd:complexType name="candidate">
<xsd:sequence>
<xsd:element name="CANDIDATEID" type="xsd:string" />
<xsd:element name="REQUISITIONNUMBER" type="xsd:string" />
<xsd:element name="BRREQNUMBER" type="xsd:string" />
<xsd:element name="JOBCODE" type="xsd:string" />
<xsd:element name="STATUS" type="xsd:string" />
<xsd:element name="FIRSTNAME" type="xsd:string" />
<xsd:element name="LASTNAME" type="xsd:string" />
<xsd:element name="CONTACTMETHOD" type="xsd:string" />
<xsd:element name="HOMEPHONE" type="xsd:string" />
<xsd:element name="COUNTRY" type="xsd:string" />
<xsd:element name="SSN" type="xsd:string" />
<xsd:element name="REQTEMPLATE" type="xsd:string" />
<xsd:element name="PSIDCANDSTACKINGFIELD" type="xsd:string" />
</xsd:sequence>
     </xsd:complexType>
    </xsd:schema> 

Use this command to generate java bean out from the xsd
C:\Program Files\Java\jdk1.6.0_27\bin>xjc C:/jaxb/test.xsd

We need to manually add @XmlRootElement(name = "Envelope") in the Envelope class. No change required in any other beans

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.05.09 at 03:12:02 PM CDT 
//


package generated;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for envelope complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="envelope">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="Sender" type="{}sender"/>
 *         &lt;element name="TimeStamp" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="Manifest" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="CANDIDATE" type="{}candidate"/>
 *       &lt;/sequence>
 *       &lt;attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlRootElement(name = "Envelope")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "envelope", propOrder = {
    "sender",
    "timeStamp",
    "manifest",
    "candidate"
})
public class Envelope {

    @XmlElement(name = "Sender", required = true)
    protected Sender sender;
    @XmlElement(name = "TimeStamp", required = true)
    protected String timeStamp;
    @XmlElement(name = "Manifest", required = true)
    protected String manifest;
    @XmlElement(name = "CANDIDATE", required = true)
    protected Candidate candidate;
    @XmlAttribute
    protected String version;

    /**
     * Gets the value of the sender property.
     * 
     * @return
     *     possible object is
     *     {@link Sender }
     *     
     */
    public Sender getSender() {
        return sender;
    }

    /**
     * Sets the value of the sender property.
     * 
     * @param value
     *     allowed object is
     *     {@link Sender }
     *     
     */
    public void setSender(Sender value) {
        this.sender = value;
    }

    /**
     * Gets the value of the timeStamp property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getTimeStamp() {
        return timeStamp;
    }

    /**
     * Sets the value of the timeStamp property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setTimeStamp(String value) {
        this.timeStamp = value;
    }

    /**
     * Gets the value of the manifest property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getManifest() {
        return manifest;
    }

    /**
     * Sets the value of the manifest property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setManifest(String value) {
        this.manifest = value;
    }

    /**
     * Gets the value of the candidate property.
     * 
     * @return
     *     possible object is
     *     {@link Candidate }
     *     
     */
    public Candidate getCANDIDATE() {
        return candidate;
    }

    /**
     * Sets the value of the candidate property.
     * 
     * @param value
     *     allowed object is
     *     {@link Candidate }
     *     
     */
    public void setCANDIDATE(Candidate value) {
        this.candidate = value;
    }

    /**
     * Gets the value of the version property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getVersion() {
        return version;
    }

    /**
     * Sets the value of the version property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setVersion(String value) {
        this.version = value;
    }

}




Friday, May 4, 2012

Database


Difference between UNIQUE constraint and PRIMARY key
1) By default Primary Key will generate Clustured Index
whereas Unique Key will Generate Non-Clustured Index.
2) Primary Key is a combination of Unique and NOT NULL Constraints so it can’t
have duplicate values or any NUll
Whereas for Oracle UNIQUE Key can have any number of NULL whereas for SQL
Server It can have only one NULL

A UNIQUE constraint is similar to PRIMARY key, but you can have more than one UNIQUE constraint per table.
When you declare a UNIQUE constraint, SQL Server creates a UNIQUE index to speed up the process of searching for duplicates. In this case the index defaults to NONCLUSTERED index, because you can have only one CLUSTERED index per table.
* The number of UNIQUE constraints per table is limited by the number of indexes on the table i.e 249 NONCLUSTERED index and one possible CLUSTERED index.
Contrary to PRIMARY key UNIQUE constraints can accept NULL but just once. If the constraint is defined in a combination of fields, then every field can accept NULL and can have some values on them, as long as the combination values is unique.
Difference Clustered and Nonclustered indexes
Clustered
·         Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
·         The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
Nonclustered
·         Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
·         The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
·         You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, 900 bytes and 16 key columns, and execute fully covered, indexed, queries. 


How to find duplicate records in a table
select name, count(name) as times from contacts group by name, phone having times>1;

Explain the difference between a hot backup and a cold backup and the benefits associated with each?


Cold Backup- We can take the Backup while DB(eg. Oracle) is down.
Hot Backup-We can take the Backup while DB(eg. Oracle) is running.

Cold backup is a physicalbackup. During a cold backupthe databaseis closed and not available to users. All files of the databaseare copied (image copy). The datafiles do not change during the copy so the databaseis in sync upon restore.
Used when:Service level allows for some down time for backup
Hot backup is a physical backup. In a hot backup the database remains open and available to users. All files of the database are copied (image copy). There may be changes to the database as the copy is made and so all log files of changes being made during the backupmust be saved too. Upon a restore, the changes in the log files are reapplied to bring the databasein sync. Used when:A full backupof a databaseis needed
Service level allows no down time for the backup


Difference between TRUNCATE, DELETE and DROP commands
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.
DELETE FROM emp WHERE name = 'CLERK';

TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
TRUNCATE TABLE emp;

The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
DROP TABLE emp;



Servlets and JSPs


What is the hierarchy, who calls the doXXX method?
public interface Servlet {
      void service();
      public void init();
      public void destroy();
}
abstract class GenericServlet implements Servlet
public void init(){}
public void destroy(){}
public abstract void service();
public abstract class HttpServlet extends GenericServlet{
     
protected void service(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {

if (method.equals(METHOD_HEAD)) {
                 long lastModified = getLastModified(req);
                 maybeSetLastModified(resp, lastModified);
                 doHead(req, resp);
     
             } else if (method.equals(METHOD_POST)) {
                 doPost(req, resp);
                 
             } else if (method.equals(METHOD_PUT)) {
                 doPut(req, resp);        
                 
             } else if (method.equals(METHOD_DELETE)) {
                 doDelete(req, resp);
                 
             } 
Can servlet have a constructor ?
One can definitely have constructor in servlet. Even you can use the constructor in servlet for initialization purpose, but this type of approach is not so common. You can perform common operations with the constructor as you normally do. The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do. In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.
NB: Constructor is called when the servlet object is created and using this obj init() and all doXXX methods will be called (so constructor first, then init)
What are the types of protocols supported by HttpServlet ?
It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

What's the difference between GenericServlet and HttpServlet?
GenericServlet
HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.
An abstract class that simplifies writing HTTP servlets.
It extends the GenericServlet base class and provides an framework
for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers.
The HttpServlet subclass passes generic service method requests
to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol.
HttpServlet only supports HTTP and HTTPS protocol.

Why is HttpServlet declared abstract?
The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.

Should I override service()
How do I call one servlet from another servlet?
[ Short answer: there are several ways to do this, including
  • use a RequestDispatcher
  • use a URLConnection or HTTPClient
  • send a redirect
  • call getServletContext().getServlet(name) (deprecated, doesn't work in 2.1+)

How does a servlet communicate with a JSP page?

try {
             govi.FormBean f = new govi.FormBean();
             String id = request.getParameter("id");
             f.setName(request.getParameter("name"));
             f.setAddr(request.getParameter("addr"));
             f.setAge(request.getParameter("age"));
                //use the id to compute 
                //additional bean properties like info 
               //maybe perform a db query, etc.
                // . . .
                f.setPersonalizationInfo(info);
             request.setAttribute("fBean",f);
             getServletConfig().getServletContext().getRequestDispatcher
                       ("/jsp/Bean1.jsp").forward(request, response);
           } catch (Exception ex) {
             . . .
           }

How to Enable Cross Context

It is possible to access variables/object created in one web apps in other webapps, if the <Context crossContext="true"> is set.

Tomcat
Add context.xml inside \webapps\TestWebApps\META-INF

JBoss
C:\Program Files\jboss-5.0.1.GA\server\default\deploy\jbossweb.sar\context.xml

In the source webapps, add the variable in ServletContext
servletContext.setAttribute("GVMap", globalVariablesMap);

In the destination webapps
Map globalVariablesMap = (Map<String, String>)filterConfig.getServletContext().getContext("/taxanswer-webapps").getAttribute("GVMap");