Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

09 March 2011

Query2XML, my latest projects on google code :)

Query2xml is a java tool to convert from the Result set of a SQL query to a simple XML output... find it here..
BTW, it is the first time to use byte code manipulation frameworks ....

12 February 2011

Cross-site referencing in GWT

Al salamo Alykom,

basic steps to do cross-site referencing:

1- add
<add-linker name="xs" /> 
to your .gwt.xml file
2- replace all GWT-RPC by JsonpRequestBuilder

JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
requestBuilder.setCallbackParam("callback");
requestBuilder.requestObject("http://mydomain/servlet?key=value&key=value", new AsyncCallback<JsArray<com.me.json_objects.Employee>>()
{
    public void onFailure(Throwable caught)
    {
    }
    
    public void onSuccess(com.me.json_objects.Employee result)
    {
        com.me.java_objects.Employee  emp = JsonConverterUtil.convertObjct(result);
    }
});


2.a- find a lib that convert java objects returned from business layer (in servlets) to JSON objects (http://jackson.codehaus.org/ is a great, simple to use)
Very simple really:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
String value = mapper.writeValueAsString( object);


2.b- Convert json objects to java objects in GWT using JavaScript Overlay Types so every JSON object coming from server will be represented using using a JavaScript Overlay class, and this object at first has a java object that accessed by your GWT code. so you will have to map JSON objects returned from JsonpRequestBuilder to reqular Java objects to use in your GWT code.

Sample json object:
package com.me.json_objects;

public class Employee
{
    protected Employee(){}
    
    public final String native getName() /*-{
        return this.name;
    }-*/;

    public final String native getLocation() /*-{
        return this.location;
    }-*/;
}

That maps to this java object:
package com.me.java_objects;

public class Employee
{

    private String name;
    private String location;
    
    public Employee(){}
    
    public void setName(String name)
    {
        this.name = name;
    }
    public String  getName() {
        return this.name;
    }

    public String getLocation(){
        return this.location;
    }
    
    public void setLocation(String loc)
    {
        this.location = loc;
    }
}

to test your code, fire up your server (say tomcat) on two different http ports, one for deploying the client appand the other to deploy the GWT application.. and try to import the gwt application into the client, .. it should work.

Two ports here because cross-site in most browsers are for app running in different hosts and/or ports.

I wish if I could provide code sample soon :)

good luck

11 March 2010

Validating XML Documents against XML Schema using JAXP1.3 Validator

Here's an example on how to validate an XML document against an XML Schema using JAXP 1.3 Validator API.
Suppose you have the following XML Schema file :

(the full file path should be : org/daz/xml/validation/employee.xsd)

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="employees" type="employeesType" />
<xsd:complexType name="employeesType">
<xsd:sequence>
<xsd:element name="employee" type="employeeType"
maxOccurs="unbounded" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="company" type="xsd:string" use="required" />
</xsd:complexType>
<xsd:complexType name="employeeType">
<xsd:sequence>
<xsd:element ref="name" />
<xsd:element ref="role" maxOccurs="unbounded" minOccurs="1" />
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required" />
</xsd:complexType>
<xsd:element name="name">
<xsd:simpleType>
<xsd:restriction base="xsd:string" />
</xsd:simpleType>
</xsd:element>
<xsd:element name="role">
<xsd:simpleType>
<xsd:restriction base="xsd:string" />
</xsd:simpleType>
</xsd:element>
</xsd:schema>


And This XML File :

(the full file path should be : org/daz/xml/validation/employee.xml)
<?xml version="1.0" encoding="UTF-8"?>
<employees company="ArxICT" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="employee.xsd">
<employee id="MHWDY">
<name>Mohammed Hewedy</name>
<role>SW Engineer</role>
</employee>
<employee id="MBSRY">
<name>Mohammed Besary</name>
<role>QA Engineer</role>
<role>Business Analyst</role>
</employee>
<employee id="EDWD">
<name>Eslam Dawood</name>
<role>SW Engineer</role>
</employee>
</employees>


Here's the code that validate the XML Againest the Schema :

package org.daz.xml.validation;

import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class EmployeeValidatorTest {

public void validate(String schemaFile, String xmlFile) {
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(getSource(schemaFile));
Validator validator = schema.newValidator();
ValidationHandler handler = new ValidationHandler();
validator.setErrorHandler(handler);
validator.validate(getSource(xmlFile));

if (handler.errorsFound == true) {
System.err.println("Validation Error : " + handler.exception.getMessage());
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private Source getSource(String resource) {
return new StreamSource(EmployeeValidatorTest.class.getClassLoader().getResourceAsStream(resource));
}

private class ValidationHandler implements ErrorHandler{
private boolean errorsFound = false;
private SAXParseException exception;

public void error(SAXParseException exception) throws SAXException {
this.errorsFound = true;
this.exception = exception;
}
public void fatalError(SAXParseException exception) throws SAXException {
this.errorsFound = true;
this.exception = exception;
}
public void warning(SAXParseException exception) throws SAXException {
}
}

/*
* Test
*/
public static void main(String[] args) {
new EmployeeValidatorTest().
validate("org/daz/xml/validation/employee.xsd", "org/daz/xml/validation/employee.xml");
}
}


related SO question: about "Cannot find the declaration of element "
http://stackoverflow.com/questions/3049779/cannot-validate-xml-doc-againest-cybs-xsd-schema-cannot-find-the-declaration-of/3049812#3049812

05 March 2010

Using java.beans.XMLEncoder and XMLDecoder

java.beans.XMLEncoder and java.beans.XMLDecoder provides functionality similar to one of java.io.ObjectInputStream and java.io.ObjectOutputStream in which it can serialize an Object ( or graph of Objects) to some streams to be used later.

I've created a simple example here on how to use it :

Here's the Person Class that to be serialized:


package org.daz.xml;

public class Person implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
private int age;

// Don't forget the Default Constructor
public Person() {
}

public Person(String fName, String lName, int age) {
this.firstName = fName;
this.lastName = lName;
this.age = age;
}

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}



And Here's The Encoder :

package org.daz.xml;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;

public class XMLEncoderTest<T> {

private static final String FILE_PATH = "org/daz/xml/persons.xml";

public static void main(String[] args) throws Exception{
XMLEncoderTest<Person> personEncoder = new XMLEncoderTest<Person>();
Person person = new Person("Ahmed", "Talat", 23);
personEncoder.encode(person);
Person p = personEncoder.decode(true);
System.out.println("Result : ");
System.out.println(p.getFirstName() + " \t" + p.getLastName() + "\t" + p.getAge());
}

public void encode(T object) throws Exception{
OutputStream stream = new FileOutputStream(new File(XMLEncoderTest.class.getClassLoader().getResource(FILE_PATH).toURI()));
XMLEncoder encoder = new XMLEncoder(stream);
encoder.writeObject(object);
encoder.close();
}

public T decode(boolean showXml) throws IOException{
InputStream inStream = XMLEncoderTest.class.getClassLoader().getResourceAsStream(FILE_PATH);
XMLDecoder decoder = new XMLDecoder(inStream);
T t = (T) decoder.readObject();
decoder.close();

if (showXml) {
printXML();
}
return t;
}

private void printXML()throws IOException{
InputStream inStream = XMLEncoderTest.class.getClassLoader().getResourceAsStream(FILE_PATH);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buf = new byte[inStream.available()];
inStream.read(buf);
byteStream.write(buf);
System.out.println("Raw XML : \n" + byteStream.toString());
}
}



Before to run, create an empty xml file besides your Java source files (to be located at org/daz/xml/persons.xml )