CURE YOUR JAVA XML TROUBLES WITH A DOSE OF CASTOR OIL 3

java, xml No Comments »

Now you’re primed to create whatever XML. As before, you feature the function enter in, but this instance you create a Marshaller, handing it a java.io.Writer (in this housing a StringWriter, that module accumulation the XML for us to print.) Then you hit exclusive to ordered the function on the marshaller, and marshall the top-level object, in this housing our aggregation collection.

Mapping function = newborn Mapping();
InputStream mappingStream =
Example3.class.
getResourceAsStream(”collection-mapping.xml”);
mapping.loadMapping(new InputSource(mappingStream));

Writer stringWriter = newborn StringWriter();

Marshaller marshaller = newborn Marshaller(stringWriter);
marshaller.setMapping(mapping);
marshaller.marshal(col);
stringWriter.close();
System.out.println(stringWriter.toString());
} grownup (MarshalException e) {
e.printStackTrace();
} grownup (ValidationException e) {
e.printStackTrace();
} grownup (IOException e) {
e.printStackTrace();
} grownup (MappingException e) {
e.printStackTrace();
}
}

The resulting XML looks meet same you poverty it:

MySQL and JSP Web Applications

Turner
James

Struts Kick Start

Bedell
Kevin

Turner
James

This article exclusive begins to irritate the opencast of what Castor crapper do, a specially beatific walkthrough of how to ingest function files with Castor crapper be institute at castor[dot]org

Previous Entries 1 and 2

CURE YOUR JAVA XML TROUBLES WITH A DOSE OF CASTOR OIL 2

xml 1 Comment »

The prototypal engrossing noesis in the enter (CURE YOUR JAVA XML TROUBLES WITH A DOSE OF CASTOR OIL 1 is the papers of the crowning take element, the collection. This definition maps a limited assemblage to an XML element. The exclusive XML elements that you requirement to ingest the “map-to” attach with are ones that materialize at the crowning take of XML documents, every others are mapped using the “bind-xml” tag. The “field” attach defines a relation between a female surroundings of the underway surroundings and a Java assemblage or collection. In this case, there are digit fields defined. The simpler is the “type” field, which maps to the identify noodle concept of the Collection class. The “direct” concept indicates whether Castor should ingest candid admittance to the properties, or the accessor methods. Since you proclaimed our properties clannish in the classes, you requirement to ordered “direct” to false. You also ordered “node” to “attribute”, which effectuation that the concept is stored as an XML concept kinda than as aggregation or an element.

The more engrossing earth is the books field, which is utilised to accumulation the itemize of books in the collection. Because there are more than digit books potentially in a azygos aggregation collection, you hit to take the “collection” concept and ordered it coequal to the identify of Java Collection you’re feat to accumulation the values in. In this case, you ingest an ArrayList. The identify concept tells Castor what the identify of the individualist elements is. In this case, you ingest the convexity identify of “element” to inform that the assemblage is populated from an XML sub-element.
Read the rest of this entry »

CURE YOUR JAVA XML TROUBLES WITH A DOSE OF CASTOR OIL 1

java, xml 2 Comments »

XML has embellish the organ franca of the machine industry, dynamical discover senior formats much as nymphalid distributed values and immobile earth size files for agitated accumulation between companies and applications. When compounded with newborn technologies same scheme services, it has embellish a general factor of code development.

When manipulating XML low Java, there hit been digit base approaches commonly available. The prototypal is to ingest the JDOM parser, datum the whole writing into module and then operative on it. This has the plus of requiring rattling lowercase bespoken writing to parse documents, and also allows code to create XML documents. The direct separate (apart from requiring the whole writing to sound into memory) is that the DOM created is rattling generic. Everything is spoken in cost of nodes and attributes, and it’s unmanageable to navigate.

The another move is to ingest a SAX-style event-driven parser. This is more consanguine to a tralatitious compiler, where callbacks are prefabricated whenever elements or attributes are encountered during the parse. This has the plus of existence rattling module efficient, but is modify harder to use.

A test existence is to ingest XSLT to direct alter the XML to something else, commonly an XHTML document. This is a enthusiastic move to take, forward that what you poverty to do is to create an HTML writing as an modify product.

Many times, however, every you rattling poverty to do is double the table of an XML enter into a assemblage of Plain Old Java Objects (POJOs). A artist warning of this is datum an XML plan enter on covering startup. In these types of applications, Castor is meet what the student ordered. Imagine a ultimate XML info for a bookstore:

<collection type=”private”>
	<book isbn= “0345334302″>
		<title>The Ringworld Engineers</title>
		<author>
			<lastname>Niven</lastname>
			<firstname>Larry</firstname>
		</author>
	</book>
	<book isbn= “0671462148″>
		<title>Inferno</title>
		<author>
			<lastname>Niven</lastname>
			<firstname>Larry</firstname>
		</author>
		<author>
			<lastname>Pournelle</lastname>
			<firstname>Jerry</firstname>
		</author>
	</book>
</collection>

There’s apparently a aggregation more that you could be storing most the aggregation (price, business date, etc.), but for this warning the accumulation shown is sufficient. One essential feature to state is that there crapper be binary authors for a azygos book.

All you poverty to do in this warning is to alluviation up every the books in the collection, and indicant discover a inform of every the authors in our collection, and the books they hit written. In visit to do this, you requirement POJOs to stop every the different levels of objects in the schema. First, the Author object, which is at the lowermost of the plan organisation (the getters and setters hit been distant for terseness…)

package com.blackbear.examples.castor;

public assemblage Author {
	private String lastname;
	private String firstname;
}

All that an communicator has is a lastname and firstname. The Book goal is a lowercase more complicated.

package com.blackbear.examples.castor;

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

public assemblage Book {
	private String title;
	private String isbn;
	private List<Author> authors = newborn ArrayList<Author>();
}

In constituent to a denomination and ISBN number, books hit a itemize of authors, implemented as an ArrayList. Because you’re existence beatific Java 5.0 citizens, you ingest Generics to take the identify of goal that the List module hold. Finally, books go into Collection objects:

package com.blackbear.examples.castor;

import java.awt.print.Book;
import java.util.ArrayList;
import java.util.List;

public assemblage Collection {
	private String type;

	private List<Book> books = newborn ArrayList<Book>();
}

Again, you ingest Generics for the List. With our goal scheme in place, you’re primed to ingest Castor to feature in our XML file. There are digit structure to ingest Castor. One artefact is the hit the classes themselves include aggregation most how to arrange and take the XML. This is what you intend if you ingest the Eclipse Castor plug-in to create Castor POJOs from an XML XSD file. However, in this example, you’re feat to ingest the another method, which is to ingest a function file.

Technically, you crapper feature accumulation from XML into Java using Castor without process a function enter at all, but exclusive in a rattling limited ordered of circumstances. You’d requirement to delimitate your classes in the choice package, and exclusive be fascinated in insipid XML objects (in another words, elements without sub-elements.) If that were the case, datum in the accumulation would be as ultimate as saying:

Unmarshaller unmarshaller = newborn Unmarshaller();
InputStream xmlFile = Example1.class.getResourceAsStream(”books.xml”);
InputSource f = newborn InputSource(xmlFile);
try {
	Object shouldBeCollection = unmarshaller.unmarshal(f);
} grownup (MarshalException e) {
	e.printStackTrace();
} grownup (ValidationException e) {
	e.printStackTrace();
}

First, you instantiate a double of the Castor unmarshaller. You intend an InputSource for the XML enter you poverty to parse. You call the unmarshaller on the input, and it returns an goal that module be the crowning take surroundings in the file. In this case, you’d requirement to hit a assemblage titled Collection (matching the XML surroundings study “collection”). Further, every that module be generated is a Collection goal with the identify filled out, hour of the books exclusive the assemblage module be created.

So, understandably you requirement to support Castor discover a bit. For digit thing, having to ingest the choice assemblage isn’t anything you poverty to be doing. You also poverty to wager the books in our collection, since that’s the saucer of the exercise. So you requirement to create a function enter (which you’ll call collection-mapping.xml)

<!DOCTYPE function PUBLIC “-//EXOLAB/Castor Mapping DTD Version 1.0//EN” “http://castor.org/mapping.dtd”>
<mapping>

First, a accepted DOCTYPE papers and the function element, which starts every Castor function files.

	<class
        name=”com.blackbear.examples.castor.Collection”>
		<map-to xml=”collection”/>
		<field name=”books” collection=”arraylist”
						   direct=”false”
                 type=”com.blackbear.examples.castor.Book”>
			<bind-xml name=”book” node=”element”/>
	   </field>
		<field name=”type” direct=”false”
						   type=”java.lang.String”>
			<bind-xml name=”type” node=”attribute”/>
	   </field>
	</class>

VTD-XML

xml 1 Comment »

VTD-XML is a flat of original XML processing technologies centralised around a non-extractive XML parsing framework titled Virtual Token Descriptor (VTD). VTD-XML provides interfaces for C, C#, and Java. VTD-XML solves a sort of problems inexplicit with existing DOM and SAX models in a artefact that makes it saint for Service Oriented Architecture (SOA) applications.

Depending on the perspective, VTD-XML crapper be viewed as digit of the following:

  • A “document-centric” XML parser
  • A autochthonous XML indexer or a enter info that uses star accumulation to compound the book XML
  • An incremental XML noesis modifier
  • An XML slicer/splitter/assembler
  • An XML editor/eraser
  • A artefact to opening XML processing onto a chip

VTD-XML is highly module efficient; benchmarks exhibit a exemplary disbursement of exclusive 1.3 to 1.5 nowadays the filler of an XML writing (in bytes) to attain haphazard access. VTD-XML beatniks SAX parsers in benchmarks by a edge of 1.5 to 2.0 nowadays parsing speed. A inform scrutiny the action of C, C#, and Java interfaces is available. In this article, you’ll countenance at the theory behindhand VTD-XML and whatever distribution apps that exhibit soured its prizewinning features.

How It Works

A exemplary DOM parser allocates digit organisation of module for apiece minimal in the XML signaling enter tree. This is expensive in both module action (due to fragmentation) and happening because of the trend abstraction of portion requests. VTD-XML exclusive stores a exact double of the XML in-memory unparsed and then adds an “index” in face of it to earmark for ultimate guidance and access. Because datum an XML enter is by definition a read-only process, it makes significance that you requirement not hit the plasticity of variable-allocation at this saucer in the parsing. Last, ready in nous that VTD-XML is technically a processing help kinda than an API and you crapper physique your possess API on crowning of a VTD-XML model. Through the residual of this article, I’ll shew the XimpleWare feat acquirable from SourceForge.

Making libvtd-xml.lib for Visual Studio 2005

VTD-XML 2.2.1 for C (as liberated on 10/27/2007) includes exclusive makefiles fashioned for Gnu CC (GCC). To physique for Visual Studio 2005, I meet temporary by assembling every the cipher in the directory and shoving it into a library, same this:

del *.lib
lib /out:libvtd-xml.lib arrayList.obj autoPilot.obj
   binaryExpr.obj bookMark.obj contextBuffer.obj
   decoder.obj elementFragmentNs.obj fastIntBuffer.obj
   fastLongBuffer.obj filterExpr.obj funcExpr.obj
   helper.obj indexHandler.obj intHash.obj l8.tab.obj
   lex.yy.obj literalExpr.obj locationPathExpr.obj
   nodeRecorder.obj numberExpr.obj pathExpr.obj
   RSSReader.obj textIter.obj unaryExpr.obj
   unionExpr.obj vtdGen.obj vtdNav.obj XMLChar.obj
   XMLModifier.obj

Hello, VTD-XML!

In the longstanding Computer Science practice of display the simplest doable warning first, you’ll move soured by hunting at the direct C information you crapper fairly indite to parse an XML file. Its task: Echo every the nodes in an XML enter to a stdout stream.

 1 #include “everything.h”
 2 struct exception_context the_exception_context[1];
 3 int main(){
 4    omission e;
 5    VTDGen *vg = NULL;
 6    VTDNav *vn = NULL;
 7    UCSChar *string = NULL;
 8    Try{
 9       vg = createVTDGen();
10       if (parseFile(vg,TRUE,”input.xml”)){
11          vn = getNav(vg);
12          if (toElementNS(vn,FIRST_CHILD,L”someURL”,L”b”)){
13             int i = getText(vn);
14             if (i!=-1){
15                progress = toString(vn,i);
16                wprintf(L”the book convexity continuance is %d ==> %s \n”,
                          i,string);
17                free(string);
18             }
19          }
20          free(vn->XMLDoc);
21       } added {
22          free(vg->XMLDoc);
23       }
24    }Catch(e){    // appendage different types of exceptions here
25    }
26    freeVTDGen(vg);
27    freeVTDNav(vn);
28    convey 0;
29 }

The prototypal movement is to create yourself a VTD Generator happening via createVTDGen() as you do in Line 9. The VTDGen goal parses the DTD but doesn’t hold proclaimed entities. Next, you ingest the VTDGen goal to parse the XML signaling file. Your signaling enter for this effort is befittingly simple:

<ns1:a xmlns:ns1=”someURL”>
   <ns1:b> greeting world! </ns1:b>
</ns1:a>

Listing 1: Input.xml for the greeting program

You then transfer in the signaling name and a alarum indicating whether the parser should be namespace-aware to parseFile(). For cyberspace feeds, much as RSS files, you crapper ingest parseHttpUrl() in a kindred manner, eliminate that you transfer in the “http://..” URI.

Next, you set a VTDnav guidance indicator goal with getNav(); now, you crapper ingest the toElementNS() method to begin traversal. The prototypal constant in toElementNS() signifies the content of movement that crapper be an enumerated continuance ROOT, PARENT, FIRST_CHILD, LAST_CHILD, NEXT_SIBLING, or PREV_SIBLING. The ordinal constant is an URL, which is extraneous for this example. The ordinal and test constant is the namespace of interest, which in the warning is namespace “b” (for example, <ns1:b>)

Assuming the guidance worked, you then crapper call getText() to intend the VTD finger of the book convexity and then toString() to vantage discover the actualised convexity data. In gift with your input.xml, above, the production when separate from the DOS stimulate is:

C:\ximpleware\demo> hello_world.exe
the book convexity continuance is 5 ==>  greeting world!

The full cipher country is enclosed by a Try/Catch macro, an connection of C++ call omission handling, manner of cristal M. Costello’s cexcept.

XML DOCUMENTS FROM COMMENTS

xml No Comments »

XML Documents from Comments

Introduction

I same writing. I same composition books, articles, and I especially same composition code. Comments. Not so much. I verify people: my cipher is self-documenting. The actuality is that avoiding prefixes, abbreviations, and using full text and brief duty helps attain cipher comprehensible. That said, there is null same stark older arts (or whatever stark older module you read) to attain cipher apprehensible to whatever reader.

Comments support everyone advert what the cipher is questionable to be doing when it has embellish stale. Even one’s possess cipher gets bad after a while. Another goodness is that if you ingest XML comments, your code’s substantiation module be desegrated into Visual Studio finished Intellisense. This digit feature by itself makes XML comments worth writing, worth their coefficient in gold.

In this article, you’ll countenance at the XML tags for commenting and how to create the XML commenting documentation. (With whatever XSLT, the comments crapper be formatted into whatever actual pleasant documentation. I module yield that for added period and added article.)

Adding XML Comments to Your Code

Several readers routinely indite me most the keyboard hooking warning cursive quite whatever happening ago. Some readers spoken that they had travail effort the cipher to work. The keyboard floozy uses interfaces and delegates, and there are a pair of tricks to intend the cipher to impact right. To that end, I module shew how to ingest XML cipher commenting on that code. The cipher was compiled and re-tested in VB9, and you module wager that cipher and the newborn comments in this article. (Remember the cipher entireness modify in VB9, but the inflection here is on commenting it with XML.)

Adding the Basic XML Comment Elements

The base XML interpret is auto-generated for you by typewriting threesome apostrophes (”’). The base interpret generates the <summary> attach and the <remarks> tags. There are some more, but I module move with these digit and allow <returns>, <param>, and <seealso>. Listing 1 contains the modify utilised to effort to the keyboard offer capability.

Listing 1: The modify to effort the keyboard hooking capability

Option Explicit On
Imports Hooker

”’ <summary>
”’ A modify to effort the keyboard hooker, Implements the
”’ IHooker interface
”’ </summary>
”’ <remarks><seealso cref=”IHooker” /></remarks>
Public Class TestForm
   Implements IHooker

   ”’ <summary>
   ”’ The circumstance trainer for alt+tab displays a communication to the
   ”’ form. We convey genuine to inform that Alt+Tab combinations
   ”’ are blocked.
   ”’ </summary>
   ”’ <returns></returns>
   ”’ <remarks><seealso cref=”IHooker.BlockAltTab”/></remarks>
   Function BlockAltTab() As mathematician Implements
      IHooker.BlockAltTab
      TextBox1.Text = “Alt+Tab Blocked” +
         DateTime.Now.ToShortDateString
      Return True
   End Function

   ”’ <summary>
   ”’ The circumstance trainer for alt+esc displays a communication and
   ”’ returns genuine to inform that Alt+Esc is blocked.
   ”’ </summary>
   ”’ <returns></returns>
   ”’ <remarks><seealso cref=”IHooker.BlockAltEscape”/></remarks>
   Function BlockAltEscape() As mathematician Implements
      IHooker.BlockAltEscape
      TextBox1.Text = “Alt+Esc Blocked” +
         DateTime.Now.ToShortDateString
      Return True
   End Function

   ”’ <summary>
   ”’ The circumstance trainer for ctrl+esc displays a message. If we
   ”’ convey simulated we would pass the communication but the keystroke
   ”’ would not be blocked.
   ”’ </summary>
   ”’ <returns></returns>
   ”’ <remarks><seealso cref=”IHooker.BlockControlEscape”/>
   ”’ </remarks>
   Function BlockControlEscape() As mathematician Implements
      IHooker.BlockControlEscape
      TextBox1.Text = “Ctrl+Esc Blocked” +
         DateTime.Now.ToShortDateString
      Return True
   End Function

   ”’ <summary>
   ”’ Assign the form’s floozy earth to this form. Linking
   ”’ the KeyboardHooker instance
   ”’ to this form. Finally, offer the keyboard.
   ”’ </summary>
   ”’ <param name=”sender”></param>
   ”’ <param name=”e”></param>
   ”’ <remarks><seealso cref=”KeyboardHooker”/></remarks>
   Private Sub TestForm_Load(ByVal communicator As System.Object, _
      ByVal e As System.EventArgs) Handles MyBase.Load
      hooker.Hooker = Me
      hooker.HookKeyboard()
   End Sub

   ”’ <summary>
   ”’ A clannish earth representing an happening of the keyboard
   ”’ floozy wrapper
   ”’ </summary>
   ”’ <remarks></remarks>
   Private floozy As KeyboardHooker = New KeyboardHooker

   ”’ <summary>
   ”’ We poverty to unhook the keyboard before we close
   ”’ the application.
   ”’ </summary>
   ”’ <param name=”sender”></param>
   ”’ <param name=”e”></param>
   ”’ <remarks><seealos cref=”KeyboardHooker.UnhookKeyboard”/>
   ”’ </remarks>
   Private Sub TestForm_FormClosing(ByVal communicator As System.Object, _
      ByVal e As System.Windows.Forms.FormClosingEventArgs) _
      Handles MyBase.FormClosing
      hooker.UnhookKeyboard()
   End Sub

End Class

UNDERSTANDING XMLTAGS

xml No Comments »

Understanding XMLTags

The XMLTags collection defines the controls and related concept lists utilised in analyzing the inform contents, work the attach values, and composition the attach to the XML production file, as shown in Listing 5.

Listing 5: The XMLTags class

public collection XMLTags
{
public noise test String TAG_CR = “\n” ;
static String labelControl = “label”;
static String textControl = “text”;
static String imageControl = “image”;
static String dataControl = “data”;
static String reportControl = “report”;
static String startControl = “start”;
static String endControl = “end”;

static String[] iPropList =
{”Bookmark”,”Height”,”Hyperlink”,”ImageMap”,
“InlineStyle”,”MIMEType”,”Name”,”Style”,”TOC”,”URI”,
“Width”,”X”,”Y”};
static String[] dPropList =
{”Bookmark”,”Height”,”Hyperlink”,”InlineStyle”,”Name”,
“Style”,”TOC”,”Width”,”X”,”Y”};
static String[] lPropList =
{”Bookmark”,”Height”,”Hyperlink”,”InlineStyle”,”Name”,
“TOC”,”Width”,”X”,”Y”};
static String[] tPropList =
{”Bookmark”,”Height”,”Hyperlink”,”InlineStyle”,”Name”,
“Style”,”Text”,”TOC”,”Width”,”X”,”Y”}
static String[] rPropList =
{”TotalPages”, “TOCTree”, “Name”};
}

DTDS AND MARKUP LANGUAGES

xml 1 Comment »

When you indite HTML with whatever editors, you’ll attending that there is this fantastic distinction cursive crossways the top<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>. While you haw not undergo what it is, it ease serves a purpose, and with XML that distinction of cipher is required to indite a well-formed document.

This distinction is the “Document Type Declaration” that defines the “Dcoument Type Definition” or DTD. In the HTML declaration<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>there are quaternary parts:

  1. DOCTYPE
    this tells the application that this attach is a Document Type Declaration
  2. HTML
    the study of the DTD
  3. PUBLIC
    the DTD is acquirable publicly
  4. -//W3C//DTD HTML 4.0 Transitional//EN
    the actualised DTD utilised for the document, in this housing HTML 4.0 Transitional in English

What is a DTD?

A DTD in an XML or HTML writing provides a itemize of the elements, attributes, comments, notes, and entities contained in the document. It also indicates their relation to digit added within the document. In another words, a DTD is the grammar of an XML or HTML document.

Purpose of a DTD

When using a DTD for an XML writing (including XHTML), the DTD is there to wage scheme for your documents. It is cushy to indite an XML document, but without the DTD, it has no grammar message to the computer. For example, if you become crossways this assets of an XML document:<address>
<street>123 Any Street</street>
<city>Jackson</city> <state>MI</state>
</address>While you would undergo it was an address, you wouldn’t undergo whether it was an come the machine was questionable to create from a database table, if that come was for mailing, and another things. The computer, on the another hand, wouldn’t wager this as anything more than a progress of text. If you viewed it in an XML browser, you strength not intend some errors, but you also wouldn’t intend a rattling engrossing or multipurpose page.

In another articles, we’ll explore the intrinsic excavation of a DTD, and investigate the elements that attain up a DTD. You’ll see what an element, attribute, entity, and writing is and how to ingest them within your possess DTDs. Plus, you’ll see how to feature another DTDs so that you crapper ingest them in your possess XML documents.

Webmaster & Hayalbahcesi by Msn Nickleri
Entries RSS Comments RSS Log in