List of usage examples for org.jdom2.input SAXBuilder SAXBuilder
public SAXBuilder()
From source file:hintahaku.HintahakuFrame.java
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed //Avaa//from ww w .j a v a2 s. c o m Path viimeisin = Asetukset.getViimeisinKokoonpanoKansio(); JFileChooser valitsin = new JFileChooser(viimeisin == null ? null : viimeisin.toFile()); valitsin.setFileFilter(new FileNameExtensionFilter("Kokoonpanot (xml)", "xml")); int valinta = valitsin.showOpenDialog(rootPane); if (valinta != JFileChooser.APPROVE_OPTION) { return; } Path avattava = valitsin.getSelectedFile().toPath(); Asetukset.setViimeisinKokoonpanoKansio(avattava.getParent()); org.jdom2.Document xml; try (BufferedReader reader = Files.newBufferedReader(avattava)) { xml = new SAXBuilder().build(reader); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Tiedoston avaaminen eponnistui!", "Virhe!", JOptionPane.ERROR_MESSAGE); return; } catch (JDOMException ex) { JOptionPane.showMessageDialog(null, "Avattu tiedosto ei ole kokoonpano!", "Virhe!", JOptionPane.ERROR_MESSAGE); return; } Element juuri = xml.getRootElement(); if (!"Tallennettu Hintahaku-kokoonpano".equals(juuri.getAttributeValue("info"))) { JOptionPane.showMessageDialog(null, "Avattu tiedosto ei ole kokoonpano!", "Virhe!", JOptionPane.ERROR_MESSAGE); return; } String vanhaTeksti = jLabel11.getText(); jLabel11.setText("Haetaan kokoonpanon hintatietoja..."); new SwingWorker<List<RaakaTuote>, Void>() { @Override protected List<RaakaTuote> doInBackground() throws Exception { List<RaakaTuote> lista = new ArrayList<>(); Pattern urlPattern = Pattern.compile("http://hinta\\.fi/\\d+"); for (Element tuoteEl : juuri.getChildren()) { String url = tuoteEl.getChildText("url"); int maara = Integer.parseInt(tuoteEl.getChildText("mr")); if (!urlPattern.matcher(url).matches() || maara <= 0) { throw new KokoonpanoTiedostoException(); } Document dok; try { dok = Jsoup.connect(url).userAgent(USERAGENT).get(); } catch (HttpStatusException ex) { //Tuotetta ei ole en olemassa dok = null; } lista.add(new RaakaTuote(url, dok, maara)); } return lista; } @Override protected void done() { List<RaakaTuote> lista; try { lista = get(); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(null, "Tuntematon virhe!", "Virhe!", JOptionPane.ERROR_MESSAGE); jLabel11.setText(vanhaTeksti); return; } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof IOException) { JOptionPane.showMessageDialog(null, "Ohjelma ei saa yhteytt hinta.fi-palvelimeen!", "Virhe!", JOptionPane.ERROR_MESSAGE); } else if (cause instanceof NumberFormatException || cause instanceof KokoonpanoTiedostoException) { JOptionPane.showMessageDialog(null, "Avattu tiedosto on virheellinen!", "Virhe!", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Tuntematon virhe!", "Virhe!", JOptionPane.ERROR_MESSAGE); } jLabel11.setText(vanhaTeksti); return; } List<KokoonpanoTuote> lisattavat = new ArrayList<>(); for (RaakaTuote raakaTuote : lista) { if (raakaTuote.dok == null) { Object[] napit = { "Poista tuote", "l nyt" }; int valinta = JOptionPane.showOptionDialog(null, "<html>Tuotetta ei lydy en hinta.fi:st:<br><b>" + raakaTuote.url + "</b><br><br>Haluatko poistaa tuotteen tiedostosta, vai jtt sen vain nyttmtt kokoonpanossa? (Tallentaminen poistaa silti.)", "Varmistus", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, napit, napit[1]); if (valinta == JOptionPane.YES_OPTION) { Iterator<Element> xmlIter = juuri.getChildren().iterator(); while (xmlIter.hasNext()) { Element tuoteEl = xmlIter.next(); if (raakaTuote.url.equals(tuoteEl.getChildText("url"))) { xmlIter.remove(); break; } } try (BufferedWriter writer = Files.newBufferedWriter(avattava)) { new XMLOutputter(Format.getPrettyFormat()).output(xml, writer); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Tuotteen poistaminen eponnistui, joten se jtetn tiedostoon!", "Virhe!", JOptionPane.ERROR_MESSAGE); } } } else { Tuote tuote = new Tuote(raakaTuote.url, raakaTuote.dok); if (tuote.getParasHinta() == null) { Object[] napit = { "Poista tuote", "Jt kokoonpanoon" }; int valinta = JOptionPane.showOptionDialog(null, "<html>Tuotetta ei ole saatavilla en yhdesskn kaupassa:<br><b>" + tuote.getNimi() + "</b><br><br>Haluatko poistaa tuotteen tiedostosta?", "Varmistus", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, napit, napit[1]); if (valinta == JOptionPane.YES_OPTION) { Iterator<Element> xmlIter = juuri.getChildren().iterator(); while (xmlIter.hasNext()) { Element tuoteEl = xmlIter.next(); if (tuote.getUrl().equals(tuoteEl.getChildText("url"))) { xmlIter.remove(); break; } } try (BufferedWriter writer = Files.newBufferedWriter(avattava)) { new XMLOutputter(Format.getPrettyFormat()).output(xml, writer); continue; //Keskeytetn tuotteen lisminen } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Tuotteen poistaminen eponnistui, joten se jtetn tiedostoon!", "Virhe!", JOptionPane.ERROR_MESSAGE); } } } lisattavat.add(new KokoonpanoTuote(tuote, raakaTuote.maara)); } } Kokoonpano.tyhjennaJaLisaaMonta(lisattavat); Kokoonpano.setTiedosto(avattava); paivitaKokoonpanonTulos(); paivitaLisattyMaara(); jLabel11.setText("Avattu: " + avattava.getFileName().toString()); jButton7.setEnabled(false); } }.execute(); }
From source file:hintahaku.Suodattimet.java
public static void vaihda(Path tiedosto) throws IOException, JDOMException, SuodatinTiedostoException { Document xml;/* w ww .j a va 2 s. c o m*/ try (BufferedReader reader = Files.newBufferedReader(tiedosto)) { xml = new SAXBuilder().build(reader); } Element juuri = xml.getRootElement(); if (!"Hintahaku-suodattimet".equals(juuri.getAttributeValue("info"))) { throw new SuodatinTiedostoException(); } tapahtumatPaalla = false; Set<Kauppa> tiedostossa = new HashSet<>(); for (Element kauppaxml : juuri.getChildren()) { String kaupanNimi = kauppaxml.getChildText("nimi"); if (kaupanNimi != null) { boolean voiNoutaa = Boolean.parseBoolean(kauppaxml.getChildText("voiNoutaa")); boolean suodataPois = Boolean.parseBoolean(kauppaxml.getChildText("suodataPois")); Kauppa haettuKauppa = haeKauppa(kaupanNimi); if (haettuKauppa == null) { Kauppa uusiKauppa = new Kauppa(kaupanNimi, voiNoutaa, suodataPois); lisaaKauppa(uusiKauppa); tiedostossa.add(uusiKauppa); } else { haettuKauppa.setVoiNoutaa(voiNoutaa); haettuKauppa.setSuodataPois(suodataPois); tiedostossa.add(haettuKauppa); } } } for (Kauppa kauppa : kaupatEventList) { if (!tiedostossa.contains(kauppa)) { kauppa.setVoiNoutaa(false); kauppa.setSuodataPois(false); } } tapahtumatPaalla = true; pcs.firePropertyChange("suodattimet", null, null); Suodattimet.tiedosto = tiedosto; }
From source file:information.Information.java
License:Open Source License
private static void leerDatos() { java.io.File archivo = new java.io.File(informationPath); SAXBuilder saxBuilder = new SAXBuilder(); try {/*from w w w . j a v a2 s.c o m*/ Document documento = saxBuilder.build(archivo); Element raiz = documento.getRootElement(); List<Element> elementosSalon = raiz.getChildren("Salon"); for (Element salone : elementosSalon) { Salon salon = new Salon(salone.getAttributeValue("Nombre")); List<Element> elementosSala = salone.getChildren("Sala"); for (Element salae : elementosSala) { Room sala = new Room(salae.getAttributeValue("Nombre"), Boolean.parseBoolean(salae.getAttributeValue("Horizontal")), Integer.parseInt(salae.getAttributeValue("SufijoIP"))); List<Element> elementosFila = salae.getChildren("Fila"); for (Element filae : elementosFila) { Row fila = new Row(sala.isHorizontal()); List<Element> elementosEquipo = filae.getChildren("Equipo"); for (Element equipoe : elementosEquipo) { ServerComputer equipo = new ServerComputer(sala); equipo.setComputerNumber(Integer.parseInt(equipoe.getAttributeValue("Numero"))); equipo.setIP(equipoe.getChildText("IP")); equipo.setMac(equipoe.getChildText("Mac")); equipo.setHostname(equipoe.getChildText("Hostname")); List<Element> elementosEjecucion = equipoe.getChildren("Ejecucion"); for (Element ejecucione : elementosEjecucion) { String[] resultado = { ejecucione.getAttributeValue("Orden"), ejecucione.getAttributeValue("Resultado") }; equipo.addResult(resultado); } fila.addComputer(equipo); } sala.addRow(fila); } salon.addRoom(sala); } salons.add(salon); } } catch (JDOMException ex) { Logger.getLogger(Information.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Information.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:insa.h4401.utils.DocumentFactory.java
/** * Creates a MapDocument object from the given File object * * @param file file to interpret as a MapDocument * @return null if the given file doesn't exists or is a directory */// w ww. ja v a2s .co m public static MapDocument createMapDocument(File file) { // Reset factory error DocumentFactory.error = null; // Create MapDocument MapDocument mapdoc = null; if (file.exists() && !file.isDirectory()) { SAXBuilder builder = new SAXBuilder(); try { Document document = builder.build(file); mapdoc = new MapDocument(document); } catch (IOException | JDOMException ex) { DocumentFactory.error = "Invalid XML file"; } } else { DocumentFactory.error = "File is not a regular file"; } return mapdoc; }
From source file:insa.h4401.utils.DocumentFactory.java
/** * Creates a PlanningDocument object from the given File object * * @param file file to interpret as a PlanningDocument * @return a planningDocument//from w w w .java2 s .co m */ public static PlanningDocument createPlanningDocument(File file) { // Reset factory error DocumentFactory.error = null; // Create a PlanningDocument PlanningDocument plandoc = null; if (file.exists() && !file.isDirectory()) { SAXBuilder builder = new SAXBuilder(); try { Document document = builder.build(file); plandoc = new PlanningDocument(document); } catch (IOException | JDOMException ex) { DocumentFactory.error = "Invalid XML file"; } } else { DocumentFactory.error = "File is not a regular file"; } return plandoc; }
From source file:instanceXMLParser.Instance.java
public void buildINstanceJDom(String path) { //creating JDOM SAX parser SAXBuilder builder = new SAXBuilder(); //reading XML document Document xml = null;//from www . jav a2s.c om try { xml = builder.build(new File(path)); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //getting root element from XML document Element root = xml.getRootElement(); List<Element> list = root.getChildren(); for (Element element : list) { List<Element> list1; if (element.getName().equals("board")) { list1 = element.getChildren(); for (Element element2 : list1) { if (element2.getName().equals("size_n")) {//size of the space size_n = Integer.parseInt(element2.getText()); } else if (element2.getName().equals("size_m")) {//size of the space size_m = Integer.parseInt(element2.getText()); //inizializzo matrice solo dop aver letto le due dimensioni //NOTA CHE SIZE_M E SIZE_N devono essere i primi elementi e in quell ordine! boardState = new CellLogicalState[size_n][size_m]; for (int j = 0; j < size_n; j++) { for (int k = 0; k < size_m; k++) { boardState[j][k] = new CellLogicalState(); } } } else if (element2.getName().equals("tile_state")) {//tile states int x, y, value; CellLogicalState state = new CellLogicalState(); String stateString; x = Integer.parseInt(element2.getAttribute("x").getValue()); y = Integer.parseInt(element2.getAttribute("y").getValue()); stateString = element2.getText(); if (stateString.equals("obstacle")) { state.setLocState(LocationState.Obstacle); } else if (stateString.equals("dirty")) { state.setLocState(LocationState.Dirty); value = 1; if (element2.getAttribute("value").getValue() != null) { value = Integer.parseInt(element2.getAttribute("value").getValue()); } state.setDirtyAmount(value); } boardState[x][y] = state; } } } else if (element.getName().equals("agent")) {//agent List<Element> list3 = element.getChildren(); for (Element element3 : list3) { if (element3.getName().equals("x")) { agentPos.setX(Integer.parseInt(element3.getValue())); } else if (element3.getName().equals("y")) { agentPos.setY(Integer.parseInt(element3.getValue())); } else if (element3.getName().equals("energy")) { energy = Double.parseDouble(element3.getValue()); } } } else if (element.getName().equals("base")) {//agent List<Element> list3 = element.getChildren(); for (Element element3 : list3) { if (element3.getName().equals("x")) { basePos.setX(Integer.parseInt(element3.getValue())); } else if (element3.getName().equals("y")) { basePos.setY(Integer.parseInt(element3.getValue())); } } } else if (element.getName().equals("action_costs")) {//agent List<Element> list3 = element.getChildren(); for (Element element3 : list3) { if (element3.getName().equals("up") || element3.getName().equals("left") || element3.getName().equals("down") || element3.getName().equals("right") || element3.getName().equals("suck")) { actionCosts.put(element3.getName(), Double.parseDouble(element3.getValue())); } } } } }
From source file:interfacermi.Traza.java
public void insertarTraza(String hora, String actor, String accion) { Document document = null;//from w w w .j av a 2 s . c o m Element root = null; File xmlFile = new File("Traza.xml"); //Se comprueba si el archivo XML ya existe o no. if (xmlFile.exists()) { FileInputStream fis; try { fis = new FileInputStream(xmlFile); SAXBuilder sb = new SAXBuilder(); document = sb.build(fis); //Si existe se obtiene su nodo raiz. root = document.getRootElement(); fis.close(); } catch (JDOMException | IOException e) { e.printStackTrace(); } } else { //Si no existe se crea su nodo raz. document = new Document(); root = new Element("Traza"); } //Se crea un nodo Hecho para insertar la informacin. Element nodohecho = new Element("Hecho"); //Se crea un nodo hora para insertar la informacin correspondiente a la hora. Element nodohora = new Element("Hora"); //Se crea un nodo actor para insertar la informacin correspondiente al actor. Element nodoactor = new Element("Actor"); //Se crea un nodo accion para insertar la informacin correspondiente a la accin. Element nodoaccion = new Element("Accion"); //Se asignan los valores enviados para cada nodo. nodohora.setText(hora); nodoactor.setText(actor); nodoaccion.setText(accion); //Se aade el contenido al nodo Hecho. nodohecho.addContent(nodohora); nodohecho.addContent(nodoactor); nodohecho.addContent(nodoaccion); //Se aade el nodo Hecho al nodo raz. root.addContent(nodohecho); document.setContent(root); //Se procede a exportar el nuevo o actualizado archivo de traza XML XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); try { xmlOutput.output(document, new FileWriter("Traza.xml")); } catch (IOException e) { e.printStackTrace(); } }
From source file:io.LoadSave.java
License:Open Source License
/** * loads a .oger file//from www . j a v a2 s . co m */ public static void load() { ParticipantTableModel tableModel = ParticipantTableModel.getInstance(); RoomTreeModel slotModel = RoomTreeModel.getInstance(); if (!Main.isSaved()) { // current game must be saved int saveResult = JOptionPane.showOptionDialog(null, "Mchten Sie vorher speichern?", "Speichern?", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); if (saveResult == JOptionPane.YES_OPTION) { save(); } } Document document = new Document(); Element root = new Element("root"); SAXBuilder saxBuilder = new SAXBuilder(); // Dialog to choose the oger file to parse JFileChooser fileChoser = new JFileChooser(".xml"); fileChoser.setFileFilter(new OgerDialogFilter()); int result = fileChoser.showOpenDialog(null); switch (result) { case JFileChooser.APPROVE_OPTION: try { // clear models tableModel.clear(); slotModel.clear(); // Create a new JDOM document from a oger file File file = fileChoser.getSelectedFile(); document = saxBuilder.build(file); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Fehler beim Parsen der Datei!"); } // Initialize the root Element with the document root Element try { root = document.getRootElement(); } catch (NullPointerException e) { JOptionPane.showMessageDialog(null, "Fehler beim Parsen der Datei!"); } // participants Element participantsElement = root.getChild("allParticipants"); for (Element participant : participantsElement.getChildren("participant")) { String firstName = participant.getAttributeValue("firstName"); String lastName = participant.getAttributeValue("lastName"); String mail = participant.getAttributeValue("mail"); int group = Integer.parseInt(participant.getAttributeValue("group")); Participant newParticipant = new Participant(firstName, lastName, mail, group); tableModel.addParticipant(newParticipant); } // slots final DateFormat dateFormat = new SimpleDateFormat("dd.MM.yy"); final DateFormat timeFormat = new SimpleDateFormat("HH:mm"); boolean parseFailed = false; Element slotsElement = root.getChild("Slots"); for (Element slotElement : slotsElement.getChildren("Slot")) { Date date = null; Date beginTime = null; Date endTime = null; try { date = dateFormat.parse(slotElement.getAttributeValue("Date")); } catch (ParseException e) { JOptionPane.showMessageDialog(null, "Konnte Slot-Datum nicht parsen", "Datum nicht erkannt", JOptionPane.ERROR_MESSAGE); parseFailed = true; } try { beginTime = timeFormat.parse(slotElement.getAttributeValue("Begin")); } catch (ParseException e) { JOptionPane.showMessageDialog(null, "Konnte Slot-Angfangszeit nicht parsen", "Anfangszeit nicht erkannt", JOptionPane.ERROR_MESSAGE); parseFailed = true; } try { endTime = timeFormat.parse(slotElement.getAttributeValue("End")); } catch (ParseException e) { JOptionPane.showMessageDialog(null, "Konnte Slot-Endzeit nicht parsen", "Endzeit nicht erkannt", JOptionPane.ERROR_MESSAGE); parseFailed = true; } if (!parseFailed) { Slot slot = new Slot(date, beginTime, endTime); SlotNode newSlotNode = new SlotNode(); newSlotNode.setUserObject(slot); ((DefaultMutableTreeNode) RoomTreeModel.getInstance().getRoot()).add(newSlotNode); // Rooms Element roomsElement = slotElement.getChild("AllRooms"); for (Element roomElement : roomsElement.getChildren("Room")) { parseFailed = false; String roomString = roomElement.getAttributeValue("ID"); Date roomBeginTime = null; Date roomEndTime = null; Boolean hasBeamer = false; String hasBeamerString = roomElement.getAttributeValue("Beamer"); if (hasBeamerString.equals("false")) { hasBeamer = false; } else if (hasBeamerString.equals("true")) { hasBeamer = true; } else { JOptionPane.showMessageDialog(null, "Beamer nicht erkannt", "Beamer nicht erkannt", JOptionPane.ERROR_MESSAGE); parseFailed = true; } try { roomBeginTime = timeFormat.parse(roomElement.getAttributeValue("Begin")); } catch (ParseException e) { JOptionPane.showMessageDialog(null, "Konnte Slot-Angfangszeit nicht parsen", "Anfangszeit nicht erkannt", JOptionPane.ERROR_MESSAGE); parseFailed = true; } try { roomEndTime = timeFormat.parse(roomElement.getAttributeValue("End")); } catch (ParseException e) { JOptionPane.showMessageDialog(null, "Konnte Slot-Endzeit nicht parsen", "Endzeit nicht erkannt", JOptionPane.ERROR_MESSAGE); parseFailed = true; } if (!parseFailed) { Room room = new Room(roomString, hasBeamer, roomBeginTime, roomEndTime); RoomNode newRoomNode = new RoomNode(); newRoomNode.setUserObject(room); newSlotNode.add(newRoomNode); Gui.getRoomTree().updateUI(); } } Gui.getRoomTree().updateUI(); } } } }
From source file:io.macgyver.plugin.ci.jenkins.JenkinsClientImpl.java
License:Apache License
@Override public org.jdom2.Document getJobConfig(String jobName) { try {/*from w w w . jav a2 s . com*/ io.macgyver.okrest3.OkRestResponse rr = target.path("job").path(jobName).path("config.xml").get() .execute(); return new SAXBuilder().build(rr.response().body().byteStream()); } catch (IOException | JDOMException e) { throw new OkRestWrapperException(e); } }
From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java
License:Apache License
protected Element parseXmlResponse(Response response, String method) { try {/* w ww . ja v a 2 s . co m*/ Document d = new SAXBuilder().build(response.body().charStream()); return d.getRootElement(); } catch (IOException | JDOMException e) { throw new ElbException(e); } }