8000 Refactor + Add Logging · codepressed/Java-CSV2XML@6f8a16f · GitHub
[go: up one dir, main page]

Skip to content

Commit 6f8a16f

Browse files
committed
Refactor + Add Logging
1 parent 2ee234a commit 6f8a16f

File tree

7 files changed

+167
-181
lines changed

7 files changed

+167
-181
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,6 @@ artifacts/
1515

1616
# Maven
1717
log/
18-
target/
18+
target/
19+
20+
examples/

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,19 @@
33
* Uses the traditional methodology to generate the xml (without a library), through
44
of nodes and tree structure.
55
* Can read ANY CSV File
6-
* Args are: Input file, output file, element node name and optionally, if you add -s program will read the csv
6+
* Args are:
7+
- [0] Input file
8+
- [1] Output file
9+
- [2] Element node name and optionally,
10+
- [3] -s parameter, if you add it, program will read the csv
711
as semicolon-separated values instead of comma-separated values.
12+
13+
Example of command to compile and run the program for comma-separated values:
14+
```
15+
javac CSV2XML.java
16+
java CSV2XML inputfilePath outputFilePath element -s
17+
```
18+
819
## Project test
920

1021
### CSV Input File
Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,59 @@
11
package com.codepressed.CSVtoXML;
22

3-
import org.apache.commons.lang3.StringUtils;
3+
44
import org.w3c.dom.Document;
55
import javax.xml.parsers.ParserConfigurationException;
66
import javax.xml.transform.TransformerException;
77
import java.io.IOException;
88
import java.util.ArrayList;
9+
import java.util.List;
10+
import java.util.logging.Level;
11+
import java.util.logging.Logger;
12+
913

1014
public class Main {
15+
private static final Logger logger = Logger.getLogger(Main.class.getName());
16+
1117
/**
1218
* Executes the CSV to XML conversion
1319
*
14-
* @param args Input file, output file, elements names and csv type.
15-
* @author Daniel Apesteguia Timoner
20+
* @param args [0] = Input file, [1] = Output file, [2] = Elements names, [3] = csv type.
21+
* @author Daniel Apesteguia Timoner (Codepressed)
1622
*/
1723
public static void main(String[] args) {
24+
1825
//Arg validator
1926
if (args.length == 0) {
20-
System.out.println("You didn't type any args.");
27+
logger.log(Level.SEVERE, "No args were specified.");
2128
System.exit(0);
2229
}
23-
//Vars Initialization
24-
String csvFile = args[0];
25-
String xmlFile = args[1];
26-
String elementName;
27-
String csvSplit = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
28-
29-
try {
30-
elementName = args[2];
31-
} catch (ArrayIndexOutOfBoundsException e) {
32-
System.out.println("You didn't especify any element so we will fix 'element' as parental node.");
33-
elementName = "element";
34-
}
30+
//Vars Initialization
31+
String csvFile = args[0];
32+
String xmlFile = args[1];
33+
String elementName;
34+
String csvSplit = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
3535

36-
try {
37-
if (args[3] == "-s")
38-
csvSplit = ";(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
39-
} catch (ArrayIndexOutOfBoundsException e){
40-
}
36+
try {
37+
elementName = args[2];
38+
} catch (ArrayIndexOutOfBoundsException e) {
39+
logger.log(Level.INFO, "Since you didn't specify a element name, 'element' will be the parental node.");
40+
elementName = "element";
41+
}
4142

42-
try {
43-
ArrayList<String[]> elements;
44-
elements = new Reader().CSVtoArrayList(csvFile, csvSplit);
45-
Document xmlDoc;
46-
xmlDoc = new XMLDoc().docBuilder(elements, elementName);
47-
XMLTransformer.transformDocToFile(xmlDoc, xmlFile);
48-
} catch (IOException e) {
49-
e.printStackTrace();
50-
System.out.println("File wasn't found, error: " + e);
51-
} catch (TransformerException e) {
52-
System.out.println("Transformer error: " + e);
53-
} catch (ParserConfigurationException e) {
54-
System.out.println("Configuration error: " + e);
55-
}
43+
try {
44+
if (args[3] == "-s")
45+
csvSplit = ";(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
46+
} catch (ArrayIndexOutOfBoundsException e){
47+
}
48+
49+
List<String[]> elements;
50+
elements = XMLutils.readCsvFile(csvFile, csvSplit);
51+
Document xmlDoc;
52+
xmlDoc = XMLutils.createXmlDocument(elements, elementName);
53+
XMLutils.writeXmlDocumentToFile(xmlDoc, xmlFile);
54+
}
5655
}
57-
}
56+
57+
58+
5859

src/main/java/com/codepressed/CSVtoXML/Reader.java

Lines changed: 0 additions & 36 deletions
This file was deleted.

src/main/java/com/codepressed/CSVtoXML/XMLDoc.java

Lines changed: 0 additions & 71 deletions
This file was deleted.

src/main/java/com/codepressed/CSVtoXML/XMLTransformer.java

Lines changed: 0 additions & 36 deletions
This file was deleted.
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
package com.codepressed.CSVtoXML;
2+
3+
import org.w3c.dom.Document;
4+
import org.w3c.dom.Element;
5+
import org.w3c.dom.Text;
6+
7+
import javax.xml.parsers.DocumentBuilder;
8+
import javax.xml.parsers.DocumentBuilderFactory;
9+
import javax.xml.parsers.ParserConfigurationException;
10+
import javax.xml.transform.OutputKeys;
11+
import javax.xml.transform.Transformer;
12+
import javax.xml.transform.TransformerException;
13+
import javax.xml.transform.TransformerFactory;
14+
import javax.xml.transform.dom.DOMSource;
15+
import javax.xml.transform.stream.StreamResult;
16+
import java.io.BufferedReader;
17+
import java.io.File;
18+
import java.io.FileOutputStream;
19+
import java.io.IOException;
20+
import java.nio.file.Files;
21+
import java.nio.file.Paths;
22+
import java.util.ArrayList;
23+
import java.util.List;
24+
import java.util.logging.Level;
25+
import java.util.logging.Logger;
26+
27+
public class XMLutils {
28+
29+
private static final Logger logger = Logger.getLogger(XMLutils.class.getName());
30+
31+
public static boolean writeXmlDocumentToFile(Document xmlDoc, String xmlFilePath) {
32+
try {
33+
TransformerFactory xmlTransformerFactory = TransformerFactory.newInstance();
34+
Transformer xmlTransformer = xmlTransformerFactory.newTransformer();
35+
xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
36+
xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
37+
xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
38+
xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
39+
40+
try (FileOutputStream outputStream = new FileOutputStream(new File(xmlFilePath))) {
41+
xmlTransformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream));
42+
}
43+
return true;
44+
} catch (TransformerException | IOException e) {
45+
logger.log(Level.SEVERE, "Error writing xml document to file", e);
46+
return false;
47+
}
48+
}
49+
50+
public static Document createXmlDocument(List<String[]> XMLelements, String elementName) {
51+
if (elementName == null) {
52+
elementName = "element";
53+
}
54+
55+
try {
56+
DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
57+
DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();
58+
Document xmlDoc = xmlBuilder.newDocument();
59+
60+
Element rootElement = xmlDoc.createElement("root");
61+
xmlDoc.appendChild(rootElement);
62+
Element mainElement = xmlDoc.createElement(elementName + "s");
63+
rootElement.appendChild(mainElement);
64+
65+
boolean headerDefined = false;
66+
String[] header = new String[XMLelements.size()];
67+
68+
for (String[] node : XMLelements) {
69+
if (headerDefined) {
70+
Element nodesElements = xmlDoc.createElement(elementName);
71+
mainElement.appendChild(nodesElements);
72+
73+
for (int j = 0; j < node.length; j++) {
74+
node[j] = node[j].replaceAll("\"", "").trim();
75+
Element nodesValues = xmlDoc.createElement(header[j]);
76+
nodesElements.appendChild(nodesValues);
77+
Text nodeTxt = xmlDoc.createTextNode(node[j]);
78+
nodesValues.appendChild(nodeTxt);
79+
}
80+
} else {
81+
header = node;
82+
for (int j = 0; j < node.length; j++) {
83+
header[j] = header[j].replaceAll("[^a-zA-Z0-9]", "");
84+
try {
85+
Integer.parseInt(header[j]);
86+
header[j] = "node" + header[j];
87+
} catch (NumberFormatException e) {
88+
}
89+
}
90+
headerDefined = true;
91+
}
92+
}
93+
return xmlDoc;
94+
} catch (ParserConfigurationException e) {
95+
logger.log(Level.SEVERE, "Error creating the xml document", e);
96+
return null;
97+
}
98+
}
99+
100+
public static List<String[]> readCsvFile(String csvFilePath, String separator) {
101+
List<String[]> elements = new ArrayList<>();
102+
103+
try (BufferedReader reader = Files.newBufferedReader(Paths.get(csvFilePath))) {
104+
String line;
105+
while ((line = reader.readLine()) != null) {
106+
String[] nodes = line.split(separator);
107+
elements.add(nodes);
108+
}
109+
} catch(IOException e){
110+
logger.log(Level.SEVERE, "Error reading the csv file", e);
111+
}
112+
return elements;
113+
}
114+
115+
}

0 commit comments

Comments
 (0)
0