Tuesday, April 08, 2014

Accept a CSV input and convert it to XML in ADF

In the previous exercise we have seen how to read a csv file and then how to generate an XMl file.

Now combining the technology of both we will create an ADF page that will accept csv file as input and will generate an XML file as an output.

This code is specific to a particular format and is not a generic code for converting csv file to xml format but it can be manipulate to make a generic tool for converting any csv file to xml.

My input screen looks like



The text in the output text is my result.

It will accept a csv file as input and will generate an XML file in the mentioned location.

The input in my case is as follows



And following is the response document



And following is the code to do the same.

package Login;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.InputStream;

import javax.xml.transform.dom.DOMSource;

import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;

import javax.faces.event.ValueChangeEvent;

import oracle.adf.view.rich.component.rich.input.RichInputFile;
import oracle.adf.view.rich.component.rich.input.RichTextEditor;

import oracle.adf.view.rich.component.rich.output.RichOutputText;

import org.apache.commons.io.IOUtils;
import org.apache.myfaces.trinidad.model.UploadedFile;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CSVTOXML {
private RichInputFile csvInput;

String header = "";
private UploadedFile file;
private InputStream inputstream;
BufferedReader br = null;
String csvData = "";
String SplitBy = ",";
private RichTextEditor textOutput;

public CSVTOXML() {
}

public void setCsvInput(RichInputFile csvInput) {
this.csvInput = csvInput;
}

public RichInputFile getCsvInput() {
return csvInput;
}

public String cb1_action() {
// Add event code here...
try {
System.out.println("Employee Details ");
String header = br.readLine();
System.out.println(header);

DocumentBuilderFactory documentFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder =
documentFactory.newDocumentBuilder();

// define root elements
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Employee");
document.appendChild(rootElement);
String[] elementName = header.split(",");
// int count = 0;


while ((csvData = br.readLine()) != null) {
// // System.out.println(csvData);
String[] employee = csvData.split(SplitBy);

Element subrootElement =
document.createElement("EmployeeDetails");
rootElement.appendChild(subrootElement);

Element empDept =
document.createElement(elementName[0].toString());
empDept.appendChild(document.createTextNode(employee[0].toString()));
subrootElement.appendChild(empDept);

Element firstname =
document.createElement(elementName[1].toString());
firstname.appendChild(document.createTextNode(employee[1].toString()));
subrootElement.appendChild(firstname);

Element lastname =
document.createElement(elementName[2].toString());
lastname.appendChild(document.createTextNode(employee[2].toString()));
subrootElement.appendChild(lastname);

Element empId =
document.createElement(elementName[3].toString());
empId.appendChild(document.createTextNode(employee[3].toString()));
subrootElement.appendChild(empId);

}


TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
StreamResult file =
new StreamResult(new File("C:\\Users\\Token\\Desktop\\Temp\\createFile.xml"));
transformer.transform(domSource, result);
transformer.transform(domSource, file);

String content = result.toString();


String display =
"Data is converted and written to the target directory-C:\\Users\\Token\\Desktop\\Temp File name-createFile.xml";
textOutput.setValue(display);
if (csvInput != null) {
csvInput.resetValue();
//upload.setValid(true);
}
}
// {
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}

return null;
}

public void valueChangeListener(ValueChangeEvent e) {
// Add event code here...
file = (UploadedFile)e.getNewValue();

try {
inputstream = file.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
// br = new BufferedReader(new FileReader(fileData));
//BufferedReader buf = (Reader)inputstream;
// br = new BufferedReader(inputstream);
} catch (IOException z) {
z.printStackTrace();
}
}


public void setTextOutput(RichTextEditor textOutput) {
this.textOutput = textOutput;
}

public RichTextEditor getTextOutput() {
return textOutput;
}
}


As you can see i have manually hardcoded the value

document.createElement(elementName[0].toString());
empDept.appendChild(document.createTextNode(employee[0].toString()));

This can be changed at run time ,Also the parameter to split the document is "," that can also be taken as input and passed at runtime to make it more generic for processing pipe separate or any particular value separated data. A small tweak and you can convert this code to accept any csv input

package Login;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.InputStream;

import javax.xml.transform.dom.DOMSource;

import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;

import javax.faces.event.ValueChangeEvent;

import oracle.adf.view.rich.component.rich.input.RichInputFile;
import oracle.adf.view.rich.component.rich.input.RichTextEditor;

import oracle.adf.view.rich.component.rich.output.RichOutputText;

import org.apache.commons.io.IOUtils;
import org.apache.myfaces.trinidad.model.UploadedFile;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CSVTOXML {
private RichInputFile csvInput;

String header = "";
private UploadedFile file;
private InputStream inputstream;
BufferedReader br = null;
String csvData = "";
String SplitBy = ",";
private RichTextEditor textOutput;

public CSVTOXML() {
}

public void setCsvInput(RichInputFile csvInput) {
this.csvInput = csvInput;
}

public RichInputFile getCsvInput() {
return csvInput;
}

public String cb1_action() {
// Add event code here...
try {
// System.out.println("Employee Details ");
String header = br.readLine();
// System.out.println(header);

DocumentBuilderFactory documentFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder =
documentFactory.newDocumentBuilder();

// define root elements
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Employee");
document.appendChild(rootElement);
String[] elementName = header.split(",");

int count = elementName.length;
// System.out.println("count" + count);


while ((csvData = br.readLine()) != null) {


String[] employee = csvData.split(SplitBy);
String[] finalList = new String[count];
int finalcount=employee.length;
for(int cnt=0;cnt < count;cnt++ ){
if(cnt < employee.length){
finalList[cnt] =employee[cnt];
}
else{
finalList[cnt] = "";
}
}

Element subrootElement =
document.createElement("EmployeeDetails");
rootElement.appendChild(subrootElement);
for (int i = 0; i < count; i++) {
// if (employee[i]==null) {
Element emp =
document.createElement(elementName[i].toString());
emp.appendChild(document.createTextNode(finalList[i].toString()));
subrootElement.appendChild(emp);
// }


}
}


TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
StreamResult file =
new StreamResult(new File("C:\\Users\\arahi\\Desktop\\Temp\\createFile.xml"));
transformer.transform(domSource, result);
transformer.transform(domSource, file);

String content = result.toString();


String display =
"Data is converted and written to the target directory-C:\\Users\\Token\\Desktop\\Temp -File name-createFile.xml";
textOutput.setValue(display);
if (csvInput != null) {
csvInput.resetValue();
//upload.setValid(true);
}
}
// {
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}

return null;
}

public void valueChangeListener(ValueChangeEvent e) {
// Add event code here...
file = (UploadedFile)e.getNewValue();

try {
inputstream = file.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
// br = new BufferedReader(new FileReader(fileData));
//BufferedReader buf = (Reader)inputstream;
// br = new BufferedReader(inputstream);
} catch (IOException z) {
z.printStackTrace();
}
}


public void setTextOutput(RichTextEditor textOutput) {
this.textOutput = textOutput;
}

public RichTextEditor getTextOutput() {
return textOutput;
}
}


The additional logic that we have used here

String[] finalList = new String[count];
int finalcount=employee.length;
for(int cnt=0;cnt < count;cnt++ ){
if(cnt < employee.length){
finalList[cnt] =employee[cnt];
}
else{
finalList[cnt] = "";
}
}

is to create a new list, this is required because when we read one line and the last character is null the java will fail as it will not find the last element in a line hence to skip this error condition we have used this logic to assign null value to blank this , this can be used to have assign another values such as NA to blank values.

No comments: