I need help with XML and JSON to improved the code, \"Refactor the code to use d
ID: 3575757 • Letter: I
Question
I need help with XML and JSON to improved the code, "Refactor the code to use design patterns and responsibility patterns a design that is easier to extend and High Cohesion.
import org.json.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
//
// Convert XML content to Product object
//
private static Product convertXMLToProduct(File file) {
try {
// Load file to XML Document object
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new FileReader(file)));
// Find Product name
Node product = document.getElementsByTagName("Product").item(0);
String id = product.getAttributes().getNamedItem("identifier").getTextContent();
// Find Product Id
String name = product.getTextContent();
// Create new product object from XML file
return new Product(name, id);
} catch (Exception e) {
}
return null;
}
private static Product convertJsonToProduct(File file) {
try {
JSONTokener jsonTokener = new JSONTokener(new FileInputStream(file));
JSONObject obj = ((JSONObject) jsonTokener.nextValue()).getJSONObject("product_record");
String name = obj.getString("product_name");
String id = obj.getString("product_id");
return new Product(name, id);
} catch (Exception ex) {
}
return null;
}
//
// List all files in particular folder
//
public static List<String> listFilesForFolder(final File folder) {
List<String> filenames = new ArrayList<>();
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isFile()) {
filenames.add(fileEntry.getAbsolutePath());
}
}
return filenames;
}
public static void main(String[] args) {
// Check parameters
if (args.length <= 0) {
System.out.println("Syntax: java ProductParse file_directory");
return;
}
File f = new File(args[0]);
//If imputed parameter is not directory
if (!f.isDirectory()) {
System.out.println("Syntax: java ProductParse file_directory");
return;
}
List<String> filenames = listFilesForFolder(f);
if (filenames.size() <= 0) {
System.out.println("Folder is empty");
return;
}
List<Product> products = new ArrayList<>();
for (String filename : filenames) {
// Read XML file
Product p = convertXMLToProduct(new File(filename));
if (p != null) {
products.add(p);
continue;
}
// If it is not XML file, try reading with Json format
p = convertJsonToProduct(new File(filename));
if (p != null) {
products.add(p);
continue;
}
// If it is not json format, print error
System.out.println(String.format("%s is invalid format", filename));
}
try {
// Convert List of product to json format
StringWriter strWriter = new StringWriter();
JSONWriter writer = new JSONWriter(strWriter);
writer.object();
writer.key("product_records");
writer.array();
for (Product p : products) {
// Print to console
System.out.println(String.format("%s %s", p.getName(), p.getId()));
writer.object();
writer.key("product_name");
writer.value(p.getName());
writer.endObject();
writer.object();
writer.key("product_id");
writer.value(p.getId());
writer.endObject();
}
writer.endArray();
writer.endObject();
// Write to file
FileWriter ofs = new FileWriter(new File(args[0] + System.getProperty("file.separator") + "output.json"));
ofs.write(strWriter.toString());
ofs.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Explanation / Answer
public class ProductObject { private String pname; private int pid; public String getName() { return pname; } public void setName(String pname) { this.pname = pname; } public void setpid(int pid) { this.pid = pid; } Public int getpid() { Return pid; } import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import java.util.List; public final class Translator { private XStream xstream = null; private Translator(){ xstream = new XStream(); xstream.ignoreUnknownElements(); } public String toXMLString(Object object) { return xstream.toXML(object); } public Object toObject(String xml) { return (Object) xstream.fromXML(xml); } public static Translator getInstance(){ return new Translator(); } public Object toObject(File xmlFile) throws IOException { return xstream.fromXML(new FileReader(xmlFile)); } public void toXMLFile(Object objTobeXMLTranslated, String fileName ) throws IOException { FileWriter writer = new FileWriter(fileName); xstream.toXML(objTobeXMLTranslated, writer); writer.close(); } public void toXMLFile(Object objTobeXMLTranslated, String fileName, List omitFieldsRegXList) throws IOException { xstreamInitializeSettings(objTobeXMLTranslated, omitFieldsRegXList); toXMLFile(objTobeXMLTranslated, fileName); } public void xstreamInitializeSettings(Object objTobeXMLTranslated, List omitFieldsRegXList) { if(omitFieldsRegXList != null && omitFieldsRegXList.size() > 0){ Iterator itr = omitFieldsRegXList.iterator(); while(itr.hasNext()){ String omitEx = itr.next(); xstream.omitField(objTobeXMLTranslated.getClass(), omitEx); } } } public void toXMLFile(Object objTobeXMLTranslated) throws IOException { toXMLFile(objTobeXMLTranslated,objTobeXMLTranslated.getClass().getName()+".xml"); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.