Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, June 28, 2014

Java - Install a Java Development Kit (JDK) on Windows

java logo
Java is a computer programming language that is concurrent, class-based and object-oriented. It was originally developed by James Gosling at Sun Microsystems. Java applications are typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. Java is currently owned by the Oracle Corporation which acquired Sun Microsystems in 2010. Following tutorial will show you how to setup and configure Java on your computer so you can develop and run Java code.

JDK Install

Java can be downloaded from the Oracle Java download page. There are a number of different download packages available, for this tutorial we will be installing Java Standard Edition (SE) on Windows. In order to be able to compile Java code we need the Java Development Kit (JDK) package that comes with a Java compiler. The JDK package also comes with a Java runtime environment (JRE) that is needed to run compiled Java code.

For this tutorial we will use an older Java version which can be obtained by scrolling all the way down to the bottom of the page and clicking on the Previous Releases - Java Archive link. Look for the Java SE 6 link and after clicking on it select Java SE Development Kit 6u45. Accept the License Agreement and pick the correct download for your operating system. In this example we will use the Windows x64 version.

jdk download page

Sign in using your Oracle account (or create a new one) and the download should start. Once the download is complete, locate the 'jdk-6u45-windows-x64.exe' file and double click to run the installer.

jdk installer welcome

Click Next and on the following screen optionally change the installation location by clicking on the Change... button. In the example below the install location was change to 'C:\Java\jdk1.6.0_45'. From now on we will refer to this directory as: [java_install_dir].

jdk installer installation path

Click Next and then Close after the installer successfully finished installing Java.

jdk installer complete

JDK Configuration

In order for Java applications to be able to run we need to setup a JAVA_HOME environment variable that will point to the Java installation directory. In addition if we want to run Java commands from a command prompt we need to setup the PATH environment variable to contain the Java bin directory.

When using Windows the above parameters can be configured on the Environment Variables panel. Click on the Windows Start button and enter "env" without quotes as shown below.

edit environment variables for your account

Environment variables can be set at account level or at system level. For this example click on Edit environment variables for your account and following panel should appear.

environment variables panel

Click on the New button and enter "JAVA_HOME" as variable name and the [java_install_dir] as variable value. In this tutorial the installation directory is "C:\Java\jdk1.6.0_45". Click OK to to save.

java_home user variable

Click on the New button and enter "PATH" as variable name and "%JAVA_HOME%\bin" as variable value. Click OK to save.
Note that in case a PATH variable is already present you can add ";%JAVA_HOME%\bin" at the end of the variable value.
edit path variable value

The result should be as shown below. Click OK to close the environment variables panel.

environment variables panel jdk configuration

In order to test the above configuration, open a command prompt by clicking on the Windows Start button and typing "cmd" followed by pressing ENTER. A new command prompt should open in which the following command can be entered to verify the installed Java version:

java -version
The result should be as shown below.

jdk version command


This concludes the setting up and configuring Java. If you found this post helpful or have any questions or remarks, please leave a comment.

Wednesday, July 31, 2013

JAXB - Unmarshal an XML String

jaxb logo
When trying to unmarshal an XML to a Java object using JAXB you might want to pass the XML as a String. However the unmarshal() method of the Unmarshaller interface does not support passing an XML String. Following code sample illustrates how to solve this.


Wrap the XML String in a StringReader object and pass this to the unmarshal() method as shown below:

public static Car unmarshal(String xml) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader(xml);
Car car = (Car) jaxbUnmarshaller.unmarshal(reader);

LOGGER.info(car.toString());
return car;
}

Pass below string representation of an XML to the above unmarshal() method.

xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" "
+ "standalone=\"yes\"?>"
+ "<ns2:Car xmlns:ns2=\"info.source4code.jaxb.model\" id=\"ABC-123\">"
+ "<make>Passat</make>"
+ "<manufacturer>Volkswagen</manufacturer></ns2:Car>";

JAXB is now able to unmarshal the StringReader object and the result is the following:

Car [make=Passat, manufacturer=Volkswagen, id=ABC-123]


github icon
If you would like to run the above code sample you can download the full source code and their corresponding JUnit test cases here.

This concludes the unmarshal an XML String code example. If you found this post helpful or have any questions or remarks, please leave a comment.

Tuesday, July 30, 2013

JAXB - Marshal & Unmarshal with missing @XmlRootElement annotation

jaxb logo
Information on the root XML element is required when 'marshalling to' or 'unmarshalling from' a Java object. JAXB provides this information via the @XmlRootElement annotation which contains the name and namespace of the root XML element. When trying to marshal or unmarshal a class which does not have a @XMLRootElement annotation defined, an error will be thrown. One way to solve this problem would be by changing the class and adding the @XMLRootElement annotation. In case the class cannot be altered, another solution is to wrap the root object in an instance of JAXBElement. Following code sample illustrates how to implement this.


For this example let’s use following class representing a car with a simple structure. Note that a XmlRootElement is not defined!
package info.source4code.jaxb.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

public class Car {

private String make;
private String manufacturer;
private String id;

public String getMake() {
return make;
}

@XmlElement
public void setMake(String make) {
this.make = make;
}

public String getManufacturer() {
return manufacturer;
}

@XmlElement
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}

public String getId() {
return id;
}

@XmlAttribute
public void setId(String id) {
this.id = id;
}

public String toString() {
return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
+ ", id=" + id + "]";
}
}

Marshal when @XMLRootElement is missing

Marshalling is the process of transforming the memory representation of an object to a data format suitable for storage or transmission. In the case of JAXB it means converting a Java object into XML. The below code snippet shows the creation of a new Car instance.
        car = new Car();
car.setMake("Passat");
car.setManufacturer("Volkswagen");
car.setId("ABC-123");

The method below takes as input the above car object and tries to marshal it using JAXB.
    public static String marshalError(Car car) throws JAXBException {
StringWriter stringWriter = new StringWriter();

JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// format the XML output
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(car, stringWriter);

String result = stringWriter.toString();
LOGGER.info(result);
return result;
}

When running the above method, the runtime returns an error as the Car class is missing the required @XMLRootElement annotation.
unable to marshal type "info.source4code.jaxb.model.Car" as an
element because it is missing an @XmlRootElement annotation

In order to be able to marshal the car object we need to provide a root XML element. This is done as shown below by first creating a qualified name which contains the name and namespace of the root XML element. In a next step we create a new JAXBElement and pass the qualified name, class and object. Using the created JAXBElement we call the marshal() method.
    public static String marshal(Car car) throws JAXBException {
StringWriter stringWriter = new StringWriter();

JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// format the XML output
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

QName qName = new QName("info.source4code.jaxb.model", "car");
JAXBElement<Car> root = new JAXBElement<Car>(qName, Car.class, car);

jaxbMarshaller.marshal(root, stringWriter);

String result = stringWriter.toString();
LOGGER.info(result);
return result;
}

This time JAXB is able to successfully marshal the object and the result is the following:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:car id="ABC-123" xmlns:ns2="info.source4code.jaxb.model">
<make>Passat</make>
<manufacturer>Volkswagen</manufacturer>
</ns2:car>

Unmarshal when @XMLRootElement is missing

Unmarshalling in JAXB is the process of converting XML content into a Java object.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:car id="DEF-456" xmlns:ns2="info.source4code.jaxb.model">
<make>Golf</make>
<manufacturer>Volkswagen</manufacturer>
</ns2:car>

In the method below we pass the above XML file and try to unmarshal it to an instance of the Car class.
    public static Car unmarshalError(File file) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

Car car = (Car) jaxbUnmarshaller.unmarshal(file);

LOGGER.info(car.toString());
return car;
}

When running the above code, the runtime returns an error as a root XML element is found (the XML has a root element) but the Car class does not define a @XMLRootElement and as such it is not expected.
unexpected element (uri:"info.source4code.jaxb.model", local:"car").
Expected elements are (none)

In order to be able to unmarshal the object we need to define a root XML element. This is done as shown below by first manually creating the root JAXBElement of type Car by using the XML file and the class we are trying to unmarshal to. Then we create a Car object and assign the value of the previous created root JAXBElement.
    public static Car unmarshal(File file) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

JAXBElement<Car> root = jaxbUnmarshaller.unmarshal(new StreamSource(
file), Car.class);
Car car = root.getValue();

LOGGER.info(car.toString());
return car;
}

This time JAXB is able to successfully unmarshal the object and the result is the following:
Car [make=Golf, manufacturer=Volkswagen, id=DEF-456]


github icon
If you would like to run the above code sample you can download the full source code and their corresponding JUnit test cases here.

This concludes the marshal & unmarshal with missing @XmlRootElement annotation code sample. If you found this post helpful or have any questions or remarks, please leave a comment.