Saturday, December 22, 2007

Using the Java Standard Tag Library (JSTL) in a JSP Page

There are four tag libraries that make up the JSTL; see the javax.servlet.jsp.jstl.* packages for examples that use these tag libraries. JSTL is not yet a standard part of a JSP container. Hence, in order to use the JSTL in a web application, you must include a copy the JSTL library code in the WEB-INF directory of your web application. These files are available in the Web Services Developer Pack, which can be download from http://java.sun.com/webservices/webservicespack.html.
A tag library has two parts: a Tag Library Descriptor (TLD) file and a JAR file. The following ant elements copy the TLD files from the Web Services Developer Pack into WEB-INF/tld and the JAR files into WEB-INF/lib. These elements should be added to the build target in your build.xml file:

<%-- Copy TLD files from WSDP installation --%>






<%-- Copy JSTL jar files from WSDP installation --%>









In order for a JSP page to use the JSTL, it must declare it's use on the page using the taglib directive. Here's an example that declares the use of all four JSTL tag libraries:
<%-- Core --%>
<%@ taglib uri="/WEB-INF/tld/c-rt.tld" prefix="c_rt" %>

<%-- I18N Formatting --%>
<%@ taglib uri="/WEB-INF/tld/fmt-rt.tld" prefix="fmt_rt" %>

<%-- SQL --%>
<%@ taglib uri="/WEB-INF/tld/sql-rt.tld" prefix="sql_rt" %>

<%-- XML --%>
<%@ taglib uri="/WEB-INF/tld/x-rt.tld" prefix="x_rt" %>

Sample Java Code To Create Custom Tag

A custom tag handler must implement the Tag interface. This interface is implemented by many convenient support classes from which a custom tag handler can extend. As a JSP page is executed and the custom tag is encountered, the doStartTag() of the tag handler is executed. If that method does not throw an exception, the tag handler's doEndTag() method is then called.
The JSP container may create many instances of the tag handler but guarantees that an instance services only one request at a time. A JSP container also typically reuses a tag handler instance and so instance variables should be appropriately reset if necessary.

This example implements a tag handler for the simplest type of tag - - one without attributes or a body. This custom tag simply prints the current time and day.

package com.mycompany;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

// This tag simply emits the current date and time.
public class MyTagHandler extends TagSupport {
public int doStartTag() throws JspException {
try {
// Print the current date and time
pageContext.getOut().print(""+new java.util.Date());
} catch (java.io.IOException e) {
throw new JspTagException("MyTag: "+e.getMessage());
}
return SKIP_BODY;
}

public int doEndTag() {
return EVAL_PAGE;
}
}

A web application wishing to use the custom tag must not only include the custom tag's class file but also its Tag Library Descriptor (TLD) as well. The TLD is a file that contains information about one or more custom tags and is needed by a JSP container to process pages that use a custom tag. Here's the TLD file (mytaglib.tld) for the custom tag:


"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<%-- Version of this tag library; it should have the form 123 or 123.456 --%>
0.96

<%-- The required version of JSP for this tag library --%>
1.2

<%-- The preferred prefix for this tag library --%>
my

<%-- This is the URI that uniquely identifies this tag library.
The URI does not have to exist; it is merely an identifier --%>
http://com.mycompany/taglib/mytaglib

<%-- This name is used by tools to represent this tag library --%>
My Tag Library

This is a description of the tag library.


<%-- Name of tag in this library --%>
simple
com.mycompany.MyTagHandler

<%-- Specify that the tag must not have a body --%>
empty

This is a description of the tag.




Here's an example of a JSP page that uses the custom tag. The TLD file is assumed to be in WEB-INF/tld and the MyTagHandler.class file in WEB-INF/classes/com/mycompany:
<%@ taglib uri="/WEB-INF/tld/mytaglib.tld" prefix="my" %>

Thursday, December 20, 2007

Java Program to Parse an XML File Using SAX

import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class BasicSax {
public static void main(String[] args) {
// Create a handler to handle the SAX events generated during parsing
DefaultHandler handler = new MyHandler();

// Parse the file using the handler
parseXmlFile("infilename.xml", handler, false);
}

// DefaultHandler contain no-op implementations for all SAX events.
// This class should override methods to capture the events of interest.
static class MyHandler extends DefaultHandler {
}

// Parses an XML file using a SAX parser.
// If validating is true, the contents is validated against the DTD
// specified in the file.
public static void parseXmlFile(String filename, DefaultHandler handler, boolean validating) {
try {
// Create a builder factory
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(validating);

// Create the builder and parse the file
factory.newSAXParser().parse(new File(filename), handler);
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
}
}

Wednesday, December 19, 2007

Java Code to convert XML fragment to DOM fragment

// Parses a string containing XML and returns a DocumentFragment
// containing the nodes of the parsed XML.

public static DocumentFragment parseXml(Document doc, String fragment) {
// Wrap the fragment in an arbitrary element
fragment = ""+fragment+"";

try {
// Create a DOM builder and parse the fragment
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

Document d = factory.newDocumentBuilder().parse(
new InputSource(new StringReader(fragment)));

// Import the nodes of the new document into doc so tha they

// will be compatible with doc
Node node = doc.importNode(d.getDocumentElement(), true);

// Create the document fragment node to hold the new nodes
DocumentFragment docfrag = doc.createDocumentFragment();

// Move the nodes into the fragment
while (node.hasChildNodes()) {
docfrag.appendChild(node.removeChild(node.getFirstChild()));
}

// Return the fragment
return docfrag;
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
return null;
}

Here's an example that uses the method:
// Obtain an XML document; this method is implemented in
// e510 The Quintessential Program to Create a DOM Document from an XML File
Document doc = parseXmlFile("infilename.xml", false);

// Create a fragment
DocumentFragment frag = parseXml(doc, "hello joe");

// Append the new fragment to the end of the root element
Element element = doc.getDocumentElement();
element.appendChild(frag);

Tuesday, December 18, 2007

Java Program to Play a music file.

//Loading and Playing Midi Audio
try {
// From file
Sequence sequence = MidiSystem.getSequence(new File("midifile"));

// From URL
sequence = MidiSystem.getSequence(new URL("http://hostname/midifile"));

// Create a sequencer for the sequence
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);

// Start playing
sequencer.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (MidiUnavailableException e) {
} catch (InvalidMidiDataException e) {
}

Monday, December 17, 2007

Java Program to Play Streaming Midi Audio

//Playing Streaming Midi Audio
//Supported audio file formats: mid, rmf
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();

// From file
InputStream is = new BufferedInputStream(
new FileInputStream(new File("midifile")));

// From URL
is = new BufferedInputStream(
new URL("http://hostname/rmffile").openStream());

sequencer.setSequence(is);

// Start playing
sequencer.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (MidiUnavailableException e) {
} catch (InvalidMidiDataException e) {
}

Sunday, December 16, 2007

Java Code for Playing Streaming Midi Audio

//Supported audio file formats: mid, rmf
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();

// From file
InputStream is = new BufferedInputStream(
new FileInputStream(new File("midifile")));

// From URL
is = new BufferedInputStream(
new URL("http://hostname/rmffile").openStream());

sequencer.setSequence(is);

// Start playing
sequencer.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (MidiUnavailableException e) {
} catch (InvalidMidiDataException e) {
}