Skip to content

Commit e7c3b53

Browse files
committed
#12 - Java
1 parent 5859932 commit e7c3b53

File tree

1 file changed

+256
-0
lines changed

1 file changed

+256
-0
lines changed
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
import com.fasterxml.jackson.core.JsonProcessingException;
2+
import com.fasterxml.jackson.databind.ObjectMapper;
3+
import org.w3c.dom.Document;
4+
import org.w3c.dom.Element;
5+
import org.w3c.dom.Node;
6+
import org.w3c.dom.NodeList;
7+
import org.xml.sax.SAXException;
8+
9+
import javax.xml.parsers.DocumentBuilder;
10+
import javax.xml.parsers.DocumentBuilderFactory;
11+
import javax.xml.parsers.ParserConfigurationException;
12+
import javax.xml.transform.*;
13+
import javax.xml.transform.dom.DOMSource;
14+
import javax.xml.transform.stream.StreamResult;
15+
import java.io.File;
16+
import java.io.IOException;
17+
import java.nio.file.Files;
18+
import java.util.ArrayList;
19+
import java.util.HashMap;
20+
import java.util.List;
21+
import java.util.Map;
22+
23+
public class Josegs95 {
24+
25+
private static final String XML_FILENAME = "Josegs95.xml";
26+
private static final String JSON_FILENAME = "Josegs95.json";
27+
28+
public static void main(String[] args) {
29+
String name = "Jose";
30+
String age = "29";
31+
String birthdate = "28-02-1995";
32+
33+
List<String> languageList = new ArrayList<>();
34+
languageList.add("Java");
35+
languageList.add("Python");
36+
37+
Map<String, Object> dataMap = new HashMap<>();
38+
dataMap.put("name", name);
39+
dataMap.put("age", age);
40+
dataMap.put("birthdate", birthdate);
41+
dataMap.put("language_list", languageList);
42+
43+
//El reto usa los archivos de los ejercicios XML y JSON, por eso la línea que borra
44+
//los ficheros está comentada.
45+
46+
//XML
47+
exerciseXML(dataMap);
48+
49+
//JSON
50+
exerciseJSON(dataMap);
51+
52+
//Reto
53+
System.out.println("\n");
54+
retoFinal();
55+
}
56+
57+
private static void exerciseXML(Map<String, Object> dataMap){
58+
try {
59+
//Creo el builder
60+
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
61+
DocumentBuilder builder = factory.newDocumentBuilder();
62+
63+
//Obtengo el documento
64+
Document document = builder.newDocument();
65+
66+
//Creo el elemento raiz
67+
Element root = document.createElement("datos");
68+
document.appendChild(root);
69+
70+
//Creo los elementos para insertar los datos y los coloco bajo el elemento raiz
71+
72+
for (Map.Entry<String, Object> entry : dataMap.entrySet()){
73+
Element element = document.createElement(entry.getKey());
74+
Object value = entry.getValue();
75+
if (value instanceof String)
76+
element.appendChild(document.createTextNode((String) value));
77+
else if (value instanceof List<?>){
78+
for (String itemText : ((List<String>) value)){
79+
Element itemElement = document.createElement("language");
80+
itemElement.appendChild(document.createTextNode(itemText));
81+
element.appendChild(itemElement);
82+
}
83+
} else
84+
continue;
85+
86+
root.appendChild(element);
87+
}
88+
89+
//Creo el objeto transformer y lo preparo para escribir el documento con el que hemos trabajado
90+
TransformerFactory transformerFactory = TransformerFactory.newInstance();
91+
Transformer transformer = transformerFactory.newTransformer();
92+
//transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //Para ver de forma mas clara el XML
93+
DOMSource source = new DOMSource(document);
94+
95+
//Escribo en el archivo con la ruta especificada
96+
File xmlFile = new File(XML_FILENAME);
97+
StreamResult result = new StreamResult(xmlFile);
98+
transformer.transform(source, result);
99+
100+
//Leer el XML
101+
102+
//Leemos el archivo de forma normal
103+
String xmlString = new String(Files.readAllBytes(xmlFile.toPath()));
104+
System.out.println(xmlString);
105+
106+
//deleteFile(new File (XML_FILENAME));
107+
} catch (ParserConfigurationException e) {
108+
throw new RuntimeException(e);
109+
} catch (TransformerConfigurationException e) {
110+
throw new RuntimeException(e);
111+
} catch (TransformerException e) {
112+
throw new RuntimeException(e);
113+
} catch (IOException e) {
114+
throw new RuntimeException(e);
115+
}
116+
}
117+
118+
private static void exerciseJSON(Map<String, Object> dataMap){
119+
try {
120+
File jsonFile = new File (JSON_FILENAME);
121+
ObjectMapper objectMapper = new ObjectMapper();
122+
123+
//Escribir en el fichero un mapa en formato JSON
124+
//objectMapper.writeValue(jsonFile, dataMap);
125+
objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, dataMap);
126+
127+
//Recuperar los datos de un JSON y meterlos en un mapa
128+
Map<String, Object> newDataMap = new HashMap<>();
129+
newDataMap = objectMapper.readValue(jsonFile, newDataMap.getClass());
130+
System.out.println(newDataMap);
131+
132+
//deleteFile(jsonFile);
133+
} catch (JsonProcessingException e) {
134+
throw new RuntimeException(e);
135+
} catch (IOException e) {
136+
throw new RuntimeException(e);
137+
}
138+
}
139+
140+
private static void retoFinal(){
141+
//XML
142+
File xmlFile = new File(XML_FILENAME);
143+
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
144+
try {
145+
DocumentBuilder builder = factory.newDocumentBuilder();
146+
Document document = builder.parse(xmlFile);
147+
148+
//document.getDocumentElement().normalize();
149+
String name = document.getElementsByTagName("name").item(0).getTextContent();
150+
String age = document.getElementsByTagName("age").item(0).getTextContent();
151+
String birthdate = document.getElementsByTagName("birthdate").item(0).getTextContent();
152+
List<String> languageList = new ArrayList<>();
153+
154+
Node languagesNode = document.getElementsByTagName("language_list").item(0);
155+
NodeList languagesNodeList = languagesNode.getChildNodes();
156+
for (int i = 0; i < languagesNodeList.getLength(); i++){
157+
Node node = languagesNodeList.item(i);
158+
languageList.add(node.getTextContent());
159+
}
160+
161+
Person personFromXML = new Person(name, age, birthdate, languageList);
162+
System.out.println("Persona XML = " + personFromXML);
163+
} catch (ParserConfigurationException e) {
164+
throw new RuntimeException(e);
165+
} catch (IOException e) {
166+
throw new RuntimeException(e);
167+
} catch (SAXException e) {
168+
throw new RuntimeException(e);
169+
}
170+
171+
//JSON
172+
File jsonFile = new File (JSON_FILENAME);
173+
ObjectMapper objectMapper = new ObjectMapper();
174+
175+
try {
176+
Map<String, Object> dataMap = new HashMap<>();
177+
dataMap = objectMapper.readValue(jsonFile, dataMap.getClass());
178+
179+
String name = (String) dataMap.get("name");
180+
String age = (String) dataMap.get("age");
181+
String birthdate = (String) dataMap.get("birthdate");
182+
List<String> languageList = (List<String>) dataMap.get("language_list");
183+
Person personFromJSON = new Person(name, age, birthdate, languageList);
184+
185+
System.out.println("Persona JSOM = " + personFromJSON);
186+
} catch (IOException e) {
187+
throw new RuntimeException(e);
188+
}
189+
190+
deleteFile(xmlFile);
191+
deleteFile(jsonFile);
192+
}
193+
194+
private static void deleteFile(File file){
195+
if (file.delete())
196+
System.out.println("Se ha borrado el archivo con éxito.");
197+
else
198+
System.out.println("No se ha podido borrar el archivo.");
199+
}
200+
201+
public static class Person{
202+
private String name;
203+
private String age;
204+
private String birthdate;
205+
private List<String> languageList;
206+
207+
public Person(String name, String age, String birthdate, List<String> languageList) {
208+
this.name = name;
209+
this.age = age;
210+
this.birthdate = birthdate;
211+
this.languageList = languageList;
212+
}
213+
214+
public Person(){}
215+
216+
public String getName() {
217+
return name;
218+
}
219+
220+
public void setName(String name) {
221+
this.name = name;
222+
}
223+
224+
public String getAge() {
225+
return age;
226+
}
227+
228+
public void setAge(String age) {
229+
this.age = age;
230+
}
231+
232+
public String getBirthdate() {
233+
return birthdate;
234+
}
235+
236+
public void setBirthdate(String birthdate) {
237+
this.birthdate = birthdate;
238+
}
239+
240+
public List<String> getLanguageList() {
241+
return languageList;
242+
}
243+
244+
public void setLanguageList(List<String> languageList) {
245+
this.languageList = languageList;
246+
}
247+
248+
@Override
249+
public String toString() {
250+
return "Nombre: " + name +
251+
", Edad: " + age +
252+
", Fecha de nacimiento: " + birthdate +
253+
", Lista de lenguajes: " + languageList;
254+
}
255+
}
256+
}

0 commit comments

Comments
 (0)