Notes by Dr. Xi
Displaying notes 11 - 20
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 ...
Created by Dr. Xi on June 11, 2010 19:04:18
Last update: June 11, 2010 19:06:35
The caret ^ is DOS command line escape character. Example 1: echo < and > as is, not interpreting them as input/output redirect. @rem sign an XML file. Requires Java class utils.xmlsig.SignXMLFile. @echo off if "%2" == "" goto usage java -Xms256m -Xmx512m utils.xmlsig.SignXMLFile %1 %2 goto end :usage echo Usage: %0 ^<inputFile^> ^<outputFile^> echo. :end Example 2: treat & literally, not as the special character to combine two commands. @rem search "dos command line" in Google. curl http://www.google.com/search?hl=en^&q=dos+command+line -o google.html Add switch -A "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1" to make curl look like Firefox.
Created by Dr. Xi on June 03, 2010 22:43:43
Last update: June 20, 2010 14:13:05
Using the Sun BASE64Encoder : import java.io.*; import sun.misc.BASE64Encoder; public class EncodeFileWithBase64 { public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println("Usage: java EncodeFileWithBASE64 <inputFile> <outputFile>"); return; } String inputFile = args[0]; String outputFile = args[1]; BASE64Encoder encoder = new BASE64Encoder(); encoder.encode( new FileInputStream(inputFile), new FileOutputStream(outputFile) ); } } However, the Sun encoder is awfully slow. The Apache encoder is a lot faster. Here's the code with Apache encoder: import java.io.*; import org.apache.commons.codec.binary.Base64OutputStream; public class EncodeBase64WithApache { public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println("Usage: java EncodeBase64WithApache <inputFile> <outputFile>"); return; } int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; InputStream input = new FileInputStream(args[0]); OutputStream output = new Base64OutputStream(new FileOutputStream(args[1])); int n = ...