Saturday, August 20, 2016

How to use JAXB for Unmarshalling

Hello everyone,

Today, I would like to show you how to read and XML using JAXB library.

0-Make sure your project has the library
1- We need to create the object for JAXBContext.
2- We need also to create Unmarshaller objects that will be used to unmarshal method loading the content of the file.




package thiagolguimaraes;

/**
 * @author Thiago leoncio
 *
 *This is JAXB Unmarshalling Example: Converting XML into Object
 *
 *The steps to convert XML document in the java object are:
 *
 *Create POJO or bind the schema and generate the classes
 *Create the JAXBContext object
 *Create the Unmarshaller objects
 *Call the unmarshal method
 *Use getter methods of POJO to access the data
 *
 */
import java.io.File;
import java.util.List;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
 
public class XmlToObject {
    public static void main(String[] args) {
 
     try {
 
        File file = new File("src\\thiagolguimaraes\\question.xml");
       
       
        //Create the JAXBContext object
        JAXBContext jaxbContext = JAXBContext.newInstance(Retrieve.class);
        //Create the Unmarshaller objects
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        //Use getter methods of POJO to access the data
        Retrieve que= (Retrieve) jaxbUnmarshaller.unmarshal(file);
         
        System.out.println(que.getId()+" "+que.getRetrievename());
        System.out.println("Responses:");
        List<Response> list=que.getResponses();
        for(Response ans:list)
          System.out.println(ans.getId()+" "+ans.getResponsename()+"  "+ans.getPostedby());
 
      } catch (JAXBException e) {
        e.printStackTrace();
      }
 
    }
}

---------------------------------------------------------------------------------------------------
/**
 *
 */
package thiagolguimaraes;

/**
 * @author Thiago Leoncio
 *
 */
import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
public class Retrieve {
private int id;
private String questionname;
private List<Response> answers;
public Retrieve() {}
public Retrieve(int id, String questionname, List<Response> answers) {
    super();
    this.id = id;
    this.questionname = questionname;
    this.answers = answers;
}
@XmlAttribute
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
@XmlElement
public String getRetrievename() {
    return questionname;
}
public void setRetrievename(String questionname) {
    this.questionname = questionname;
}
@XmlElement
public List<Response> getResponses() {
    return answers;
}
public void setResponses(List<Response> answers) {
    this.answers = answers;
}
}

---------------------------------------------------------------------------------------------------

/**
 *
 */
package thiagolguimaraes;

/**
 * @author Thiago Leoncio
 *
 */
public class Response {
private int id;
private String answername;
private String postedby;
public Response() {}
public Response(int id, String answername, String postedby) {
    super();
    this.id = id;
    this.answername = answername;
    this.postedby = postedby;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getResponsename() {
    return answername;
}
public void setResponsename(String answername) {
    this.answername = answername;
}
public String getPostedby() {
    return postedby;
}
public void setPostedby(String postedby) {
    this.postedby = postedby;
}
 
}



Happy coding,
Thiago Leoncio.

Saturday, August 6, 2016

How to read a XML file from jar in Java



Hello everyone,


I would like to show you how to find/read a file that comes from a jar(compressed file) and provide the content of this.


Structure of folders and files I have:
File.jar
-->under File.jar there is a folder called zipThiagoFolder that has the xml file named xmlFileNameInJarFile.xml


Source code:

/**
 *
 */
package thiago.leoncio;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.IOUtils;

/**
 * @author Thiago Leoncio
 * @date 08062016
 * Description: provide the details on how to read a XML file from jar or compressed file in Java
 *
 */
public class FindXmlContentInCompressedFile {

/**
* @param args
*/
public static void main(String args[]) {
//relativePath is the file that you are searching inside of the Jar/zip file.
   String relativeFilePath = "zipThiagoFolder/xmlFileNameInJarFile.xml";
   //The zip path is where the compressed files is.
   String zipFilePath = "C:\\codes\\TesterProject\\src\\thiago\\leoncio\\File.jar";
   String contents = readZipFile(zipFilePath,relativeFilePath);
   System.out.println(contents);
}

public static String readZipFile(String zipFilePath, String relativeFilePath) {
   try {
       ZipFile zipFile = new ZipFile(zipFilePath);
       Enumeration<? extends ZipEntry> e = zipFile.entries();
       while (e.hasMoreElements()) {
        System.out.println("[LOG] While it's getting the elements on XML content");
           ZipEntry entry = (ZipEntry) e.nextElement();
         
           // if the entry is not directory and matches relative file then extract it
           if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
            System.out.println("[LOG] Relative Path:"+relativeFilePath);
               BufferedInputStream bis = new BufferedInputStream(
                       zipFile.getInputStream(entry));
               // Read the file
                   // With Apache Commons I/O
               System.out.println("[LOG] Converting in String file using Apache lib[commons-io-2.5.jar] for fileContentsStr var");
                String fileContentsStr = IOUtils.toString(bis, "UTF-8");

                   // With Guava
               //String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
               // close the input stream.
               bis.close();
               return fileContentsStr;
           } else {
               continue;
           }
       }
   } catch (IOException e) {
       e.printStackTrace();
   }
   return null;
}

}


Expected output:

[LOG] While it's getting the elements on XML content
[LOG] While it's getting the elements on XML content
[LOG] Relative Path:zipThiagoFolder/xmlFileNameInJarFile.xml
[LOG] Converting in String file using Apache lib[commons-io-2.5.jar] for fileContentsStr var
<References xmlns="http://xmlns.oracle.com/adf/jndi">
  <Reference name="thiago" className="oracle.jdeveloper.db.adapter.DatabaseProvider" credentialStoreKey="thiago"
             xmlns="">
    <Factory className="oracle.jdevimpl.db.adapter.DatabaseProviderFactory1212"/>
    <RefAddresses>
      <StringRefAddr addrType="oraDriverType">
        <Contents>thin</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="hostname">
        <Contents>clusterd-RacThiagoleoncio</Contents>
      </StringRefAddr>
      <SecureRefAddr addrType="password"/>
      <StringRefAddr addrType="subtype">
        <Contents>oraJDBC</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="port">
        <Contents>3099</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="serviceName">
        <Contents>SIDTESTThiagoLeoncioEnvironment</Contents>
      </StringRefAddr>
      <StringRefAddr addrType="user">
        <Contents>ThiagoLeoncioUser</Contents>
      </StringRefAddr>
    </RefAddresses>
  </Reference>
</References>



Happy coding,
Thiago Leoncio.