Custom Hibernate Query(SQL) Examples


Custom Hibernate Query Examples;

public static boolean queryStaffLogin(Session openSession,Staff stf)
{
boolean loginResult=false;
try
{
//selecting all information from STAFFS and AUTHORITIES TABLE
//using {s.*} and {a.*}

SQLQuery sqlQry = openSession.createSQLQuery(“”
+”SELECT {s.*} , {a.*} “
+” FROM STAFFS {s}, AUTHORITIES {a}”
+” WHERE {s}.STAFFAUTHORYID = {a}.AUTHORITYID”
+” AND {s}.STAFFAUTHORYID=:pstaffauthid“+ ” AND {s}.STAFFUSERNAME=”
+”:pstfusername AND {s}.STAFFPASSWORD=:pstfpassword“);

sqlQry.addEntity(“s”, Staff.class); //s variable will refer to Staff object
sqlQry.addEntity(“a”, Authority.class); //a varible will refer to Authority object

sqlQry.setLong(“pstaffauthid”, stf.getAuthority().getAuthorityId()); //parameter setting :pstaffauthid
sqlQry.setString(“pstfusername”, stf.getStaffUsername());//parameter setting :pstfusername
sqlQry.setString(“pstfpassword”, stf.getStaffPassword());//parameter setting :pstfpassword

Iterator it = sqlQry.list().iterator();
if(it.hasNext())
{
loginResult = true;
}
}
catch(Exception ex)
{
log.log(Level.SEVERE, “QueryManager : queryntvStaffLogin”, ex);
}
return loginResult;
}

Second example:

public static List<CustomerAddress> queryntvSearchCustomerAddressList(Session openSession, Customer customerIn)
{
 List<CustomerAddress> custAddrList = null;
try
{
SQLQuery sqlQry = openSession.createSQLQuery(“”
+”SELECT {ca.*} FROM CUSTOMERADDRESSES {ca}”
                    +” WHERE {ca}.ADDRESSCUSTOMERID=:acId
                    +””);
sqlQry.addEntity(“ca“, CustomerAddress.class);
sqlQry.setLong(“acId“,customerIn.getCustomerId());

custAddrList = sqlQry.list();
}
catch(Exception ex)
{
log.log(Level.SEVERE, “QueryManager : queryntvSearchCustomerAddressList “,ex);
}
return custAddrList;
}

How to produce a HTML output using XML and XSL transformation


In this post, I will show how to produce a HTML file using XML and XSL transformation;

XSL files are used to get (iterate) the required data from XML files.  Lets examine the following web application’s source code;

XML file; bank.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<?xml-stylesheet type=”text/xsl” href=”bank.xsl”?>
<bnk:Bank
xmlns:bnk=”http://www.tunatore.wordpress.com/bank&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.tunatore.wordpress.com/bank bank.xsd”>

    <bnk:BankName>IT Bank of Turkey</bnk:BankName>
    <bnk:Branch>
        <bnk:branchID>11111</bnk:branchID>
        <bnk:branchName>Istanbul Branch</bnk:branchName>
        <bnk:branchLocation>Istanbul</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Branch>
        <bnk:branchID>12345</bnk:branchID>
        <bnk:branchName>New York Branch</bnk:branchName>
        <bnk:branchLocation>New York</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Branch>
        <bnk:branchID>222222</bnk:branchID>
        <bnk:branchName>Miami Branch</bnk:branchName>
        <bnk:branchLocation>Miami</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Employee>
        <bnk:employeeID>12345678</bnk:employeeID>
        <bnk:name>Tuna</bnk:name>
        <bnk:surname>TORE</bnk:surname>
        <bnk:profession>IOC Advocate, Abstract Developer</bnk:profession>
    </bnk:Employee>

    <bnk:Employee>
        <bnk:employeeID>987654321</bnk:employeeID>
        <bnk:name>James</bnk:name>
        <bnk:surname>Gosling</bnk:surname>
        <bnk:profession>Java GURU</bnk:profession>
    </bnk:Employee>

    <bnk:Employee>
        <bnk:employeeID>11111111</bnk:employeeID>
        <bnk:name>Linus</bnk:name>
        <bnk:surname>Torvalds</bnk:surname>
        <bnk:profession>Linux GURU</bnk:profession>
    </bnk:Employee>

</bnk:Bank>

XSL file bank.xsl

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
  <xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform&#8221;
   xmlns:bnk=”http://www.tunatore.wordpress.com/bank&#8221; exclude-result-prefixes=”xhtml” >
  <xsl:output indent=”yes” method=”html” doctype-public=”-//W3C//DTD XHTML 1.0 Transitional//EN”
    doctype-system=”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”/&gt;
  <xsl:template match=”bnk:Bank”>
    <html xmlns=”http://www.w3.org/1999/xhtml”&gt;
    <head>
    <title>COMPANY</title>
    </head>
    <body bgcolor=”#CEF6CE”>
        <strong><h1><xsl:value-of select=”bnk:BankName”/></h1></strong>
         <table>
            <tr>
               <td>
               <h2>BRANCHES</h2>
               <table width=”500px” cellpadding=”0″ cellspacing=”0″ border=”1″>
                <tr>
                  <th>branchID</th>
                  <th>branchName</th>
                  <th>branchLocation</th>
                </tr>
                <xsl:for-each select=”//bnk:Branch”>
                  <tr>
                    <td><xsl:value-of select=”bnk:branchID”/></td>
                    <td><xsl:value-of select=”bnk:branchName”/></td>
                    <td><xsl:value-of select=”bnk:branchLocation”/></td>
                  </tr>
                </xsl:for-each>
                </table>
                </td>
             </tr>
             <tr>
               <td width=”500px”>
               <h2>EMPLOYEES</h2>
               <table width=”500px” cellpadding=”0″ cellspacing=”0″ border=”1″>
                <tr>
                  <th>employeeID</th>
                  <th>name</th>
                  <th>surname</th>
                  <th>profession</th>
                </tr>
                <xsl:for-each select=”//bnk:Employee”>
                  <tr>
                    <td><xsl:value-of select=”bnk:employeeID”/></td>
                    <td><xsl:value-of select=”bnk:name”/></td>
                    <td><xsl:value-of select=”bnk:surname”/></td>
                    <td><xsl:value-of select=”bnk:profession”/></td>
                  </tr>
                </xsl:for-each>
                </table>
                </td>
             </tr>
      </table>
    </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

Servlet class: TransformXML.java

package xmlxslwebexample;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.File;
import java.io.PrintWriter;

/**
 *
 * @author tunatore
 */
public class TransformXML extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType(“text/html;charset=UTF-8”);
        PrintWriter out = response.getWriter();
        try {

            //getting XML and XSL files
            File sourceFile = new File(TransformXML.class.getResource(“bank.xml”).getFile().replace(“%20″, ” “));
            File xsltFile = new File(TransformXML.class.getResource(“bank.xsl”).getFile().replace(“%20″, ” “));

            Source xsltSource = new StreamSource(xsltFile);
            Source xmlSource = new StreamSource(sourceFile);

            TransformerFactory factory = TransformerFactory.newInstance();            
            Transformer transformer = factory.newTransformer(xsltSource);
            //producing html output by using XML and XSL transformation
            transformer.transform(xmlSource, new StreamResult(out));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

Jsp file: index.jsp

<%–
    Document   : index
    Created on : May 24, 2011, 1:04:01 AM
    Author     : tunatore
–%>

<%@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”&gt;

<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
        <title>JSP Page</title>
    </head>
    <body>
        <jsp:forward page=”/TransformXML”></jsp:forward>
    </body>
</html>

Sample output:

 

Download Source

 

How to use inner classes in JAVA?


Here is a example code for testing Inner Classes in Java Environment;

package innerclassexample;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
*
* @author tunatore
*/
public class Department {

private static String deparmentName = “IT Department”;
private static int departmentId = 1;
//Syntax
//OuterClass.StaticInnerClass innerClassObject = new OuterClass.StaticInnerClass();
//location is a static inner class
private Location location = new Department.Location(“Istanbul”);
private List employeesInDepartment = new ArrayList();

//this is a inner class inside Department class
public class Employee {

private int employeeId;
private String name;
private String surname;
//private static String staticVariableIsNotAllowed;
//inner classes can not have static variables error

/**
* @return the employeeId
*/
public int getEmployeeId() {
return employeeId;
}
/**
* @param employeeId the employeeId to set
*/
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the surname
*/
public String getSurname() {
return surname;
}
/**
* @param surname the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}
public String getDepartmentInfoInsideEmployeeClass() {

//inner classes can access outer classes variables
String departmentInfo = “Department’s Name–> ” + deparmentName
+ ” Department’s ID –> ” + departmentId
+ “ Department’s Location –> ” + location.getLocationName();
return departmentInfo;
}
}
public static class Location {

private String locationName = “”;
public Location(String name) {
locationName = name;
}
private String getLocationName() {
return locationName;
}

}

//both of these class declarations are allowed
public class TestClass {}
private class TestClass1 {}
protected class TestClass3 {}
class TestClass4 {}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

Department department = new Department();

//creating an instance of employee inner class by using outer class
//Syntax
//OuterClass.InnerClass innerClassObject = outerClassObject.new InnerClass();
Department.Employee employee = department.new Employee();
employee.employeeId = 1;
employee.name = “Tuna“;
employee.surname = “Tore“;

Department.Employee employee2 = department.new Employee();
employee2.employeeId = 2;
employee2.name = “James“;
employee2.surname = “Gosling“;

System.out.println(employee.getDepartmentInfoInsideEmployeeClass());

department.employeesInDepartment.add(employee);
department.employeesInDepartment.add(employee2);

System.out.println(“Employees in Department –> ” + department.deparmentName);

for (Iterator it = department.employeesInDepartment.iterator(); it.hasNext();) {
Employee employeeObj = (Employee)it.next();
System.out.println(employeeObj.getEmployeeId() + ” ” + employeeObj.getName() + ” ” + employeeObj.getSurname());

}

}

}

Output of the program

run:
Department’s Name–> IT Department Department’s ID –> 1 Department’s Location –> Istanbul
Employees in Department –> IT Department
1 Tuna Tore
2 James Gosling
BUILD SUCCESSFUL (total time: 1 second)

Download Source

How to use serialization with JAVA? Serialize objects


Serialization can be considered as saving the state of any class instances into a file or a stream.

Firstly, Serializable objects must implement the Serializable interface.

Lets use the following code for serialization.

Message.java class will be serialized by the program so that it must implement Serializable interface

package serializationexample;

import java.io.Serializable;

/**
*
* @author tunatore
*/
public class Message implements Serializable{

private int messageId; //–>available for serialization
private String code; //–>available for serialization
private String content; //–>available for serialization
private transient String privateInfo;
//this field does not allow serialization
//the value stored inside this field wont be available to read
//by an another program
//transient keyword should be used to achieve this kind of operation

/**
* @return the messageId
*/
public int getMessageId() {
return messageId;
}

/**
* @param messageId the messageId to set
*/
public void setMessageId(int messageId) {
this.messageId = messageId;
}

/**
* @return the code
*/
public String getCode() {
return code;
}

/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}

/**
* @return the content
*/
public String getContent() {
return content;
}

/**
* @param content the content to set
*/
public void setContent(String content) {
this.content = content;
}

/**
* @return the privateInfo
*/
public String getPrivateInfo() {
return privateInfo;
}

/**
* @param privateInfo the privateInfo to set
*/
public void setPrivateInfo(String privateInfo) {
this.privateInfo = privateInfo;
}
}

Main.java class will handle all of serialization and deserialization processes

package serializationexample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
*
* @author tunatore
*/
public class Main {

public static void main(String[] args) {

Message message = new Message();
message.setMessageId(0);
message.setCode(“000000”);
message.setContent(“SUCCESS MESSAGE”);
message.setPrivateInfo(“PRIVATE INFO WILL BE HERE”);

System.out.println(“BEFORE SERIALIZATION”);
System.out.println(“Message ID: ” + message.getMessageId());
System.out.println(“Message code: ” + message.getCode());
System.out.println(“Message content: ” + message.getContent());
System.out.println(“Message private info: ” + message.getPrivateInfo());

serializeMessageObject(message);

Message afterDeSerializeMessage = deserializeMessageObject();

System.out.println(“\nAFTER DESERIALIZATION”);
System.out.println(“Message ID: ” + afterDeSerializeMessage.getMessageId());
System.out.println(“Message code: ” + afterDeSerializeMessage.getCode());
System.out.println(“Message content: ” + afterDeSerializeMessage.getContent());
System.out.println(“Message private info: ” + afterDeSerializeMessage.getPrivateInfo());
//transient field will be NULL because it was not serialized by the program
}
public static void serializeMessageObject(Message message) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(new File(“serialized.file”));
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(message);
objectOutputStream.close();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public static Message deserializeMessageObject() {
Message message = null;
try {
FileInputStream fileInputStream = new FileInputStream(new File(“serialized.file”));
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
message = (Message) objectInputStream.readObject();
objectInputStream.close();
} catch (Exception e) {
e.printStackTrace(System.out);
}
return message;
}

}

Output of the program

run:
BEFORE SERIALIZATION
Message ID: 0
Message code: 000000
Message content: SUCCESS MESSAGE
Message private info: PRIVATE INFO WILL BE HERE

AFTER DESERIALIZATION
Message ID: 0
Message code: 000000
Message content: SUCCESS MESSAGE
Message private info: null
BUILD SUCCESSFUL (total time: 2 seconds)

The program throws an exception if you don’t implement the Serializable interface by Message class.

 java.io.NotSerializableException: serializationexample.Message

at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
Exception in thread “main” java.lang.NullPointerException
at serializationexample.Main.serializeMessageObject(Main.java:44)
at serializationexample.Main.main( at serializationexample.Main.main(Main.java:29)
Main.java:34)
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: serializationexample.Message
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1332)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at serializationexample.Main.deserializeMessageObject(Main.java:55)
at serializationexample.Main.main(Main.java:31)
Caused by: java.io.NotSerializableException: serializationexample.Message
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at serializationexample.Main.serializeMessageObject(Main.java:44)
at serializationexample.Main.main(Main.java:29)

Download Source

How to validate a XML file using XSD schema file simple example (JAVA)


 

Here is a sample XML file;

<?xml version=”1.0″ encoding=”UTF-8″?>
<?xml-stylesheet type=”text/xsl” href=”bank.xsl”?>
<bnk:Bank
xmlns:bnk=”http://www.tunatore.wordpress.com/bank
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=”http://www.tunatore.wordpress.com/bank bank.xsd”>

    <bnk:BankName>IT Bank of Turkey</bnk:BankName>
    <bnk:Branch>
        <bnk:branchID>11111</bnk:branchID>
        <bnk:branchName>Istanbul Branch</bnk:branchName>
        <bnk:branchLocation>Istanbul</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Branch>
        <bnk:branchID>12345</bnk:branchID>
        <bnk:branchName>New York Branch</bnk:branchName>
        <bnk:branchLocation>New York</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Branch>
        <bnk:branchID>222222</bnk:branchID>
        <bnk:branchName>Miami Branch</bnk:branchName>
        <bnk:branchLocation>Miami</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Employee>
        <bnk:employeeID>12345678</bnk:employeeID>
        <bnk:name>Tuna</bnk:name>
        <bnk:surname>TORE</bnk:surname>
        <bnk:profession>IOC Advocate, Abstract Developer</bnk:profession>
    </bnk:Employee>

    <bnk:Employee>
        <bnk:employeeID>987654321</bnk:employeeID>
        <bnk:name>James</bnk:name>
        <bnk:surname>Gosling</bnk:surname>
        <bnk:profession>Java GURU</bnk:profession>
    </bnk:Employee>

    <bnk:Employee>
        <bnk:employeeID>11111111</bnk:employeeID>
        <bnk:name>Linus</bnk:name>
        <bnk:surname>Torvalds</bnk:surname>
        <bnk:profession>Linux GURU</bnk:profession>
    </bnk:Employee>
   
</bnk:Bank>

XSD file (bank.xsd) for validating the XML (bank.xml)

<?xml version=”1.0″ encoding=”UTF-8″?>
<schema targetNamespace=”http://www.tunatore.wordpress.com/bank
elementFormDefault=”qualified”
xmlns=”http://www.w3.org/2001/XMLSchema
xmlns:bnk=”http://www.tunatore.wordpress.com/bank“>

    <element name=”Bank” type=”bnk:BankType”></element>
    <complexType name=”EmployeeType”>
     <sequence>
      <element name=”employeeID” type=”string”></element>
      <element name=”name” type=”string”></element>
      <element name=”surname” type=”string”></element>
      <element name=”profession” type=”string”></element>
     </sequence>
    </complexType>
  
    <complexType name=”BranchType”>
     <sequence>
      <element name=”branchID” type=”string”></element>
      <element name=”branchName” type=”string”></element>
      <element name=”branchLocation” type=”string”></element>
                <element name=”employee” type=”bnk:EmployeeType” minOccurs=”0″ maxOccurs=”unbounded”></element>
     </sequence>
    </complexType>

    <complexType name=”BankType”>
     <sequence>
                <element name=”BankName” type=”string” minOccurs=”0″ maxOccurs=”1″></element>
                <element name=”Branch” type=”bnk:BranchType” minOccurs=”0″ maxOccurs=”unbounded”></element>
                <element name=”Employee” type=”bnk:EmployeeType” minOccurs=”0″ maxOccurs=”unbounded”></element>
     </sequence>
    </complexType>
     
</schema>

validate method for validating the XML file defined

public static boolean validate() {

        boolean isValid = false;
       
        try {

            //location of the XML file
            File xmlFile = new File(Transformation.class.getResource(“bank.xml”)
                    .getFile().replace(“%20″, ” “));
            //location of the XSD file
            File xsdFile = new File(Transformation.class.getResource(“bank.xsd”)
                    .getFile().replace(“%20″, ” “));

            //Create source objects for XML and XSD files
            Source xmlSource = new StreamSource(xmlFile);
            Source xsdSource = new StreamSource(xsdFile);

            //Create SchemaFactory using XSD file
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(xsdSource);

            //Validator will use xsd  file for validating the XML file
            Validator validator = schema.newValidator();

            // Validate the DOM tree.
            validator.validate(xmlSource);

            isValid = true;
           
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
       
        if(isValid == true)
        System.out.println(“Document is valid!”);
        else
        System.out.println(“Document is NOT valid!”);
       
        return isValid;
    }

SAMPLE OUTPUT FOR A VALID XML DOCUMENT;

run:
Document is valid!
BUILD SUCCESSFUL (total time: 9 seconds)

SAMPLE OUTPUT FOR AN INVALID XML DOCUMENT;

Use the following invalid XML document

<?xml version=”1.0″ encoding=”UTF-8″?>
<?xml-stylesheet type=”text/xsl” href=”bank.xsl”?>
<bnk:Bank
xmlns:bnk=”http://www.tunatore.wordpress.com/bank
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=”http://www.tunatore.wordpress.com/bank bank.xsd”>

    <bnk:NOTVALIDTAG>THIS ELEMENT IS NOT VALID</bnk:NOTVALIDTAG>

    <bnk:BankName>IT Bank of Turkey</bnk:BankName>
    <bnk:Branch>
        <bnk:branchID>11111</bnk:branchID>
        <bnk:branchName>Istanbul Branch</bnk:branchName>
        <bnk:branchLocation>Istanbul</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Branch>
        <bnk:branchID>12345</bnk:branchID>
        <bnk:branchName>New York Branch</bnk:branchName>
        <bnk:branchLocation>New York</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Branch>
        <bnk:branchID>222222</bnk:branchID>
        <bnk:branchName>Miami Branch</bnk:branchName>
        <bnk:branchLocation>Miami</bnk:branchLocation>
    </bnk:Branch>

    <bnk:Employee>
        <bnk:employeeID>12345678</bnk:employeeID>
        <bnk:name>Tuna</bnk:name>
        <bnk:surname>TORE</bnk:surname>
        <bnk:profession>IOC Advocate, Abstract Developer</bnk:profession>
    </bnk:Employee>

    <bnk:Employee>
        <bnk:employeeID>987654321</bnk:employeeID>
        <bnk:name>James</bnk:name>
        <bnk:surname>Gosling</bnk:surname>
        <bnk:profession>Java GURU</bnk:profession>
    </bnk:Employee>

    <bnk:Employee>
        <bnk:employeeID>11111111</bnk:employeeID>
        <bnk:name>Linus</bnk:name>
        <bnk:surname>Torvalds</bnk:surname>
        <bnk:profession>Linux GURU</bnk:profession>
    </bnk:Employee>
   
</bnk:Bank>

OUTPUT OF THE PROGRAM

run:
org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element ‘bnk:NOTVALIDTAG’. One of ‘{“http://www.tunatore.wordpress.com/bank”:BankName, “http://www.tunatore.wordpress.com/bank”:Branch, “http://www.tunatore.wordpress.com/bank”:Employee}’ is expected.
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
        at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:417)
        at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3182)
        at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1806)
        at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:705)
        at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:400)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
        at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
        at com.sun.org.apache.xerces.internal.jaxp.validation.StreamValidatorHelper.validate(StreamValidatorHelper.java:144)
        at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorImpl.validate(ValidatorImpl.java:111)
        at javax.xml.validation.Validator.validate(Validator.java:127)
        at xmlxsltexample.Transformation.validate(Transformation.java:75)
        at xmlxsltexample.Transformation.produceHTMLfromXMLwithXSL(Transformation.java:30)
        at xmlxsltexample.Transformation.main(Transformation.java:22)
Document is NOT valid!
BUILD SUCCESSFUL (total time: 2 seconds)

How to use xsl:value-of select inside html tags as an attribute using xsl:attribute


If you want to use <xsl:value-of select=””/> inside .xsl files.

Use the following examples;

The following is used as an attribute for html tags;

<a><xsl:attribute name=”href”><xsl:value-of select=”bnk:URL”/></xsl:attribute> Click me </a>

the result will be such as the following

or the second solutions is using XPath expression inside {} braces such as

<a href={bnk:URL}>Click me</a>

and the result will be same;

<xsl:value-of select> could be also used like;

<td> <xsl:value-of select=”bnk:URL”/ ></td>

the result is;

<td>https://tunatore.wordpress.com</td&gt;

How to use static import in Java?


By using static import statement such as importing; Math class

import static java.lang.Math.*;

All of the fields and methods of Math class will be available inside the importer class without having a reference to Math class. (Math.PI)

Let me give you an example;

package staticimportexample;

import static java.awt.Color.*;
import static java.lang.Math.*;
import static java.lang.System.*;

/**
* @author tunatore
*/
public class Main {

/**
* import static example
*/

public static void main(String[] args) {

// by importing with static keyword
// instead of accessing methods or fields by the class name reference
// such as Math.PI or Color.GREEN
// these fields can be used like PI or GREEN in the code
// example:

//orginal access must be Math.PI
//using static import gives an access by field name only
System.out.println(“PI –> ” + PI);

//original access must be Math.E
System.out.println(“E –> ” + E);

//original access must be Color.GREEN
System.out.println(GREEN);

//original method Math.sqrt(400)
//after static import
System.out.println(“sqrt(400) –> ” + sqrt(400));

//original System.out.println();
out.println(“I am System.out.println method”);

}

}

Output of the program;

run:
PI –> 3.141592653589793
E –> 2.718281828459045
java.awt.Color[r=0,g=255,b=0]
sqrt(400) –> 20.0
I am System.out.println method
BUILD SUCCESSFUL (total time: 1 second)

Download Source