Archive for August, 2007

Java & XML, 2nd (Best web design) Edition // Create new

Friday, August 31st, 2007

Java & XML, 2nd Edition // Create new DOM tree DOMImplementation domImpl = new DOMImplementationImpl( ); Document doc = domImpl.createDocument(null, “item”, null); Element root = doc.getDocumentElement( ); // ID of item (as attribute) root.setAttribute(”id”, id); // Name of item Element nameElement = doc.createElement(”name”); Text nameText = doc.createTextNode(name); nameElement.appendChild(nameText); root.appendChild(nameElement); // Description of item Element descriptionElement = doc.createElement(”description”); Text descriptionText = doc.createTextNode(description); descriptionElement.appendChild(descriptionText); root.appendChild(descriptionElement); // Serialize DOM tree DOMSerializer serializer = new DOMSerializer( ); serializer.serialize(doc, new File(ITEMS_DIRECTORY + “item-” + name + “.xml”)); // Print confirmation PrintWriter out = res.getWriter( ); res.setContentType(”text/html”); out.println(”Thank you for your submission. ” + “Your item has been processed.“); out.close( ); } } Go ahead and compile this class. I’ll walk you through it in just a moment, but ensure that you have your environment set up to include the needed classes. Make sure the DOMSerializer class from the last chapter is in your classpath when compiling the UpdateItemServlet class. You’ll also want to add this to the classes in your servlet engine’s context. In my setup, using Tomcat, my context is called javaxml2, in a directory named javaxml2 under the webapps directory. In my WEB-INF/classes directory, there is a javaxml2 directory (for the package), and then the DOMSerializer.class and UpdateItemServlet.class files are within that directory. You should also ensure that a copy of your parser’s jar file (xerces.jar in my case) is in the classpath of your engine. In Tomcat, you can simply drop a copy in Tomcat’s lib directory. Finally, you’ll need to ensure that Xerces, and the DOM Level 2 implementation within it, is loaded before the DOM Level 1 implementation in Tomcat’s parser.jar archive. Do this by renaming parser.jar to z_parser.jar. I’ll explain more about this in Chapter 10, but for now just trust me and make the change. Then restart Tomcat and everything should work.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

Java & XML, 2nd Edition // DOM importsimport (Professional web hosting)

Friday, August 31st, 2007

Java & XML, 2nd Edition // DOM importsimport org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Element; import org.w3c.dom.Text; // Parser importimport org.apache.xerces.dom.DOMImplementationImpl; public class UpdateItemServlet extends HttpServlet { private static final String ITEMS_DIRECTORY = “/javaxml2/ch06/xml/”; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get output PrintWriter out = res.getWriter( ); res.setContentType(”text/html”); // Output HTML out.println(”“); out.println(” “); out.println(” “); out.println(”

Input/Update Item Listing

“); out.println(”

“); out.println(”

“); out.println(” Item ID (Unique Identifier):
“); out.println(” ” + “

“); out.println(” Item Name:
“); out.println(” ” + “

“); out.println(” Item Description:
“); out.println(”

“); out.println(”   ”); out.println(” “); out.println(”

“); out.println(”

“); out.println(” “); out.println(”“); out.close( ); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get parameter values String id = req.getParameterValues(”id”)[0]; String name = req.getParameterValues(”name”)[0]; String description = req.getParameterValues(”description”)[0];
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Java & XML, 2nd Edition Example 6-1. HTML (X web hosting)

Thursday, August 30th, 2007

Java & XML, 2nd Edition Example 6-1. HTML input form for item listing

Input/Update Item Listing

Item ID (Unique Identifier):

Item Name:

Item Description:

  

Notice that the target of this form submission is a servlet. That servlet is shown in Example 6-2. The doPost( ) method reads in these input parameters and puts their values into temporary variables. At that point, the servlet checks the filesystem for a specific file that has this information stored within it. For the sake of clarity, I’m dealing directly with the filesystem in this servlet. However, this is generally not a good idea. Consider using the ServletContext to get access to local resources, allowing your servlet to be distributed and modified easily depending on the server and servlet engine hosting it. That sort of detail tends to muddy examples up, so I’m keeping it simple here. If the file doesn’t exist (for a new listing, it wouldn’t), it creates a new DOM tree and builds up the tree structure using the values supplied. Once that’s complete, the servlet uses the DOMSerializer class (from Chapter 5) to write the DOM tree out to the file, making it available the next time this servlet is invoked. Additionally, I’ve coded up a doGet( ) method; this method just displays the HTML shown in Example 6-1. I’ll use this later to allow modification of item listings. For now, don’t worry too much about it. Example 6-2. The UpdateItemServlet class package javaxml2; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

Java & XML, (Graphic web design) 2nd Edition Chapter 6. Advanced

Thursday, August 30th, 2007

Java & XML, 2nd Edition Chapter 6. Advanced DOM Just like in Chapter 4, there’s nothing mystical about anything I’ll cover in this chapter. The topics build upon a foundation that I set in the DOM basics from the last chapter. However, with the exception of the first section on mutation, many of these features are rarely used. While almost everything you’ve seen in SAX (except, perhaps, the DTDHandler and DeclHandler) will be handy, I’ve found many of the fringe features of DOM useful only in specific applications. For example, if you aren’t doing any presentation logic, you’ll probably never touch the DOM HTML bindings. The same goes for many of DOM Level 2’s features; if you need them, you need them badly, and if you don’t, you really don’t. In this chapter, I’ll present some specific DOM topics that will be useful in your own DOM programming. I’ve tried to organize the chapter more like a reference than the previous chapters; if you want to find out more about the DOM Level 2 Traversal module, for example, you can simply thumb to that section. However, the code examples in this chapter do build upon each other, so you may still want to work through each section in order to get a complete picture of the current DOM model. This results in more practical code samples, rather than useless contrived ones that won’t get you anywhere. So buckle up, and let’s dive a little deeper into the world of DOM. 6.1 Changes First and foremost, I want to talk about the mutability of a DOM tree. The biggest limitation when using SAX for dealing with XML is that you cannot change any of the XML structure you encounter, at least not without using filters and writers. Those aren’t intended to be used for wholesale document changes anyway, so you’ll need to use another API when you want to modify XML. DOM fits the bill nicely, as it provides XML creation and modification facilities. In working with DOM, the process of creating an XML document is quite different from changing an existing one, so I’ll take them one at a time. This section gives you a fairly realistic example to mull over. If you’ve ever been to an online auction site like eBay, you know that the most important aspects of the auction are the ability to find items, and the ability to find out about items. These functions depend on a user entering in a description of an item, and the auction using that information. The better auction sites allow users to enter in some basic information as well as actual HTML descriptions, which means the savvy user can bold, italicize, link, and add other formatting to their items’ descriptions. This provides a good case for using DOM. 6.1.1 Creating a New DOM Tree To get started, a little bit of groundwork is needed. Example 6-1 shows a simple HTML form that takes basic information about an item to be listed on an auction site. This would obviously be dressed up more for a real site, but you get the idea.
We recommend high quality webhost to host and run your jsp application: christian web host services.

Java & XML, 2nd (Photo web hosting) Edition 5.4.3 DOM Parsers

Wednesday, August 29th, 2007

Java & XML, 2nd Edition 5.4.3 DOM Parsers Throwing SAX Exceptions In this chapter’s example of using DOM, I did not explicitly list the exceptions that could result from a document parse; instead a higher-level exception was caught. This was because, as I mentioned, the process of generating a DOM tree is left up to the parser implementation, and is not always the same. However, it is typically good practice to catch the specific exceptions that can occur and react to them differently, as the type of exception gives information about the problem that occurred. Rewriting the SerializerTest class’s parser invocation this way might make a surprising facet of this process surface. For Apache Xerces this could be done as follows: public void test(String xmlDocument, String outputFilename) throws Exception { try { File outputFile = new File(outputFilename); DOMParser parser = new DOMParser( ); parser.parse(xmlDocument); Document doc = parser.getDocument( ); } catch (IOException e) { System.out.println(”Error reading URI: ” + e.getMessage( )); } catch (SAXException e) { System.out.println(”Error in parsing: ” + e.getMessage( )); } // Serialize DOMSerializer serializer = new DOMSerializer( ); serializer.serialize(doc, new File(outputFilename)); } The IOException seen here should not come as a surprise, as it signifies an error in locating the specified filename as it did in the earlier SAX examples. Something else from the SAX section might make you think something was amiss; did you notice the SAXException that can be thrown? The DOM parser throws a SAX exception? Surely I have imported the wrong set of classes! Not so; these are the right classes. Remember that it would be possible to build a tree structure of the data in an XML document yourself, using SAX, but the DOM provides an alternative. However, this does not preclude SAX from being used in that alternative! In fact, SAX provides a lightweight, fast way to parse a document; in this case, it just happens that as it is parsed, it is inserted into a DOM tree. Because no standard for the DOM creation exists, this is acceptable and not even uncommon. So don’t be surprised or taken aback when you find yourself importing and catching org.xml.sax.SAXException in your DOM applications. 5.5 What’s Next? In Chapter 6, I’ll continue being tour guide through the world of DOM, as we look at some of DOM’s more advanced (and less known) features. To get rolling, I’ll show you how to modify DOM trees, as well as create them. Then, it’s on to the less common functionality in the DOM. For starters, the additions included in DOM Level 2 will be examined (some you’ve already used, and some you haven’t). Next, I’ll cover using the DOM HTML bindings, which will help you when dealing with DOM and web pages. Finally, I’ll give you some information about changes expected in the upcoming DOM Level 3 specification. That should give you plenty of ammo to take over the world using DOM!
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

Web and email hosting - Java & XML, 2nd Edition 5.4 Gotcha! As

Wednesday, August 29th, 2007

Java & XML, 2nd Edition 5.4 Gotcha! As in previous chapters, I want to revisit some of the common pitfalls for new XML Java developers. In this chapter, I have focused on the Document Object Model, and this section continues that emphasis. Although some of the points made here are more informational than directly affective on your programming, they can be helpful in making design decisions about when to use DOM, and instrumental in understanding what is going on under the hood of your XML applications. 5.4.1 Memory, Performance, and Deferred DOMs Earlier, I described the reasons to use DOM or SAX. Although I emphasized that using the DOM requires that the entire XML document be read into memory and stored in a tree structure, enough cannot be said on the subject. All too common is the scenario where a developer loads up his extensive collection of complex XML documents into an XSLT processor and begins a series of offline transformations, leaving the process to grab a bite to eat. Upon returning, he finds that his Windows machine is showing the dreaded “blue screen of death” and his Linux box is screaming about memory problems. For this developer and the hundreds like him, beware the DOM for excessively large data! Using the DOM requires an amount of memory proportional to the size and complexity of an XML document. However, you should dig a bit further into your parser’s documentation. Often, today’s parsers contain a feature modeled on what it typically called a deferred DOM . A deferred DOM tries to lower the memory cost of using DOM by not reading and allocating all information needed by a DOM node until that node is requested. Until that time, the nodes in existence, but not in use, are simply nulled out. This reduces the memory overhead for large documents when only a specific portion of the document must be processed. However, realize that with this decrease in memory, there is an increase in processing. Since nodes are not in memory, and must be filled with data when requested, there is generally more lag time when a node not previously accessed is requested. It’s a tradeoff. However, a deferred DOM can often help save the day when dealing with large documents. 5.4.2 Polymorphism and the Node Interface Previously in this chapter I stressed the tree model that DOM is built upon. I also told you that the key to this was a common interface, org.w3c.dom.Node. This class provides common functionality for all DOM classes, but sometimes it provides more. For example, this class defines a method called getNodeValue( ), which returns a String. Sounds like a good idea, right? Without having to cast the Node to a specific type, you can quickly get its value. However, things get a little sticky when you consider types like Element. Remember that an Element has no textual content, but instead has children of type Text. So an Element in DOM has no value that has any meaning; the result is that you get something like #ELEMENT#. The exact value is parser-dependent, but you get the idea. The same situation applies to other methods on the Node interface, like getNodeName( ). For Text nodes, you get #TEXT#, which doesn’t help too much. So what exactly is the gotcha here? You simply need to be careful when working with different DOM types through the Node interface. You may get some unexpected results along with the convenience of the common interface.
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Java & XML, 2nd Edition You may notice (Web design online)

Tuesday, August 28th, 2007

Java & XML, 2nd Edition You may notice that there is quite a bit of extra whitespace in the output; that’s because the serializer adds some line feeds every time writer.write(lineSeparator) appears in the code. Of course, the underlying DOM tree has some line feeds in it as well, which are reported as Text nodes. The end result in many of these cases is the double line breaks, as seen in the output. Let me be very clear that the DOMSerializer class shown in this chapter is for example purposes, and is not a good production solution. While you are welcome to use the class in your own applications, realize that several important options are left out, like encoding and setting advanced options for indentation, line feeds, and line wrapping. Additionally, entities are handled only in passing (complete treatment would be twice as long as this chapter already is!). Your parser probably has its own serializer class, if not multiple classes, that perform this task at least as well, if not better, than the example in this chapter. However, you now should understand what’s going on under the hood in those classes. As a matter of reference, if you are using Apache Xerces, the classes to look at are in the org.apache.xml.serialize. Some particularly useful ones are the XMLSerializer, XHTMLSerializer, and HTMLSerializer. Check them out they offer a good solution, until DOM Level 3 comes out with a standardized one. 5.3 Mutability One glaring omission in this chapter is the topic of modifying a DOM tree. That’s not an accident; working with DOM is a lot more complex than working with SAX. Rather than drowning you in information, I wanted to give a clear picture of the various node types and structures used in DOM. In the next chapter, in addition to looking at some of the finer points of DOM Levels 2 and 3, I’ll address the mutability of DOM trees, and in particular how to create DOM trees. So don’t panic help is on the way!
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Java & XML, 2nd Edition the OReillyCopyright entity (Web site optimization)

Tuesday, August 28th, 2007

Java & XML, 2nd Edition the OReillyCopyright entity reference. In Apache, this comes across as an entity reference, by the way. And that’s it! As I mentioned, there are a few other node types, but covering them isn’t worth the trouble at this point; you get the idea about how DOM works. In the next chapter, I’ll take you deeper than you probably ever wanted to go. For now, let’s put the pieces together and see some results. 5.2.4 The Results With the DOMSerializer class complete, all that’s left is to invoke the serializer’s serialize( ) method in the test class. To do this, add the following lines to the SerializerTest class: public void test(String xmlDocument, String outputFilename) throws Exception { File outputFile = new File(outputFilename); DOMParser parser = new DOMParser( ); // Get the DOM tree as a Document object parser.parse(xmlDocument); Document doc = parser.getDocument( ); // Serialize DOMSerializer serializer = new DOMSerializer( ); serializer.serialize(doc, new File(outputFilename)); } This fairly simple addition completes the classes, and you can run the example on Chapter 2’s contents.xml file, as shown: C:javaxml2build>java javaxml2.SerializerTestc:javaxml2ch05xmlcontents.xmloutput.xml While you don’t get any exciting output here, you can open up the newly created output.xml file and check it over for accuracy. It should contain all the information in the original XML document, with only the differences already discussed in previous sections. A portion of my output.xml is shown in Example 5-3. Example 5-3. A portion of the output.xml serialized DOM tree Java and XML
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

Java & XML, 2nd Edition case Node.DOCUMENT_NODE: writer.write(”"); (Php web hosting)

Monday, August 27th, 2007

Java & XML, 2nd Edition case Node.DOCUMENT_NODE: writer.write(”“); writer.write(lineSeparator); // recurse on each child NodeList nodes = node.getChildNodes( ); if (nodes != null) { for (int i=0; i“; writer.write(lineSeparator); break; All that’s left at this point is handling entities and entity references. In this chapter, I will skim over entities and focus on entity references; more details on entities and notations are in the next chapter. For now, a reference can simply be output with the & and ; characters surrounding it: case Node.ENTITY_REFERENCE_NODE: writer.write(”&” + node.getNodeName( ) + “;”); break; There are a few surprises that may trip you up when it comes to the output from a node such as this. The definition of how entity references should be processed within DOM allows a lot of latitude, and also relies heavily on the underlying parser’s behavior. In fact, most XML parsers have expanded and processed entity references before the XML document’s data ever makes its way into the DOM tree. Often, when expecting to see an entity reference within your DOM structure, you will find the text or values referenced rather than the entity reference itself. To test this for your parser, you’ll want to run the SerializerTest class on the contents.xml document (which I’ll cover in the next section) and see what it does with
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

Java & XML, 2nd Edition case Node.TEXT_NODE: writer.write(node.getNodeValue(

Monday, August 27th, 2007

Java & XML, 2nd Edition case Node.TEXT_NODE: writer.write(node.getNodeValue( )); break; case Node.CDATA_SECTION_NODE: writer.write(” XML constructs. That’s really all there is to it; see this code addition: case Node.COMMENT_NODE: writer.write(indentLevel + ““); writer.write(lineSeparator); break; Moving on to the next DOM node type: the DOM bindings for Java define an interface to handle processing instructions that are within the input XML document, rather obviously called ProcessingInstruction. This is useful, as these instructions do not follow the same markup model as XML elements and attributes, but are still important for applications to know about. In the table of contents XML document, there aren’t any PIs present (although you could easily add some for testing). The PI node in the DOM is a little bit of a break from what you have seen so far: to fit the syntax into the Node interface model, the getNodeValue( ) method returns all data instructions within a PI in one String. This allows quick output of the PI; however, you still need to use getNodeName( ) to get the name of the PI. If you were writing an application that received PIs from an XML document, you might prefer to use the actual ProcessingInstruction interface; although it exposes the same data, the method names (getTarget( ) and getData( )) are more in line with a PI’s format. With this understanding, you can add in the code to print out any PIs in supplied XML documents: case Node.PROCESSING_INSTRUCTION_NODE: writer.write(”“); writer.write(lineSeparator); break; While the code to deal with PIs is perfectly workable, there is a problem. In the case that handled document nodes, all the serializer did was pull out the document element and recurse. The problem is that this approach ignores any other child nodes of the Document object, such as top-level PIs and any DOCTYPE declarations. Those node types are actually lateral to the document element (root element), and are ignored. Instead of just pulling out the document element, then, the following code serializes all child nodes on the supplied Document object:
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.