utility Posts

[Java] Generate XML From XSD using xjc

For example i have an xsd, and i want to generate an XML based on it using java. This is my xsd example, and i save it as “my.xsd”

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="http://tempuri.org/PurchaseOrderSchema.xsd"
           targetNamespace="http://tempuri.org/PurchaseOrderSchema.xsd"
           elementFormDefault="qualified">
 <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>
 <xsd:complexType name="PurchaseOrderType">
  <xsd:sequence>
   <xsd:element name="ShipTo" type="tns:USAddress" maxOccurs="2"/>
   <xsd:element name="BillTo" type="tns:USAddress"/>
  </xsd:sequence>
  <xsd:attribute name="OrderDate" type="xsd:date"/>
 </xsd:complexType>

 <xsd:complexType name="USAddress">
  <xsd:sequence>
   <xsd:element name="name"   type="xsd:string"/>
   <xsd:element name="street" type="xsd:string"/>
   <xsd:element name="city"   type="xsd:string"/>
   <xsd:element name="state"  type="xsd:string"/>
   <xsd:element name="zip"    type="xsd:integer"/>
  </xsd:sequence>
  <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
 </xsd:complexType>
</xsd:schema>

Next step is generate java bean using xjc using below command

xjc -p com.edw.bean my.xsd

And it will gives below output,

parsing a schema...
compiling a schema...
com\edw\bean\ObjectFactory.java
com\edw\bean\PurchaseOrderType.java
com\edw\bean\USAddress.java
com\edw\bean\package-info.java

Import those generated java files, and print a simple xml on console based on it.

package com.edw;

import com.edw.bean.ObjectFactory;
import com.edw.bean.PurchaseOrderType;
import com.edw.bean.USAddress;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeFactory;
import java.math.BigInteger;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main().doSomething();
    }

    private void doSomething() throws Exception {
        PurchaseOrderType purchaseOrderType = new PurchaseOrderType();
        USAddress address = new USAddress();
        address.setCity("aaa");
        address.setCountry("US");
        address.setName("cccc");
        address.setState("dddd");
        address.setStreet("eee");
        address.setZip(BigInteger.ONE);

        purchaseOrderType.setBillTo(address);
        purchaseOrderType.getShipTo().add(address);
        purchaseOrderType.setOrderDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(new Date().toInstant().toString()));

        JAXBElement<PurchaseOrderType> element = new ObjectFactory().createPurchaseOrder(purchaseOrderType);
        toXml(element);
    }

    private void toXml(JAXBElement<PurchaseOrderType> element) throws Exception {
        JAXBContext ctx = JAXBContext.newInstance(PurchaseOrderType.class);
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(element, System.out);
    }
}

It will print below output,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PurchaseOrder xmlns="http://tempuri.org/PurchaseOrderSchema.xsd" OrderDate="2019-11-11Z">
    <ShipTo country="US">
        <name>cccc</name>
        <street>eee</street>
        <city>aaa</city>
        <state>dddd</state>
        <zip>1</zip>
    </ShipTo>
    <BillTo country="US">
        <name>cccc</name>
        <street>eee</street>
        <city>aaa</city>
        <state>dddd</state>
        <zip>1</zip>
    </BillTo>
</PurchaseOrder>

Final step is we can validate our generated xml with provided xsd, and see whether generated xml is valid.

Google+

A Simple Thousand Separator using Java

Trying to create a quick and simple solution for formatting an Integer into a formatted string with thousand separator,

	class Main
	{
		public static void main (String[] args) throws java.lang.Exception
		{
			String s = (String.format("%,d", 10000000)).replace(",",".");
			System.out.println(s);
		}
	}

The output will be, 10.000.000. (H)

Google+

[nginx] Replacing HTTP 302 Location URL from HTTP to HTTPS

Had this weird problem today, i can login to my web if i access it directly, but unable to do it if my website is on an iframe of another web. I found out that it happen because im using SSL on both of my website (on the iframe) and the iframe parent’s website.

It actually happen because when im successfully login on my iframed-website, it will gives http 302 (Moved Temporarily) to my dashboard page. But somehow the 302 location is not an HTTPS page, it will gives a regular HTTP pages instead. Which is not a problem when im accessing my web directly, but will gives problem when accessed using an iframe website.

The solution is quite simple, using nginx “proxy_redirect” will change my 302 page from HTTP into HTTPS.

proxy_redirect http:// https://;

Hope it helps :)

Google+

Error on Swagger 2 using Springfox – Request processing failed; nested exception is java.lang.IndexOutOfBoundsException: Index: 1

Had this very weird error, somehow it never happens before.

org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/test] threw exception [org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IndexOutOfBoundsException: Index: 1] with root cause
 java.lang.IndexOutOfBoundsException: Index: 1
	at java.util.Collections$EmptyList.get(Collections.java:3212)
	at springfox.documentation.swagger2.mappers.ModelMapper.typeOfValue(ModelMapper.java:129)
	at springfox.documentation.swagger2.mappers.ModelMapper.mapProperties(ModelMapper.java:92)
	at springfox.documentation.swagger2.mappers.ModelMapper.mapModels(ModelMapper.java:67)
	at springfox.documentation.swagger2.mappers.ModelMapper.modelsFromApiListings(ModelMapper.java:205)
	at springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl.mapDocumentation(ServiceModelToSwagger2MapperImpl.java:50)
	at springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(Swagger2Controller.java:82)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)

This is my pom.xml content,

		<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
 
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>        

The solution is quite easy, upgrading into version 2.6.1 solve my problem.

Google+

SSLHandshakeException When Connecting to Let’s Encrypt CA SSL

Found this weird error when connecting to a HTTPS website, using apache commons httpclient.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Very weird because i can connect to almost every other HTTPS website, but only one website causing this exception. After googling for a while, i found a very interesting solution from MKYong, that is to register the website’s certificate on my JVM.

http://www.mkyong.com/webservices/jax-ws/suncertpathbuilderexception-unable-to-find-valid-certification-path-to-requested-target/

Run this command to generate a new jssecacerts file,

c:\>java InstallCert localhost:443

The only difference is the location where i downloaded InstallCert.java, i downloaded it from this link.

https://github.com/OopsMouse/java-use-examples/blob/master/src/com/aw/ad/util/InstallCert.java

And i also removed the file’s package name, to make it easier to run.

Google+