Thursday, 8 March 2012

JAVAEE5-JAXB solution examples2

The Java(TM) Web Services Tutorial at http://java.sun.com/webservices/docs/1.4/tutorial/doc/JAXBUsing.html has a few JAXB examples some of which still be made to work. These examples are similar to JAVAEE5-JAXB examples. I will provide the working solution for one of these examples which can also be used to make the other examples at JAVAEE5 tutorial’s examples section.

The main deficiency in these examples is; po.xml and po.xsd is provided instead of the primer.po package. You have to create this package with xjc from po.xml and po.xsd.

C:\Users\ars\Desktop\nbJAXB\modify-marshalARS>xjc po.xsd
parsing a schema...
compiling a schema...
generated\Items.java
generated\ObjectFactory.java
generated\PurchaseOrderType.java
generated\USAddress.java

C:\Users\ars\Desktop\nbJAXB\modify-marshalARS>This command creates a generated dir in the same location as po.xml. You can copy its content to the primer.po package. You may also use the parameters of the xjc command to do this directly.

The directory structure looks like this:




The NetBeans project directory looks like this:




createMarshall.java
package create.marshalars;

//1.The <JWSDP_HOME>/jaxb/samples/create-marshal/
//Main.java class declares imports for four standard Java classes plus three
//JAXB binding framework classes and the primer.po package:
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import primer.po.*;

public class CreateMarshal {

public static void main(String[] args) {
try {
// 1.A JAXBContext instance is created for handling classes generated in primer.po.
JAXBContext jc = JAXBContext.newInstance("primer.po");

//1.The ObjectFactory class is used to instantiate a new empty PurchaseOrder object.
// creating the ObjectFactory
ObjectFactory objFactory = new ObjectFactory();

// create an empty PurchaseOrder
PurchaseOrderType po = objFactory.createPurchaseOrderType();

//1.Per the constraints in the po.xsd schema, the PurchaseOrder object requires a value for the orderDate attribute. To satisfy this constraint, the orderDate is set using the standard Calendar.getInstance() method from java.util.Calendar.
po.setOrderDate(Calendar.getInstance());

//1.The ObjectFactory is used to instantiate new empty USAddress objects, and the required attributes are set.
USAddress shipTo = createUSAddress(objFactory, "Alice Smith",
"123 Maple Street",
"Cambridge",
"MA",
"12345");
po.setShipTo(shipTo);

USAddress billTo = createUSAddress(objFactory, "Robert Smith",
"8 Oak Avenue",
"Cambridge",
"MA",
"12345");
po.setBillTo(billTo);

//1.The ObjectFactory class is used to instantiate a new empty Items object.
Items items = objFactory.createItems();

//1.A get method is used to get a reference to the ItemType list.
List itemList = items.getItem();

//1.ItemType objects are created and added to the Items list.
itemList.add(createItemType(
objFactory,
"Nosferatu - Special Edition (1929)",
new BigInteger("5"),
new BigDecimal("19.99"),
null,
null,
"242-NO"));
itemList.add(createItemType(objFactory, "The Mummy (1959)",
new BigInteger("3"),
new BigDecimal("19.98"),
null,
null,
"242-MU"));
itemList.add(createItemType(objFactory,
"Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora",
new BigInteger("3"),
new BigDecimal("27.95"),
null,
null,
"242-GZ"));

//1.The items object now contains a list of ItemType objects and can be added to the po object.
po.setItems(items);

//1.A Marshaller instance is created, and the updated XML content is marshalled to system.out. The setProperty API is used to specify output encoding; in this case formatted (human readable) XML format.
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(po, System.out);
//1.Basic error handling is implemented.
} catch (JAXBException je) {
je.printStackTrace();
}
}
//1.An empty USAddress object is created and its properties set to comply with the schema constraints.
public static USAddress createUSAddress(
ObjectFactory objFactory,
String name,
String street,
String city,
String state,
String zip)
throws JAXBException {

// create an empty USAddress objects
USAddress address = objFactory.createUSAddress();

// set properties on it
address.setName(name);
address.setStreet(street);
address.setCity(city);
address.setState(state);
address.setZip(new BigDecimal(zip));

// return it
return address;
}

//1.Similar to the previous step, an empty ItemType object is created and its properties set to comply with the schema constraints.
public static Items.Item createItemType(ObjectFactory objFactory,
String productName,
BigInteger quantity,
BigDecimal price,
String comment,
Calendar shipDate,
String partNum)
throws JAXBException {

// create an empty ItemType object
Items.Item itemType =
objFactory.createItemsItem();

// set properties on it
itemType.setProductName(productName);
itemType.setQuantity(quantity);
itemType.setUSPrice(price);
itemType.setComment(comment);
itemType.setShipDate(shipDate);
itemType.setPartNum(partNum);

// return it
return itemType;
}
}

Primer.po/Items.java
//
// 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.03.06 at 05:03:34 PM EET
//


package primer.po;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
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.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;


/**
* <p>Java class for Items complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Items">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="item" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="productName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="quantity">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}positiveInteger">
* <maxExclusive value="100"/>
* </restriction>
* </simpleType>
* </element>
* <element name="USPrice" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* <element ref="{}comment" minOccurs="0"/>
* <element name="shipDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* </sequence>
* <attribute name="partNum" use="required" type="{}SKU" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Items", propOrder = {
"item"
})
public class Items {

@XmlElement(required = true)
protected List<Items.Item> item;

/**
* Gets the value of the item property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the item property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getItem().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Items.Item }
*
*
*/
public List<Items.Item> getItem() {
if (item == null) {
item = new ArrayList<Items.Item>();
}
return this.item;
}


/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="productName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="quantity">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}positiveInteger">
* <maxExclusive value="100"/>
* </restriction>
* </simpleType>
* </element>
* <element name="USPrice" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* <element ref="{}comment" minOccurs="0"/>
* <element name="shipDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* </sequence>
* <attribute name="partNum" use="required" type="{}SKU" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"productName",
"quantity",
"usPrice",
"comment",
"shipDate"
})
public static class Item {

@XmlElement(required = true)
protected String productName;
protected BigInteger quantity;
@XmlElement(name = "USPrice", required = true)
protected BigDecimal usPrice;
protected String comment;
@XmlSchemaType(name = "date")
protected Calendar shipDate;
@XmlAttribute(required = true)
protected String partNum;

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

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

/**
* Gets the value of the quantity property.
*
*/
public BigInteger getQuantity() {
return quantity;
}

/**
* Sets the value of the quantity property.
*
*/
public void setQuantity(BigInteger value) {
this.quantity = value;
}

/**
* Gets the value of the usPrice property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getUSPrice() {
return usPrice;
}

/**
* Sets the value of the usPrice property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setUSPrice(BigDecimal value) {
this.usPrice = value;
}

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

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

/**
* Gets the value of the shipDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public Calendar getShipDate() {
return shipDate;
}

/**
* Sets the value of the shipDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setShipDate(Calendar value) {
this.shipDate = value;
}

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

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

}

}

Primer.po/ObjectFactory.java
//
// 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.03.06 at 05:03:34 PM EET
//


package primer.po;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;


/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the generated package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {

private final static QName _PurchaseOrder_QNAME = new QName("", "purchaseOrder");
private final static QName _Comment_QNAME = new QName("", "comment");

/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated
*
*/
public ObjectFactory() {
}

/**
* Create an instance of {@link Items.Item }
*
*/
public Items.Item createItemsItem() {
return new Items.Item();
}

/**
* Create an instance of {@link PurchaseOrderType }
*
*/
public PurchaseOrderType createPurchaseOrderType() {
return new PurchaseOrderType();
}

/**
* Create an instance of {@link Items }
*
*/
public Items createItems() {
return new Items();
}

/**
* Create an instance of {@link USAddress }
*
*/
public USAddress createUSAddress() {
return new USAddress();
}

/**
* Create an instance of {@link JAXBElement }{@code <}{@link PurchaseOrderType }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "purchaseOrder")
public JAXBElement<PurchaseOrderType> createPurchaseOrder(PurchaseOrderType value) {
return new JAXBElement<PurchaseOrderType>(_PurchaseOrder_QNAME, PurchaseOrderType.class, null, value);
}

/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "comment")
public JAXBElement<String> createComment(String value) {
return new JAXBElement<String>(_Comment_QNAME, String.class, null, value);
}

}

Primer.po/PurchaseOrderType.java
//
// 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.03.06 at 05:03:34 PM EET
//


package primer.po;

import java.util.Calendar;
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.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;


/**
* <p>Java class for PurchaseOrderType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PurchaseOrderType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="shipTo" type="{}USAddress"/>
* <element name="billTo" type="{}USAddress"/>
* <element ref="{}comment" minOccurs="0"/>
* <element name="items" type="{}Items"/>
* </sequence>
* <attribute name="orderDate" type="{http://www.w3.org/2001/XMLSchema}date" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PurchaseOrderType", propOrder = {
"shipTo",
"billTo",
"comment",
"items"
})
public class PurchaseOrderType {

@XmlElement(required = true)
protected USAddress shipTo;
@XmlElement(required = true)
protected USAddress billTo;
protected String comment;
@XmlElement(required = true)
protected Items items;
@XmlAttribute
@XmlSchemaType(name = "date")
protected Calendar orderDate;

/**
* Gets the value of the shipTo property.
*
* @return
* possible object is
* {@link USAddress }
*
*/
public USAddress getShipTo() {
return shipTo;
}

/**
* Sets the value of the shipTo property.
*
* @param value
* allowed object is
* {@link USAddress }
*
*/
public void setShipTo(USAddress value) {
this.shipTo = value;
}

/**
* Gets the value of the billTo property.
*
* @return
* possible object is
* {@link USAddress }
*
*/
public USAddress getBillTo() {
return billTo;
}

/**
* Sets the value of the billTo property.
*
* @param value
* allowed object is
* {@link USAddress }
*
*/
public void setBillTo(USAddress value) {
this.billTo = value;
}

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

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

/**
* Gets the value of the items property.
*
* @return
* possible object is
* {@link Items }
*
*/
public Items getItems() {
return items;
}

/**
* Sets the value of the items property.
*
* @param value
* allowed object is
* {@link Items }
*
*/
public void setItems(Items value) {
this.items = value;
}

/**
* Gets the value of the orderDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public Calendar getOrderDate() {
return orderDate;
}

/**
* Sets the value of the orderDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setOrderDate(Calendar value) {
this.orderDate = value;
}

}

Primer.po/USAddress.java
//
// 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.03.06 at 05:03:34 PM EET
//


package primer.po;

import java.math.BigDecimal;
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.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;


/**
* <p>Java class for USAddress complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="USAddress">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="street" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="city" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="state" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="zip" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* </sequence>
* <attribute name="country" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" fixed="US" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "USAddress", propOrder = {
"name",
"street",
"city",
"state",
"zip"
})
public class USAddress {

@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String street;
@XmlElement(required = true)
protected String city;
@XmlElement(required = true)
protected String state;
@XmlElement(required = true)
protected BigDecimal zip;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String country;

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

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

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

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

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

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

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

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

/**
* Gets the value of the zip property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getZip() {
return zip;
}

/**
* Sets the value of the zip property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setZip(BigDecimal value) {
this.zip = value;
}

/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCountry() {
if (country == null) {
return "US";
} else {
return country;
}
}

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

}

Once you create the primer.po package using the xjc command you can use the primer.po in almost all the JAXB examples of JAVAEE5. One problem you may encounter though it may require a root element annotation.

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PurchaseOrderType", propOrder = {
"shipTo",
"billTo",
"comment",
"items"
})
public class PurchaseOrderType {

A better example is given by JAVAEE5 in the j2s-xml-rootElement example:
@XmlRootElement(name = "purchaseOrder")
@XmlType(name = "PurchaseOrderType")
public class PurchaseOrderType {
public CreditCardVendor creditCardVendor;
public USAddress billTo;
public USAddress shipTo;

Do not forget to add:
import javax.xml.bind.annotation.XmlRootElement;

Please feel free to contact me for the working copies of the other examples by e-mail at arsaral(at) yahoo.com

Kind regards.

Ali R+ SARAL
Note. My response will be free of charge and within the same day.

JAVAEE5-JAXB examples solution example1

The JAVAEE5 tutorial at http://docs.oracle.com/javaee/5/tutorial/doc/index.html has dedicated a directory for JAXB examples. Most of the examples provided here work OK after a while of effort spent.

This blog entry will solve the worst example among these JAXB examples and provide a sample approach to solve the other simpler ones. Although the example belongs to the owners of the URL sited above the solution which makes it work belongs to me. I happily provide every detail of my solution here to the possibly interested people.

You can also contact me the working solutions of the other examples which I may consequently send you by e-mail(arsaral(at)yahoo.com).


J2s-create-marshall example of JAVAEE5 tutorial



Main.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import cardfile.BusinessCard;
import cardfile.Address;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.util.ValidationEventCollector;
import javax.xml.bind.ValidationEventLocator;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import org.xml.sax.SAXException;


public class Main {
public static void main(String[] args) throws Exception {
final File f = new File("src/bcard.xml");

// Illustrate two methods to create JAXBContext for j2s binding.
// (1) by root classes newInstance(Class ...)
JAXBContext context1 = JAXBContext.newInstance(BusinessCard.class);

// (2) by package, requires jaxb.index file in package cardfile.
// newInstance(String packageNames)
JAXBContext context2 = JAXBContext.newInstance("cardfile");

Marshaller m = context1.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(
getCard(),
System.out);

// illustrate optional unmarshal validation.
Marshaller m2 = context1.createMarshaller();
m2.marshal(
getCard(),
new FileOutputStream(f));

Unmarshaller um = context2.createUnmarshaller();
um.setSchema(getSchema("cardfile/schema1.xsd"));

Object bce = um.unmarshal(f);
m.marshal(bce, System.out);
}

/** returns a JAXP 1.3 schema by parsing the specified resource. */
static Schema getSchema(String schemaResourceName)
throws SAXException {
SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

try {
URL schemaURL = Main.class.getResource(schemaResourceName);

return sf.newSchema(schemaURL);
} catch (SAXException se) {
// this can only happen if there's a deployment error and the resource is missing.
throw se;
}
}

private static BusinessCard getCard() {
return new BusinessCard(
"John Doe",
"Sr. Widget Designer",
"Acme, Inc.",
new Address(
null,
"123 Widget Way",
"Anytown",
"MA",
(short) 12345),
"123.456.7890",
null,
"123.456.7891",
"John.Doe@Acme.ORG");
}
}

Bcard.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <businessCard>
- <address>
<city>Anytown</city>
<state>MA</state>
<street>123 Widget Way</street>
<zip>12345</zip>
</address>
<company>Acme, Inc.</company>
<email>John.Doe@Acme.ORG</email>
<fax>123.456.7891</fax>
<name>John Doe</name>
<phone>123.456.7890</phone>
<title>Sr. Widget Designer</title>
</businessCard>

Cardfile/address.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


package cardfile;

import javax.xml.bind.annotation.*;


@XmlType
public class Address {
private String city;
private String name;
private String state;
private String street;
private short zip;

public Address() {
}

public Address(
String name,
String street,
String city,
String state,
short zip) {
this.name = name;
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public short getZip() {
return zip;
}

public void setZip(short zip) {
this.zip = zip;
}

public String toString() {
StringBuilder s = new StringBuilder();

if (name != null) {
s.append(name)
.append('\n');
}

s.append(street)
.append('\n')
.append(city)
.append(", ")
.append(state)
.append(" ")
.append(zip);

return s.toString();
}
}


Cardfile/BusinessCard.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


package cardfile;

import javax.xml.bind.annotation.*;


@XmlRootElement
public class BusinessCard {
private Address address;
private String cellPhone;
private String company;
private String email;
private String fax;
private String name;
private String phone;
private String title;

public BusinessCard() {
}

public BusinessCard(
String name,
String title,
String company,
Address address,
String phone,
String cellPhone,
String fax,
String email) {
this.name = name;
this.title = title;
this.company = company;
this.address = address;
this.phone = phone;
this.cellPhone = cellPhone;
this.fax = fax;
this.email = email;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getCompany() {
return company;
}

public void setCompany(String company) {
this.company = company;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getFax() {
return fax;
}

public void setFax(String fax) {
this.fax = fax;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getCellPhone() {
return cellPhone;
}

public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}

public String toString() {
StringBuilder s = new StringBuilder();

if (name != null) {
s.append(name)
.append('\n');
}

if (title != null) {
s.append(title)
.append('\n');
}

if (company != null) {
s.append(company)
.append('\n');
}

if (address != null) {
s.append(address.toString())
.append('\n');
}

if (phone != null) {
s.append("phone: ")
.append(phone)
.append('\n');
}

if (cellPhone != null) {
s.append("cell: ")
.append(cellPhone)
.append('\n');
}

if (fax != null) {
s.append("fax: ")
.append(fax)
.append('\n');
}

if (email != null) {
s.append(email)
.append('\n');
}

return s.toString();
}
}

Cardfile/ObjectFactory.java
//
// 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.03.06 at 08:51:41 PM EET
//


package cardfile;

import javax.xml.bind.annotation.XmlRegistry;


/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the generated package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {


/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated
*
*/
public ObjectFactory() {
}

/**
* Create an instance of {@link Contact }
*
*/
public Address createAddress() {
return new Address();
}

/**
* Create an instance of {@link AddressBook }
*
*/
public BusinessCard createBusinessCard() {
return new BusinessCard();
}

}

Cardfile/jaxb.index
BusinessCard
Address

Cardfile/package-info.java
/*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/


package cardfile;

import javax.xml.bind.annotation.XmlAccessorType;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;

cardfile/schema1.xsd
<?xml version="1.0"?>

<!--
Copyright 2011 ali R+ SARAL
Please use this freely making sure that you indicate my name.
-->

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">


<xs:element name="businessCard">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="Address"/>
<!--xs:element name="cellPhone" type="xs:string" /-->
<xs:element name="company" type="xs:string" />
<xs:element name="email" type="xs:string" />
<xs:element name="fax" type="xs:string" />
<xs:element name="name" type="xs:string" />
<xs:element name="phone" type="xs:string" />
<xs:element name="title" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name="Address">
<xs:sequence>
<!--xs:element name="name" type="xs:string"/-->
<xs:element name="city" type="xs:string"/>
<xs:element name="state" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="zip" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

The solutions for the other JAVAEE5 – JAXB examples are available from
Arsaral(at)yahoo.com.

Kind regards.

Ali R+ SARAL

Monday, 5 December 2011

Eclipse Glassfish EE example

Hi, this is a simple ear application that demonstrates how to use eclipse with glassfish to build enterprise applications (J2EE). It combines the standard hello example of J2EE examples from NetBeans with the calculator example of web services example of NetBeans again. There is a simple trick in the web.xml of the war file to run the two examples seperately from the IE command line.


1.1 Create an Enterprise Application (name=ServletStatelessARSEAR)
1.2 Say OK to create an ejbClient (name = ServletStatelessARS-ejbClient)
1.3 Leave the rest as it is, you will add the EJB and war projects later on.
As seen in the picture.



2.1 Create under ejbModule an interface file at the ServletStatelessARS-ejbClient client application (loc/name=enterpriseARS.servlet_stateless_ejbClient/StatelessSessionARS.java)

package enterpriseARS.servlet_stateless_ejbClient;

public interface StatelessSessionARS {

public String sayHelloARS(String name);
public int add2Parms(int parm1, int parm2);

}





2.2 Create an EJB application (name=ServletStatelessARS-ejb) and attach it to the Enterprise application using the related creation option.
2.3 Create under ejbModule (loc/name=enterpriseARS.servlet_stateless_ejb/StatelessSessionARSBean.java)
package enterpriseARS.servlet_stateless_ejb;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jws.WebService;

import enterpriseARS.servlet_stateless_ejbClient.StatelessSessionARS;

@WebService (only for diagnostic purposes, to be used for Glassfish endpoint testing)
@Stateless
public class StatelessSessionARSBean
implements StatelessSessionARS {

public String sayHelloARS(String name) {
return "HelloARS, " + name + "!\n";
}

public int add2Parms(int parm1, int parm2){
return(parm1+parm2);
}

}
3.1 Create a dynamic web application (name=ServletStatelessARS-war) and attach it to the Enterprise application using the related creation option.





3.2 Web/index.jsp should be:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>GlassFish JSP Page</title>
</head>
<body>
<h1>Calculator Service</h1>
<form name="Submit" action="Servlet2ParmsAddARS">
<input type="text" name="value1" value="2" size="3"/>+
<input type="text" name="value2" value="2" size="3"/>=
<input type="submit" value="Get Result" name="getResult" />
</form>
</body>

</html>
3.3 Web.xml should be:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>ServletStatelessARS</display-name>
<distributable/>
<servlet>
<servlet-name>Servlet2StatelessARS</servlet-name>
<servlet-class>enterpriseARS.servlet_stateless_war.Servlet2StatelessARS</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2StatelessARS</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2ParmsAddARS</servlet-name>
<servlet-class>enterpriseARS.servlet_stateless_war.Servlet2ParmsAddARS</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2ParmsAddARS</servlet-name>
<url-pattern>/Servlet2ParmsAddARS</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
index.jsp
servlet
</welcome-file>
</welcome-file-list>
</web-app>

3.4 In the Java Resources/src/enterpriseARS.servlet_stateless_war package,
Create Servlet2ParmsAddARS.java

package enterpriseARS.servlet_stateless_war;
import java.io.*;

import javax.ejb.EJB;

import javax.servlet.*;
import javax.servlet.http.*;

import javax.naming.*;

import enterpriseARS.servlet_stateless_ejbClient.*;

// Though it is perfectly fine to declare the dependency on the bean
// at the type level, it is not required for stateless session bean
// Hence the next two lines are commented and we rely on the
// container to inject the bean.
// @EJB(name="StatelessSession", beanInterface=StatelessSession.class)

public class Servlet2ParmsAddARS
extends HttpServlet {

// Using injection for Stateless session bean is still thread-safe since
// the ejb container will route every request to different
// bean instances. However, for Stateful session beans the
// dependency on the bean must be declared at the type level

@EJB
private StatelessSessionARS sless;

public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

resp.setContentType("text/html");
PrintWriter out = resp.getWriter();

try {

out.println("<h2>Servlet ClientServlet at " + req.getContextPath () + "</h2>");

int i = Integer.parseInt(req.getParameter("value1"));
int j = Integer.parseInt(req.getParameter("value2"));

int result = sless.add2Parms(i,j);

out.println("<br/>");
out.println("Result:");
out.println("" + i + " + " + j + " = " + result);

} catch (Exception ex) {
ex.printStackTrace();
System.out.println("webclient servlet test failed");
throw new ServletException(ex);
}
}

}
3.5 create Servlet2StatelessARS.java at the same package location.

package enterpriseARS.servlet_stateless_war;

import java.io.*;

import javax.ejb.EJB;

import javax.servlet.*;
import javax.servlet.http.*;

import javax.naming.*;

import enterpriseARS.servlet_stateless_ejbClient.*;
public class Servlet2StatelessARS
extends HttpServlet {
@EJB
private StatelessSessionARS sless;

public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

resp.setContentType("text/html");
PrintWriter out = resp.getWriter();

try {

out.println("<HTML> <HEAD> <TITLE> Servlet Output </TITLE> </HEAD> <BODY BGCOLOR=white>");
out.println("<CENTER> <FONT size=+1> Servlet2Stateless:: Please enter your name </FONT> </CENTER> <p> ");
out.println("<form method=\"POST\">");
out.println("<TABLE>");
out.println("<tr><td>Name: </td>");
out.println("<td><input type=\"text\" name=\"name\"> </td>");
out.println("</tr><tr><td></td>");
out.println("<td><input type=\"submit\" name=\"sub\"> </td>");
out.println("</tr>");
out.println("</TABLE>");
out.println("</form>");
String val = req.getParameter("name");

if ((val != null) && (val.trim().length() > 0)) {
out
.println("<FONT size=+1 color=red> Greeting from StatelessSessionBean: </FONT> "
+ sless.sayHelloARS(val) + "<br>");
}
out.println("</BODY> </HTML> ");

} catch (Exception ex) {
ex.printStackTrace();
System.out.println("webclient servlet test failed");
throw new ServletException(ex);
}
}

}

4.1 It will give IDE and compile error for the EJB because currently the dynamic web application does not see the EJB application.
4.2 Right click on the dynamic web application and check that Project references indicates ejb and ejbClient applications as referred.
4.3 Go to the Java Build Path and click on the Projects tab. Add the ejb and ejbClient applications.
4.4 The IDE – compile error for the EJB disappears.
5. You may also check yhe ear application for the same items but they are done automatically for it.
6. Make sure you test the application in an orderly manner. Build the EAR application and also build the others if necessary. When you run the war application the calculator works as default. If you run
http://localhost:8080/ServletStatelessARS-war/servlet then the hello message works.








7. If you experience any problems export the ear application to a war file at the
C:\Program Files\glassfish-3.1\glassfish\domains\domain1\autodeploy
Autodeploy directory of Glassfish. Then restart Glassfish, everything will be OK.


It is free of charge to request a copy of the source files. I am sometimes hecticly busy but I promise to respond in a couple of hours.

Cheers.

Ali R+ SARAL








Sunday, 4 December 2011

Referring to another project using Eclipse

There are two seperate projects. Main project calls a method in the ReferredProject.


ReferredProject has
referredProjectPackage/ReferenceClass.java
package referredProjectPackage;

public class ReferenceClass {
public void sayHello(){
System.out.println("Hello from the reference class.");
}
}
MainProject has
mainPackage/MainClass.java
package mainPackage;
import referredProjectPackage.*;

public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("MainClass works.");
ReferenceClass rc = new ReferenceClass();
rc.sayHello();
}

}
It gives error:



Right Click on the MainProject in the PackageExplorer. Select properties at the bottom. Properties for the MainProject window opens. Select JAVA build path and then select the Projects tab.



Select ReferredProject and then click OK. The errors disappear and the program works.
But to be on the safe side, do not forget to do also:
Right click on the MainProject, select Project References, select ReferredProject and click OK.




Saturday, 3 December 2011

How to use Eclipse with GlassFish server(2)

13- Right Click on the application name and slide to the bottom and select ‘properties’ for our web app TestEclipseGlassFishARS.

14- Select libraries and observe the source of the problem.




15- Select JRE System Library and click the edit button on the right.






16- Click the Add button the Installed JREs window.





17- Select Standard VM on the JRE type window.




18- The JRE Definition window opens. Select JRE Home using the directory button and go to the JDK 1.6 installation directory.




19- Your choice fills in all the necessary fields on the JRE Definition window. Click the finish button.



20- Installed JRE’s window appears again with the newly added JDK 1.6 directory.



21- Select JDK 1.6 and return back to the JRE System Library window which also has the new addition as seen in the picture. Select JDK 1.6 as Alternate JRE and then click Finish.




22- JRE System Library is now changed to JDK 1.6 as required by GlassFish.




23- Try once more to run the test web app. It works. Don’t g’ve up! You will make it.



Cheers.

Ali R+ SARAL

Note: I know that the picture quality may not prove to be good. If you like you may obtain a Word format of this tutorial for free from arsaral(at)yahoo.com. Sometimes I may be hecticly busy but I promise a response with in a couple of hours.






How to use Eclipse with GlassFish server (1)


I am going to explain how to use Eclipse with Glassfish as a server. This tutorial uses a very simple, picture based approach. So trust me and take my advises you will make it to the end for sure.
1- Create a dynamic web project:
Open eclipse, file, new, [web], dynamic web project









2- Create a new server
Go to bottom right frame, select servers, right click in the frame content area, server, new






3- If GlassFish connection has been made for your Eclipse installation previously you will get this picture. But in your case, GlassFish will not appear.



4- Click ‘Download additional web servers’. It will open ‘ install new extension’ window and begin searching the internet. This will take a long time.



5- Be patient and wait till the end when finally it finds GlassFish and Jboss.






6- Select GlassFish and see that the previous window has the GlassFish items now.






7- Select GlassFish 3.1 and a new screen taht asks for the location of Glassfish on your computer opens. It also calls for your choice of jre.


8- Then you are asked for the admin directory and the admin password which happens to be adminadmin









9- Now it is time to try the very simple dynamic web program that we have created.




Do not forget to put index.jsp as a welcome file in the web.xml.
Index.jsp is on the picture.





10. Run the webapp on the new server.





11- Select Glassfish






12- ERROR: Glassfish requires JDK 1.6 and not a JRE.






You can request a better printed World version of this tutorial from arsaral(at)yahoo.com

The pictures are much better and scripts can be easily read in that version.






































Sunday, 25 September 2011

Struts2 Hibernate Spring Tutorial

Struts - Hibernate - Spring Application

This is a tutorial that explains how Struts2 , Hibernate and Spring(IoC) is mixed together and used in the same application.

I based my work on the examples given in Vaan Nila Struts2 tutorial. Vaan Nila gives the Struts2Example14 for Struts2 - Spring and Struts2Example17 for Struts2 - Hibernate.

My trick is: I took the Struts2Example17 project and added it the lib/jars of the Struts2Example14. Then I changed the struts.xml from:

/register.jsp

to: (my StrutsHibernateSpring application)

/register.jsp


Similar Struts2Example14 's WEB-INF/applicationContext.xml:





I did WEB-INF/applicationContext.xml in StrutsHibernateSpring:





I also added the Spring listener to the web.xml in StrutsHibernateSpring :

org.springframework.web.context.ContextLoaderListener

which is similar to the Struts2Example14 web.xml.

It worked.

Here is the code:


struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">




listUser



/register.jsp





hibernate.config.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


org.hsqldb.jdbcDriver
jdbc:hsqldb:hsql://localhost
sa

1
org.hibernate.dialect.HSQLDialect
true
create





com.vaannila.dao
UserDAO.java
package com.vaannila.dao;

import java.util.List;
import com.vaannila.domain.User;

public interface UserDAO {

public void saveUser(User user);
public List listUser();
}

UserDAOImpl.java
package com.vaannila.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.vaannila.domain.User;

public class UserDAOImpl implements UserDAO {

@SessionTarget
Session session;
@TransactionTarget
Transaction transaction;

@SuppressWarnings("unchecked")
@Override
public List listUser() {
List courses = null;
try {
courses = session.createQuery("from User").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}

@Override
public void saveUser(User user) {
try {
session.save(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}

}

com.vaannila.domain
User.java
package com.vaannila.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER")
public class User {

private Long id;
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private Boolean mailingList;

@Id
@GeneratedValue
@Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

@Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Column(name="USER_PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

@Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}

@Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

@Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}

@Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}

}

WebContent
WEB-INF
lib
application-Context.xml







web.xml


StrutsHibernateSpringARS

struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter



org.springframework.web.context.ContextLoaderListener


struts2
/*



index.jsp



WebContent
hs.bat
set classpath=.\WEB-INF\lib\hsqldb.jar;%classpath%
java org.hsqldb.Server
hs2.bat
java -cp ./WEB-INF/lib/hsqldb.jar org.hsqldb.util.DatabaseManager




I went one step further and I did a DAO dependency injection in my application StrHibSprARS2.
applicationContext.xml in src together with hibernate.cfg.xml and struts.xml









(It would be wiser to change the name of the applicationContext.xml to beans.xml.)
UserAction.java would change to:
...
//private UserDAO userDAO = new UserDAOImpl();

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
private UserDAO userDAO = (UserDAOImpl) factory.getBean("userDAOImplClass");
...
(again the name applicationContext.xml gets mixed with the real one in the WEB-INF. I tried
successfully to clean up the unnecessary entries in these two applicationContext files, namely
I deleted id="userActionClass" item from the src beans.xml and vise versa. No problem.)

Tuesday, 13 September 2011

Some notes about VaanNila's Hibernate Tutorial Examples

This note explains how to run the hibernate examples given
in VaanNila's Hibernate Tutorial.
http://www.vaannila.com/hibernate/hibernate-tutorial/hibernate-tutorial.html

ERRORS MESSAGES AND THE SOLUTIONS:


Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.vaannila.util.HibernateUtil.(HibernateUtil.java:14)


add commons-logging-1.1.1
------------------------------------
12.Eyl.2011 20:08:36 org.hibernate.cfg.Environment
INFO: Hibernate 3.2.5
12.Eyl.2011 20:08:36 org.hibernate.cfg.Environment
INFO: hibernate.properties not found
12.Eyl.2011 20:08:36 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib

...
INFO: building session factory
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.vaannila.util.HibernateUtil.(HibernateUtil.java:14)

cglib problem
add cglib.jar
-------------------------------
12.Eyl.2011 20:10:55 org.hibernate.impl.SessionFactoryImpl
INFO: building session factory
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/objectweb/asm/Type

cglib needs asm.jar
-------------------------------


INFO: exporting generated schema to database
12.Eyl.2011 20:12:25 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: schema export complete
Hibernate: insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)
Hibernate: call identity()
Hibernate: insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)
Hibernate: call identity()
Hibernate: insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)
Hibernate: call identity()
Hibernate: select course0_.COURSE_ID as COURSE1_0_, course0_.COURSE_NAME as COURSE2_0_ from COURSES course0_
Physics
Chemistry
Maths
Hibernate: select course0_.COURSE_ID as COURSE1_0_0_, course0_.COURSE_NAME as COURSE2_0_0_ from COURSES course0_ where course0_.COURSE_ID=?
Hibernate: update COURSES set COURSE_NAME=? where COURSE_ID=?
Hibernate: select course0_.COURSE_ID as COURSE1_0_0_, course0_.COURSE_NAME as COURSE2_0_0_ from COURSES course0_ where course0_.COURSE_ID=?
Hibernate: delete from COURSES where COURSE_ID=?
Hibernate: select course0_.COURSE_ID as COURSE1_0_, course0_.COURSE_NAME as COURSE2_0_ from COURSES course0_
Physics
Mathematics

It works...
-----------
Directory of C:\Users\ars\Desktop\VN_Hibernate\HibernateExample1\lib

antlr-2.7.6.jar
asm.jar
cglib-2.2.jar
commons-collections-3.2.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-annotations
hibernate-commons-annotations
hsqldb.jar
javassist-3.4.GA.jar
jta-1.1.jar
slf4j-api-1.6.2.jar
slf4j-simple-1.6.2.jar

Friday, 9 September 2011

Some notes about VaanNila's Spring Hibernate Integration Tutorial

Some notes about Vaanilla's Spring Hibernate Integration Tutorial
http://www.vaannila.com/spring/spring-hibernate-integration-1.html

SpringExample17 indicates the below list as necessary dependecies.

01.antlr-2.7.6
02.antlr-runtime-3.0
03.commons-collections-3.1
04.commons-dbcp
05.commons-logging-1.0.4
06.commons-pool
07.dom4j-1.6.1
08.ejb3-persistence
09.hibernate3
10.hibernate-annotations
11.hibernate-commons-annotations
12.hsqldb
13.javassist-3.4.GA
14.jstl
15.jta-1.1
16.org.springframework.asm-3.0.0.M3
17.org.springframework.beans-3.0.0.M3
18.org.springframework.context-3.0.0.M3
19.org.springframework.context.support-3.0.0.M3
20.org.springframework.core-3.0.0.M3
21.org.springframework.expression-3.0.0.M3
22.org.springframework.jdbc-3.0.0.M3
23.org.springframework.orm-3.0.0.M3
24.org.springframework.transaction-3.0.0.M3
25.org.springframework.web-3.0.0.M3
26.org.springframework.web.servlet-3.0.0.M3
27.slf4j-api-1.5.6
28.slf4j-simple-1.5.6
29.standard

I used the below list of dependecies:
Directory of C:\Users\ars\Desktop\Str_Hib_Spr\SpringExample17\WebContent\WEB-INF\lib

antlr-2.7.6.jar
antlr-runtime-3.0.jar
asm.jar
cglib-2.2.jar
commons-collections.jar
commons-dbcp.jar
commons-logging.jar
commons-pool.jar
dom4j-1.6.1.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate3.jar
hsqldb.jar
javassist-3.4.GA.jar
javax.persistence.jar
javax.servlet_2.4.0.v200706111738.jar
jstl.jar
jta-1.1.jar
org.springframework.asm-3.1.0.M2.jar
org.springframework.beans-3.1.0.M2.jar
org.springframework.context-3.1.0.M2.jar
org.springframework.context.support-3.1.0.M2.jar
org.springframework.core-3.1.0.M2.jar
org.springframework.expression-3.1.0.M2.jar
org.springframework.jdbc-3.1.0.M2.jar
org.springframework.orm-3.1.0.M2.jar
org.springframework.transaction-3.1.0.M2.jar
org.springframework.web-3.1.0.M2.jar
org.springframework.web.servlet-3.1.0.M2.jar
slf4j-api-1.6.2.jar
slf4j-simple-1.6.2.jar
standard.jar

I had to add asm.jar and cglib-2.2.jar because of the problems listed below.


exception

org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is org.springframework.jdbc.UncategorizedSQLException: Hibernate operation:
Cannot open connection; uncategorized SQLException for SQL [???]; SQL state [null]; error code [0];
Cannot create PoolableConnectionFactory (socket creation error);
nested exception is org.apache.commons.dbcp.SQLNestedException:
Cannot create PoolableConnectionFactory (socket creation error)

root cause

org.springframework.jdbc.UncategorizedSQLException: Hibernate operation:
Cannot open connection; uncategorized SQLException for SQL [???];
SQL state [null]; error code [0];
Cannot create PoolableConnectionFactory (socket creation error);
nested exception is org.apache.commons.dbcp.SQLNestedException:
Cannot create PoolableConnectionFactory (socket creation error)

SOLUTION:
Vaanilla assumes that you know how to run HSQLDB :-)
add hs.bat :
set classpath=.\web-inf\lib\hsqldb.jar;%classpath%
java org.hsqldb.Server

OUTPUT:
C:\Users\ars\Desktop\Str_Hib_Spr\SpringExample17\WebContent>set classpath=.\web-
inf\lib\hsqldb.jar;

C:\Users\ars\Desktop\Str_Hib_Spr\SpringExample17\WebContent>java org.hsqldb.Serv
er
[Server@6ac2a132]: [Thread[main,5,main]]: checkRunning(false) entered
[Server@6ac2a132]: [Thread[main,5,main]]: checkRunning(false) exited
[Server@6ac2a132]: Startup sequence initiated from main() method
[Server@6ac2a132]: Loaded properties from [C:\Users\ars\Desktop\Str_Hib_Spr\Spri
ngExample17\WebContent\server.properties]
[Server@6ac2a132]: Initiating startup sequence...
[Server@6ac2a132]: Server socket opened successfully in 358 ms.
[Server@6ac2a132]: Database [index=0, id=0, db=file:test, alias=] opened sucessf
ully in 156 ms.
[Server@6ac2a132]: Startup sequence completed in 514 ms.
[Server@6ac2a132]: 2011-09-09 20:21:26.494 HSQLDB server 1.8.0 is online
[Server@6ac2a132]: To close normally, connect and execute SHUTDOWN SQL
[Server@6ac2a132]: From command line, use [Ctrl]+[C] to abort abruptly
----------------

exception
...
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mySessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]:
Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError:
net/sf/cglib/proxy/CallbackFilter
...
SEVERE: Servlet /SpringExample17 threw load() exception
java.lang.ClassNotFoundException: net.sf.cglib.proxy.CallbackFilter

SOLUTION:
add cglib.jar
--------------------

exception

root cause

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mySessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]:
Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError:
Could not initialize class net.sf.cglib.proxy.Enhancer

SOLUTION:
cglib depends on asm.jar:

add asm.jar
---------------------------


If there are any problems related to antlr add:
antlr-2.7.5H3

If there are still any more problems:
arsaral [at] yahoo [dot] com

Cheers.

Ali R+