A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Cannot install Java JDK: semicolon found in selected path

There's no semi colon in the install path. But you still get the error:

        semicolon found in selected path

Solution is to move the install .exe to c:\ and run it again.

Possibly with command line switches: /v"/L c:\install.log"

(Search results show that this same issue has existed for 11 years!)

URI encoding in Java

Deprecated Apache Commons HttpClient 3.x:
 
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;

String uriTest1(String uri) {
    String encodedUri = null;
    try {
        encodedUri = URIUtil.encodePath(uri,"UTF-8");
    } catch (URIException e) {
        System.err.println("Caught URI Exception");
        e.printStackTrace();
    }
    return encodedUri;
}

URIEncoder encodes to application/x-www-form-urlencoded (i.e. spaces turn to +)

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;

String uriTest2(String uri) {
    String encodedUri = null;
    String encoding = "UTF-8";
    try {
        encodedUri = URLEncoder.encode(uri, encoding);
    } catch (UnsupportedEncodingException e) {
        System.err.println("Unsuported encoding: "+encoding);
        e.printStackTrace();
    }
    return encodedUri;
}

java.net.URI requires the whole URI to be input, but you can extract just the URI encoded query part (turns spaces to %20)

import java.net.URI;

private static String uriTest3(String path) {
    String encodedUri = null;
    URI uri = null;
    try {
        uri = new URI("http","bbc.co.uk","/search/news/",path,null);
    } catch (URISyntaxException e) {
        System.err.println("Caught URI Syntax Exception");
        e.printStackTrace();
    }
    encodedUri = uri.getRawQuery();
    return encodedUri;
}
See also.

Configuring log4j for maven

To debug: Add -Dlog4j.debug to the jvm parameters.

The files log4j.properties or log4j.xml must be on the classpath.

Easily import properties file in JUnit

Pass this parameter to the jvm:
-DPropertyManager.file=/path/to/props.properties

Then in the program:
import junitx.util.PropertyManager; // from http://sourceforge.net/projects/junit-addons/ ?
PropertyManager.getProperty("my.key");

Use DBUnit

Add to the classpath:
  • dbunit-2.4.7
    • slf4j-api-1.6.1
    • slf4j-simple-1.6.1
  • mysql-connector-java-5.0.8

Example program:

    import java.io.FileOutputStream;
    import java.sql.*;
    import org.dbunit.database.*;
    import org.dbunit.dataset.*;
    import org.dbunit.dataset.xml.*;
    // database connection
    Class driverClass = Class.forName("com.mysql.jdbc.Driver");
    Connection jdbcConnection = DriverManager.getConnection("jdbc:mysql://host:port/dbname","user","pass");
    IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
    // prevent error: Potential problem found: The configured data type factory
    // 'class org.dbunit.dataset.datatype.DefaultDataTypeFactory' might cause problems with the current database 'MySQL'
    // (e.g. some datatypes may not be supported properly).
    connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
    // full database export
    IDataSet fullDataSet = connection.createDataSet();
    FlatXmlDataSet.write(fullDataSet, new FileOutputStream("dbname"));
    

    Sprintf in Java

    import java.text.MessageFormat;
    
    int a = 3;
    String b = "coders";
    
    System.out.println(
        MessageFormat.format("{0} Java {1}.", String.format("%04d", a), b)
    );
    
    

    Sample XMLUnit test class

    import java.io.IOException;
    import org.apache.commons.httpclient.*;
    import org.apache.commons.httpclient.methods.*;
    import java.util.HashMap;
    import org.custommonkey.xmlunit.*;

    public class MyTest extends XMLTestCase {
        private HttpClient client;
        private String pageTitle = "something";
      
        protected void setUp() {
             client = new HttpClient();        
            // declare XML namespaces
            HashMap m = new HashMap();
            m.put("agg", "http://www.bbc.co.uk/aggregation/1.0");
            m.put("atom", "http://www.w3.org/2005/Atom");
            NamespaceContext ctx = new SimpleNamespaceContext(m);
            XMLUnit.setXpathNamespaceContext(ctx);
        }

        public void testVersion() throws Exception {
            String pageXML = getXML("http://example.com/version");
            assertXpathEvaluatesTo("2010-07-29", "/version/release-date", pageXML);
        }
      
        public void testTitle() throws Exception {
            String pageXML = getXML("http://example.com/test");
            assertXpathEvaluatesTo("items about "+pageTitle, "/agg:page//atom:feed/atom:title[1]", pageXML);
        }
      
         private String getXML(String uri) throws IOException {
            GetMethod method = new GetMethod(uri);
            int statusCode = client.executeMethod(method);
            assertEquals("HTTP GET " + uri, HttpStatus.SC_OK, statusCode); // 200 OK
            return method.getResponseBodyAsString();
         }

         public void TearDown() {
         }

    }

    Testing XML with Java

    Testing
    • XMLUnit
    • JUnit - most popular

    XML

    with Java
    • Selenium
    • Eclipse
    • Maven + Jetty

    3rd party javadocs in Eclipse

    • Download and unzip the 3rd party package's source
    • Open the Package Explorer view in Eclipse
    • Navigate to [your project] | Referenced libraries | [3rd party library] | right-click | Properties
    • Enter the source directory in the Java Source Attachment | Location path
    There is also a Javadoc Location field that accepts a URL (didn't work for XMLUnit or JUnit though)

    How to run a Selenium/JUnit test

    • Install Eclipse 3.5
    • Download JUnit
    • Download Selenium RC
    • Run java -jar selenium-server-1.0.3/selenium-server.jar
    • Create a Java project in Eclipse
    • Right-click on the project name and go to Properties | Java Build Path | Add External JARs
      • add JUnit JAR
      • all the Selenium Server JARs
      • all the Selenium Java JARs
    • Run a program like this (This one doesn't actually work; the assertion fails)
      package com.example;
      
      import junit.framework.TestCase;
      import com.thoughtworks.selenium.DefaultSelenium;
      import com.thoughtworks.selenium.Selenium;
      
      public class GoogleTest extends TestCase {
       private static Selenium selenium;
       protected void setUp() {
        selenium = new DefaultSelenium("localhost" , 4444 , "*firefox", "http://www.google.com");
        selenium.start();
        selenium.setSpeed("2000");
       }
       public final void testTitle() {
        selenium.open("http://www.google.com");
        selenium.type("//input[@title='Google Search']", "I am using selenium");
        selenium.click("//input[@value = 'Google Search']");
        assertTrue(selenium.isElementPresent("/html/head/title"));
       }
       protected void tearDown() {
        selenium.stop();
       }
      } 

      oXygen Eclipse plugin

      oXygen XML/XSLT: http://www.oxygenxml.com/download_oxygenxml_editor.html#Eclipse
      • it's not all that, but step-through-debugging does work
      • have to manually set the file association defaults to Oxygen types
      • unreadable default colour scheme for Oxygen filetypes. It is difficult to import syntax-highlighting preferences in Eclipse. You're better off setting them yourself.
      • to use step-through debugging, you need to:
        • 'Configure Transformation Scenario' (under XML/XSL menu - it appears when you open an XML or XSL file)
        • open the 'Debug Scenario' perspective in the XML/XSL menu
      • setting the input parameters for debugging is fiddly
      • the XML file being used as input must be "part of the project"

      How to use Saxon XSL 2 processor

      java -jar saxon9he.jar -xsl:/path/to/file.xsl -s:/path/to/file.xml -o:/path/to/output.xml parameter1='value1' parameter2='value2'

      No XSLT2 in PHP

      There is only one known xslt2 processor called SAXON (http://saxon.sourceforge.net/), built by Michael Kay, which was released for the Java and .NET platforms.

      Other XSLT processors, including Sablotron, Xalan and MSXML, have not yet adopted xslt2.

      Kay writes: "implementation [for xslt2 in php] does not exist because no-one has written one". He continues, "The usual workaround I recommend is to implement XSLT 2.0 transformation as a (Java-based or .NET-based) REST web service, and for the php application to submit transformation requests to that web service by means of HTTP requests. An alternative is to use a php-Java bridge"

      Michael Kay manages an email-based discussion group called MulberryTech, a good resource for learning XSLT techniques (both 1 and 2). (http://www.mulberrytech.com/xsl/xsl-list/)


      Cocoon XSLT errors

      java.lang.NullPointerException

      This could mean you've used the wrong attribute name in a tag, e.g.
      <xsl:attribute type="type">
      instead of
      <xsl:attribute name="type">

      There seems to be no syntax checking to warn in cases like this.

      Using Java classes from XSLT under Coocon / JBoss

      Possible MD5 methods:
      <xsl:value-of select="md5:encode('$term')" xmlns:md5="java:org.jboss.security.Base64Encoder" />
      <xsl:value-of select="md5:encodeString($term,'ISO-8859-1')" xmlns:md5="java:org.hsqldb.lib.MD5" />

      Search through built-in classes in JBoss:
      find /path/to/jboss-4.2.2.GA/server/default/ -name "*.jar" -exec jar tf {} \; | grep MD5 -H

      Setting up xemacs xslt-process mode

      I set all these options in the environment:

      #########################
      # copied from /etc/java/java.conf
      # JPackage Project
      #########################
      # Location of jar files on the system
      export JAVA_LIBDIR=/usr/share/java
      # Location of arch-specific jar files on the system
      export JNI_LIBDIR=/usr/lib/java
      # List of known java homes (used for autodetection if none is provided)
      export JAVA_HOME_LIST=$JAVA_LIBDIR-utils/java_home.list
      # Root of all JVM installations
      export JVM_ROOT=/usr/lib/jvm
      # Default jvm
      export JAVA_HOME=$JVM_ROOT/java
      # Options to pass to the java interpreter
      export JAVACMD_OPTS=
      #########################


      export CLASSPATH=/usr/share/java

      Now when I try to run xslt-process, it says:
      Starting the BeanShell. Please wait...

      ...but then straight away it still always says:
      Could not process file, most probably (Xalan1|Saxon) could not be found!

      What I think is happening:
      • xalan-2.4.1.jar is installed, not xalan1 as is required.
      • Not all of saxon's dependencies are installed.