Archive for September, 2007

Java & XML, 2nd Edition // Get textual (Web hosting)

Sunday, September 30th, 2007

Java & XML, 2nd Edition // Get textual content, normalized (all interior whitespace compressed to // single space. For example, ” this would be ” would be // “this would be” String normalizedContent = element.getTextNormalize( ); As a result, it commonly seems that no Text class is actually being used. The same methodology applies when invoking setText( ) on an element; the text is created as the content of a new Text instance, and that new instance is added as a child of the element. Again, the rationale is that the process of reading and writing the textual content of an XML element is such a common occurrence that it should be as simple and quick as possible. At the same time, as I pointed out in earlier chapters, a strict tree model makes navigation over content very simple; instanceof and recursion become easy solutions for tree explorations. Therefore, an explicit Text class, present as a child (or children) of Element instances, makes this task much easier. Further, the Text class allows extension, while raw java.lang.String classes are not extensible. For all of these reasons (and several more you can dig into on the jdom-interest mailing lists), the Text class is being added to JDOM. Even though not as readily apparent as in other APIs, it is available for these iteration-type cases. To accommodate this, if you invoke getContent( ) on an Element instance, you will get all of the content within that element. This could include Comments, ProcessingInstructions, EntityRefs, CDATA sections, and textual content. In this case, the textual content is returned as one or more Text instances rather than directly as Strings, allowing processing like this: public void processElement(Element element) { List mixedContent = element.getContent( ); for (Iterator i = mixedContent.iterator(); i.hasNext( ); ) { Object o = i.next( ); if (o instanceof Text) { processText((Text)o); } else if (o instanceof CDATA) { processCDATA((CDATA)o); } else if (o instanceof Comment) { processComment((Comment)o); } else if (o instanceof ProcessingInstruction) { processProcessingInstruction((ProcessingInstruction)o); } else if (o instanceof EntityRef) { processEntityRef((EntityRef)o); } else if (o instanceof Element) { processElement((Element)o); } } } public void processComment(Comment comment) { // Do something with comments} public void processProcessingInstruction(ProcessingInstruction pi) { // Do something with PIs} public void processEntityRef(EntityRef entityRef) { // Do something with entity references}
If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.

Java & XML, 2nd Edition Chapter 8. Advanced

Sunday, September 30th, 2007

Java & XML, 2nd Edition Chapter 8. Advanced JDOM Continuing with JDOM, this chapter introduces some more advanced concepts. In the last chapter, you saw how to read and write XML using JDOM, and also got a good taste of what classes are available in the JDOM distribution. In this chapter, I drill down a little deeper to see what’s going on. You’ll get to see some of the classes that JDOM uses that aren’t exposed in common operations, and you’ll start to understand how JDOM is put together. Once you’ve gotten that basic understanding down, I’ll move on to show you how JDOM can utilize factories and your own custom JDOM implementation classes, albeit in a totally different way than DOM. That will take you right into a fairly advanced example using wrappers and decorators, another pattern for adding functionality to the core set of JDOM classes without needing an interface-based API. 8.1 Helpful JDOM Internals The first topic I cover is the architecture of JDOM. In Chapter 7, I showed you a simple UML-type model of the core JDOM classes. However, if you look closely, there are probably some things in the classes that you haven’t worked with, or didn’t expect. I’m going to cover those particular items in this section, showing how you can get down and dirty with JDOM. JDOM beta 7 was released literally days before this chapter was written. In that release, the Text class was being whiteboarded, but had not been integrated in the JDOM internals. However, this process is happening very quickly, most likely before this book gets into your hands. Even if that is not the case, it will be integrated soon after, and the issues discussed here will then apply. If you have problems with the code snippets in this section, check the version of JDOM you are using, and always try to get the newest possible release. 8.1.1 The Text Class One class you may have been a bit surprised to see in JDOM is the Text class. If you read the last chapter, you probably caught that one large difference between DOM and JDOM is that JDOM (at least seemingly) directly exposes the textual content of an element, whereas in DOM you get the child Text node and then extract its value. What actually happens, though, is that JDOM models character-based content much like DOM does architecturally; each piece of character content is stored within a JDOM Text instance. However, when you invoke getText( ) (or getTextTrim( ) or getTextNormalize( )) on a JDOM Element instance, the instance automatically returns the value(s) in its child Text nodes: // Get textual content String textualContent = element.getText( ); // Get textual content, with surrounding whitespace trimmed String trimmedContent = element.getText().trim( ); // or… String trimmedContent = element.getTextTrim( );
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

Java & XML, 2nd (My web site) Edition 7.5.3 DOMBuilder Last

Saturday, September 29th, 2007

Java & XML, 2nd Edition 7.5.3 DOMBuilder Last but not least, you should be very careful when working with the DOMBuilder class. It’s not how you use the class, but when you use it. As I mentioned, this class works for input in a similar fashion to SAXBuilder. And like its SAX sister class, it has build( ) methods that take in input forms like a Java File or InputStream. However, building a JDOM Document from a file, URL, or I/O stream is always slower than using SAXBuilder; that’s because SAX is used to build a DOM tree in DOMBuilder, and then that DOM tree is converted to JDOM. Of course, this is much slower than leaving out the intermediary step (creating a DOM tree), and simply going straight from SAX to JDOM. So, any time you see code like this: DOMBuilder builder = new DOMBuilder( ); // Building from a file Document doc = builder.build(new File(”input.xml”)); // Building from a URL Document doc = builder.build( new URL(”http://newInstance.com/javaxml2/copyright.xml”)); // Building from an I/O stream Document doc = builder.build(new FileInputStream(”input.xml”)); You should run screaming! Seriously, DOMBuilder has its place: it’s great for taking existing DOM structures and going to JDOM. But for raw, speedy input, it’s simply an inferior choice in terms of performance. Save yourself some headaches and commit this fact to memory now! 7.6 What’s Next? An advanced JDOM chapter follows. In that chapter, I’ll cover some of the finer points of the API, like namespaces, the DOM adapters, how JDOM deals with lists internally, and anything else that might interest those of you who really want to get into the API. It should give you ample knowledge to use JDOM, along with DOM and SAX, in your applications.
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

Java & XML, 2nd Edition 7.5.2 Null Return (Web site designers)

Saturday, September 29th, 2007

Java & XML, 2nd Edition 7.5.2 Null Return Values Another interesting facet of JDOM, and one that has raised some controversy, is the return values from methods that retrieve element content. For example, the various getChild( ) methods on the Element class may return a null value. I mentioned this, and demonstrated it, in the PropsToXML example code. The gotcha occurs when instead of checking if an element exists (as was the case in the example code), you assume that an element already exists. This is most common when some other application or component sends you XML, and your code expects it to conform to a certain format (be it a DTD, XML Schema, or simply an agreed- upon standard). For example, take a look at the following code: Document doc = otherComponent.getDocument( ); String price = doc.getRootElement( ).getChild(”item”) .getChild(”price”) .getTextTrim( ); The problem in this code is that if there is no item element under the root, or no priceelement under that, a null value is returned from the getChild( ) method invocations. Suddenly, this innocuous-looking code begins to emit NullPointerExceptions, which are quite painful to track down. You can handle this situation in one of two ways. The first is to check for null values at each step of the way: Document doc = otherComponent.getDocument( ); Element root = doc.getRootElement( ); Element item = root.getChild(”item”); if (item != null) { Element price = item.getChild(”price”); if (price != null) { String price = price.getTextTrim( ); } else { // Handle exceptional condition} } else { // Handle exceptional condition} The second option is to wrap the entire code fragment in a try/catch block: Document doc = otherComponent.getDocument( ); try { String price = doc.getRootElement( ).getChild(”item”) .getChild(”price”) .getTextTrim( ); } catch (NullPointerException e) { // Handle exceptional condition} While either approach works, I recommend the first; it allows finer-grained error handling, as it is possible to determine exactly which test failed, and therefore exactly what problem occurred. The second code fragment informs you only that somewhere a problem occurred. In any case, careful testing of return values can save you some rather annoying NullPointerExceptions.
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

Java & XML, 2nd Edition governed (Adelphia web hosting) by the

Friday, September 28th, 2007

Java & XML, 2nd Edition governed by the JCP (the Java Community Process). You can read all about the JSR and JCP processes at http://java.sun.com/aboutJava/communityprocess/. As for JDOM, it is now officially JSR-102 and can be found online at Sun’s web site, located at http://java.sun.com/aboutJava/communityprocess/jsr/jsr_102_jdom.html. Once JDOM moves through the JCP, probably in late 2001, several things will happen. First, it will receive a much more elevated status in terms of standards; although the JCP and Sun aren’t perfect, they do offer a lot of credence. The JCP has support and members within IBM, BEA, Compaq, HP, Apache, and more. Additionally, it will become very easy to move JDOM into other Java standards. For example, there is interest from Sun in making JDOM part of the next version of JAXP, either 1.2 or 2.0 (I talk more about JAXP in Chapter 9). Finally, future versions of the JDK are slated to have XML as part of their core; in years to come, JDOM may be in every download of Java. 7.4.2 SAX and DOM as Standards Keep in mind that JDOM isn’t getting some sort of elevated status; DOM and SAX are already both a part of JAXP, and so are actually ahead of JDOM in that regard. However, it’s worth making some comments about the “standardization” of DOM and SAX. First, SAX came out of the public domain, and remains today a de facto standard. Developed primarily on the XML-dev mailing list, no standards body ratified or accepted SAX until it was already in heavy use. While I am by no means criticizing SAX, I am wary of folks who claim that JDOM shouldn’t be used because it wasn’t developed by a standards body. On the other hand, DOM was developed by the W3C, and is a formal standard. For that reason, it has a staunch following. DOM is a great solution for many applications. Again, though, the W3C is simply one standards body; the JCP is another, the IETF is yet another, and so on. I’m not arguing the merits of any particular group; I just caution you about accepting any standard (JDOM or otherwise) if it doesn’t meet your application’s needs. Arguments about “standardization” take a backseat to usability. If you like DOM and it serves your needs, then use it. The same goes for SAX and JDOM. What I would prefer that everybody do, though, is stop trying to make decisions for everyone else (and I know I’m defending my API, but I get this sort of thing all the time!). Hopefully, this book takes you deeply enough into all three APIs to help you make an educated decision. 7.5 Gotcha! Not to disappoint, I want to warn you of some common JDOM pitfalls. I hope this will save you a little time in your JDOM programming. 7.5.1 JDOM isn’t DOM First and foremost, you should realize that JDOM isn’t DOM. It doesn’t wrap DOM, and doesn’t provide extensions to DOM. In other words, the two have no technical relation to each other. Realizing this basic truth will save you a lot of time and effort; there are many articles out there today that talk about getting the DOM interfaces to use JDOM, or avoiding JDOM because it hides some of DOM’s methods. These statements confuse more people than almost anything else. You don’t need to have the DOM interfaces, and DOM calls (like appendChild( ) or createDocument( )) simply won’t work on JDOM. Sorry, wrong API!
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 private void loadFromElements(List (Cheap web hosting)

Friday, September 28th, 2007

Java & XML, 2nd Edition private void loadFromElements(List elements, StringBuffer baseName) { // Iterate through each elementfor (Iterator i = elements.iterator(); i.hasNext( ); ) { Element current = (Element)i.next( ); String name = current.getName( ); // String text = current.getTextTrim( ); String text = current.getAttributeValue(”value”); // Don’t add “.” if no baseName if (baseName.length( ) > 0) { baseName.append(”.”); } baseName.append(name); // See if we have an attribute value if ((text == null) || (text.equals(”"))) { // If no text, recurse on childrenloadFromElements(current.getChildren( ), baseName); } else { // If text, this is a property setProperty(baseName.toString( ), text); } // On unwind from recursion, remove last name if (baseName.length() == name.length( )) { baseName.setLength(0); } else { baseName.setLength(baseName.length( ) - (name.length( ) + 1)); } } } Compile in the changes, and you’re set to deal with attribute values instead of element content. Leave the code in the state you prefer it (as I mentioned earlier, I actually like the values as element content), so if you want textual element content, be sure to back out these changes after seeing how they affect output. Whichever you prefer, hopefully you are starting to know your way around JDOM. And just like SAX and DOM, I highly recommend bookmarking the Javadoc (either locally or online) as a quick reference for those methods you just can’t quite remember. In any case, before wrapping up, let’s talk a little about a common issue with regard to JDOM: standardization. 7.4 Is JDOM a Standard? More than any other question about JDOM, I am asked whether JDOM is a standard. This is a common question, especially among either those who want to use JDOM (and need justification) or those who don’t like JDOM (and need justification). I address some of those issues in this section, so that whatever camp you are in, you know the details about JDOM and its standardization process. 7.4.1 JDOM as a JSR First and foremost, JDOM is now an official JSR, which is a Java Specification Request. In other words, it is going through the formal standardization process, sponsored by Sun and
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

Java & (Web design tools) XML, 2nd Edition // Add in

Thursday, September 27th, 2007

Java & XML, 2nd Edition // Add in header information Comment comment = new Comment(header); doc.addContent(comment); The root element appears before the comment because it is added to the Document object first. However, the Document object can’t be created without supplying a root element a bit of a chicken-or-egg situation. To work with this, you need to use a new method, getContent( ) . This method returns a List, but that List contains all the content of the Document, including comments, the root element, and processing instructions. Then, you can prepend the comment to this list, as shown here, using methods of the List class: // Add in header information Comment comment = new Comment(header); doc.getContent( ).add(0, comment); With this change in place, your output will look as it should:
“:” “./bootstrap.conf” org.enhydra.multiServer.bootstrap.Bootstrap “.”
“org.apache.xerces.parsers.SAXParser”
The getContent( ) method is also available on the Element class, and returns all content of the element, regardless of type (elements, processing instructions, comments, entities, and Strings for textual content). Also important are the modifications necessary for XMLProperties to use attributes for property values, instead of element content. You’ve already seen the code change needed in storage of properties (in fact, the change is commented out in the source code, so you don’t need to write anything new). As for loading, the change involves checking for an attribute instead of an element’s textual content. This can be done with the getAttributeValue(String name) method, which returns the value of the named attribute, or null if no value exists. The change is shown here:
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Java & XML, 2nd Edition C:javaxml2build>java javaxml2.TestXMLProperties enhydraProps.xml (Web design seattle)

Thursday, September 27th, 2007

Java & XML, 2nd Edition C:javaxml2build>java javaxml2.TestXMLProperties enhydraProps.xml output.xml Reading XML properties from enhydraProps.xml —- Property Values —- Property Name: org.enhydra.classpath.separator has value “:” Property Name: org.enhydra.initialargs has value “./bootstrap.conf” Property Name: org.enhydra.initialclass has value org.enhydra.multiServer.bootstrap.BootstrapProperty Name: org.enhydra.classpath has value “.” Property Name: org.xml.sax.parser has value “org.apache.xerces.parsers.SAXParser” Writing XML properties to output.xml And there you have it: XML data formatting, properties behavior. 7.3.4 Backtracking Before wrapping up on the code, there are a few items I want to address. First, take a look at the XML file generated by TestXMLProperties , the result of invoking store( ) on the properties. It should look similar to Example 7-8 if you used the XML version of enhydra.properties detailed earlier in this chapter. Example 7-8. Output from TestXMLProperties
“:” “./bootstrap.conf” org.enhydra.multiServer.bootstrap.Bootstrap “.”
“org.apache.xerces.parsers.SAXParser”
Notice anything wrong? The header comment is in the wrong place. Take another look at the code that added in that comment, from the store( ) method: // Create a new JDOM Document with a root element “properties” Element root = new Element(”properties”); Document doc = new Document(root);
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

Java & XML, 2nd Edition Example 7-7. Testing

Wednesday, September 26th, 2007

Java & XML, 2nd Edition Example 7-7. Testing the XMLProperties class package javaxml2; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Enumeration; public class TestXMLProperties { public static void main(String[] args) { if (args.length != 2) { System.out.println(”Usage: java javaxml2.TestXMLProperties ” + “[XML input document] [XML output document]”); System.exit(0); } try { // Create and load propertiesSystem.out.println(”Reading XML properties from ” + args[0]); XMLProperties props = new XMLProperties( ); props.load(new FileInputStream(args[0])); // Print out properties and valuesSystem.out.println(”nn—- Property Values —-”); Enumeration names = props.propertyNames( ); while (names.hasMoreElements( )) { String name = (String)names.nextElement( ); String value = props.getProperty(name); System.out.println(”Property Name: ” + name + ” has value ” + value); } // Store properties System.out.println(”nnWriting XML properies to ” + args[1]); props.store(new FileOutputStream(args[1]), “Testing XMLProperties class”); } catch (Exception e) { e.printStackTrace( ); } } } This doesn’t do much; it reads in properties, uses them to print out all the property names and values, and then writes those properties back out but all in XML. You can run this program on the XML file generated by the PropsToXML class I showed you earlier in the chapter. The version of XMLProperties used here deals with property values as textual content of elements (the first version of PropsToXML shown), not as attribute values (the second version of PropsToXML). You’ll need to use that earlier version of PropsToXML, or back out your changes, if you are going to use it to generate XML for input to the TestXMLProperties class. Otherwise, you won’t pick up any property values with this code. Supply the test program with the XML input file and the name of the output file:
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Apache web server for windows - Java & XML, 2nd Edition begins again on

Wednesday, September 26th, 2007

Java & XML, 2nd Edition begins again on the new list of children. At each step of recursion, the name of the element being dealt with is appended to the baseName variable, which keeps track of the property names. Winding through recursion, baseName would be org, then org.enhydra, then org.enhydra.classpath. And, as recursion unwinds, the baseName variable is shortened to remove the last element name. Let’s look at the JDOM method calls that make it possible. First, you’ll notice several invocations of the getChildren( ) method on instances of the Element class. This method returns all child elements of the current element as a Java List. There are versions of this method that also take in the name of an element to search for, and return either all elements with that name (getChildren(String name)), or just the first child element with that name (getChild(String name)). There are also namespace-aware versions of the method, which will be covered in the next chapter. To start the recursion process, the root element is obtained from the JDOM Document object through the getRootElement( ) method, and then its children are used to seed recursion. Once in the loadFromElements( ) method, standard Java classes are used to move through the list of elements (such as java.util.Iterator). To check for textual content, the getTextTrim( ) method is used. This method returns the textual content of an element, and returns the element without surrounding whitespace.5 Thus, the content ” textual content ” (note the surrounding whitespace) would be returned as “textual content”. While this seems somewhat trivial, consider this more realistic example of XML: The actual textual content of the title element turns out to be several spaces, followed by a line feed, followed by more space, the characters “Advanced SAX”, more space, another line feed, and even more space. In other words, probably not what you expected. The returned string data from a call to getTextTrim( ) would simply be “Advanced SAX”, which is what you want in most cases anyway. However, if you do want the complete content (often used for reproducing the input document exactly as it came in), you can use the getText( ) method, which returns the element’s content unchanged. If there is no content, the return value from this method is an empty string (”"), which makes for an easy comparison, as shown in the example code. And that’s about it: a few simple method calls and the code is reading XML with JDOM. Let’s see this class in action. 7.3.3 Taking a Test Drive Once you’ve got everything in place in the XMLProperties class, compile it. To test it out, you can enter in or download Example 7-7, which is a class that uses the XMLPropertiesclass to load an XML document, print some information out about it, and then write the properties back out as XML. It also removes more than one space between words. The textual content “lots of spaces” would be returned through getTextTrim( ) as “lots of spaces”.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.