Notes by Dr. Xi
Displaying notes 1 - 10
Created by Dr. Xi on July 29, 2010 18:46:57
Last update: July 29, 2010 18:48:15
This is an example of using java.beans.XMLEncoder and java.beans.XMLDecoder to serialize/deserialize Java objects to XML. Java code TestXMLEncoder.java: import java.io.*; import java.beans.XMLEncoder; import java.beans.XMLDecoder; public class TestXMLEncoder { public static void main(String[] args) throws Exception { TestXMLEncoder t = new TestXMLEncoder(); t.testSimpleBean(); t.testCompositeBean(); t.testNoDefaultConstructor(); } private void testSimpleBean() throws Exception { System.out.println("Testing simple bean"); File simpleBeanXml = new File("simplebean.xml"); SimpleBean b = new SimpleBean(); b.setName("Java"); encodeObject(b, simpleBeanXml); SimpleBean b2 = (SimpleBean) decodeObject(simpleBeanXml); System.out.println("Retrieved: " + b2); System.out.println(); } private void testCompositeBean() throws Exception { System.out.println("Testing composite bean"); File compositeBeanXml = new File("compositebean.xml"); CompositeBean b = new CompositeBean(); SimpleBean s = new SimpleBean(); s.setName("Nested"); b.setS(s); encodeObject(b, compositeBeanXml); CompositeBean b2 = (CompositeBean) decodeObject(compositeBeanXml); System.out.println("Retrieved: " + b2); System.out.println(); } private void testNoDefaultConstructor() throws Exception { System.out.println("Testing noDefaultConstructor"); ...
Created by Dr. Xi on July 27, 2010 20:49:12
<?xml version="1.0"?> <project name="Ant input task example" default="all" basedir="."> <target name="all" depends="doit,don't"/> <target name="doit" depends="user-input" if="confirmed"> <echo>Task performed</echo> </target> <target name="don't" depends="user-input" unless="confirmed"> <echo>Task NOT performed</echo> </target> <target name="user-input"> <input validargs="y,n" addproperty="user-response"> Do you really want to do this? </input> <condition property="confirmed"> <equals arg1="y" arg2="${user-response}"/> </condition> </target> </project>
Created by Dr. Xi on July 21, 2010 22:14:53
This is a Java program to test XPATH expressions with namespace option. It's been tested with JDK1.6. import java.io.FileInputStream; import java.util.Iterator; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.*; import javax.xml.xpath.*; import javax.xml.namespace.NamespaceContext; import org.w3c.dom.*; public class XPathExample { public static void main(String[] args) throws Exception { if (args.length < 2) { usage(); return; } String inputFile = args[0]; String xPathStr = args[1]; // optional namespace spec: xmlns:prefix:URI String nsPrefix = null; String nsUri = null; if ((args.length >= 3) && args[2].startsWith("xmlns:")) { String[] nsDef = args[2].substring("xmlns:".length()).split("="); if (nsDef.length == 2) { nsPrefix = nsDef[0]; nsUri = nsDef[1]; } } // Parse XML to DOM DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); Document doc = dbFactory .newDocumentBuilder() .parse(new FileInputStream(inputFile)); // Find nodes by XPATH XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = ...
Created by Dr. Xi on July 19, 2010 21:58:34
Last update: July 23, 2010 21:37:23
Parsing XML in Java is really simple: import java.io.*; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class DOMParserExample { public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: java DOMParserExample <xmlFileName>"); return; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); InputStream in = new FileInputStream(args[0]); Document doc = factory.newDocumentBuilder().parse(in); in.close(); System.out.println("DOM doc: " + doc); System.out.println("DOM doc class: " + doc.getClass().getName()); } } The parser implementation details are hidden behind the JAXP API. In case you want to know which parser implementation is used, this is what the JavaDoc for DocumentBuilderFactory.newInstance says: Use the javax.xml.parsers.DocumentBuilderFactory system property. Use the properties file " lib/jaxp.properties " in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the ...
Created by Dr. Xi on June 20, 2010 14:35:17
This XML signature validator comes from the Apache XML Security project. It validates the signature according to the core validation processing rules . It does not verify that the key used to generate the signature is a trusted key. You can override the KeySelector class to make sure that the signing key is from a trusted store. import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dom.*; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.*; import java.io.FileInputStream; import java.security.*; import java.security.interfaces.*; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; /** * This is a simple example of validating an XML * Signature using the JSR 105 API. It assumes the key needed to * validate the signature is contained in a KeyValue KeyInfo. */ public class ValidateXMLSig { // ...
Created by Dr. Xi on June 19, 2010 04:34:01
Last update: June 19, 2010 04:39:13
Java SE 6 contains built-in utilities to generate XML signatures. This is an example that generates XML signatures using a Java keystore. It has options to generate signature for the whole document, for an element with a specific ID, or for elements matched by an XPATH expression. The XML document used to test is taken from Getting Started with XML Security : <?xml version="1.0"?> <PatientRecord> <Name>John Doe</Name> <Account id="acct">123456</Account> <Visit date="10pm March 10, 2002"> <Diagnosis>Broken second metacarpal</Diagnosis> </Visit> </PatientRecord> This is the Java code: import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.security.*; import java.security.cert.X509Certificate; import java.util.*; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dom.*; import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.keyinfo.*; import javax.xml.crypto.dsig.spec.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import org.w3c.dom.*; /** * Sign XML file. ...
Created by Dr. Xi on June 18, 2010 15:43:27
Last update: June 20, 2010 13:59:57
I got this error while starting jboss-5.1.0.GA on Solaris (there were no problems on Windows XP or Linux). 18:20:57,405 ERROR [AbstractKernelController] Error installing to Instantiated: name=AttachmentStore state=Described java.lang.IllegalArgumentException: Wrong arguments. new for target java.lang. reflect.Constructor expected=[java.net.URI] actual=[java.io.File] at org.jboss.reflect.plugins.introspection.ReflectionUtils.handleErrors( ReflectionUtils.java:395) at org.jboss.reflect.plugins.introspection.ReflectionUtils.newInstance(R eflectionUtils.java:153) at org.jboss.reflect.plugins.introspection.ReflectConstructorInfoImpl.ne wInstance(ReflectConstructorInfoImpl.java:106) at org.jboss.joinpoint.plugins.BasicConstructorJoinPoint.dispatch(BasicC onstructorJoinPoint.java:80) at org.jboss.aop.microcontainer.integration.AOPConstructorJoinpoint.crea teTarget(AOPConstructorJoinpoint.java:282) at org.jboss.aop.microcontainer.integration.AOPConstructorJoinpoint.disp atch(AOPConstructorJoinpoint.java:103) at org.jboss.kernel.plugins.dependency.KernelControllerContextAction$Joi npointDispatchWrapper.execute(KernelControllerContextAction.java:241) at org.jboss.kernel.plugins.dependency.ExecutionWrapper.execute(Executio nWrapper.java:47) at org.jboss.kernel.plugins.dependency.KernelControllerContextAction.dis patchExecutionWrapper(KernelControllerContextAction.java:109) It turned out that this was a bug in jboss-5.1.0.GA and was fixed in jboss 6. The fix was to add class="java.io.File" to conf/bootstrap/profile.xml : <bean name="AttachmentStore" class="org.jboss.system.server.profileservice.repository.AbstractAttachmentStore"> <constructor> <parameter class="java.io.File"> <inject bean="BootstrapProfileFactory" property="attachmentStoreRoot"/> </parameter> </constructor> <property name="mainDeployer"> <inject bean="MainDeployer" /> </property> <property name="serializer"> <inject bean="AttachmentsSerializer" /> </property> <property name="persistenceFactory"> <inject bean="PersistenceFactory" /> </property> </bean>
Created by Dr. Xi on June 16, 2010 21:24:38
More arguments than format specifiers (place holders) are allowed but not vise versa. public class TestStringFormat { public static void main(String[] args) { System.out.println(String.format("%s", "a", "b", "c")); System.out.println(String.format("%s%s", "a", "b", "c")); System.out.println(String.format("%s%s%s", "a", "b", "c")); System.out.println(String.format("%s%s%s%s", "a", "b", "c")); } }
Created by Dr. Xi on June 16, 2010 16:06:51
The + operator which is used in Java to concatenate strings does not work in JSP. In JSP, you simply string them together without the + operator. <!DOCTYPE html> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <html> <head> <title>Test Page</title> </head> <body> <c:set var="majorVersion" value="1"/> <c:set var="minorVersion" value="03"/> Full version: <c:out value="${majorVersion}.${minorVersion}"/> <br> <c:set var="fullVersion" value="${majorVersion}.${minorVersion}"/> <c:if test="${'1.03' == fullVersion}"> Can't use concatenation directly in test condition, set variable fullVersion first! </c:if> </body> </html>
Created by Dr. Xi on June 11, 2010 23:11:59
Last update: June 11, 2010 23:14:02
Given a simple XML file like this: <?xml version="1.0"?> <root id="1"> <node id="12"> <text id="123">Some garbage.</text> </node> </root> Calling Document.getElementById returns null (surprisingly!): import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; public class TestGetElementById { public static void main(String[] args) throws Exception { String id = "123"; if (args.length > 0) { id = args[0]; } DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); System.out.println("Is Validating: " + domFactory.isValidating()); domFactory.setNamespaceAware(true); DocumentBuilder docBuilder = domFactory.newDocumentBuilder(); Document doc = docBuilder.parse("simple.xml"); Node n = doc.getElementById(id); if (n == null) { System.out.println("Failed to find node for id: " + id); } else { System.out.println("Found node: " + n); } } } In fact the JavaDoc says something along the lines that getElementById returns the Element that has an ID attribute with the given value. An ...