Example usage for org.jdom2.input SAXBuilder build

List of usage examples for org.jdom2.input SAXBuilder build

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder build.

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

From source file:interfacermi.Traza.java

public void insertarTraza(String hora, String actor, String accion) {

    Document document = null;//  w w  w  .  j ava  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//  w  w w  .  ja  va 2s  . c  om
 */
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.sitespeed.jenkins.xml.impl.XMLToPageJDOM.java

License:Open Source License

public Page get(File pageXML) throws IOException {

    final SAXBuilder b = new SAXBuilder(new XMLReaderSAX2Factory(false));
    Document doc;/*from  ww w  .  j  av  a2 s.c o  m*/
    try {
        doc = b.build(pageXML);
    } catch (JDOMException e) {
        throw new IOException(e);
    }

    int numOfHosts = doc.getRootElement().getChild("g").getChild("ydns").getChild("components")
            .getChildren("item").size();

    String url = doc.getRootElement().getChildText("curl");
    Integer score = new Integer(doc.getRootElement().getChildText("o"));

    return new Page(url, score, getRules(doc), numOfHosts, getAssetsSize(doc), getNumberOfAssets(doc));
}

From source file:io.sitespeed.jenkins.xml.impl.XMLToPageTimingsJDOM.java

License:Open Source License

public PageTimings get(File browserTimeXML) throws IOException {

    final SAXBuilder b = new SAXBuilder(new XMLReaderSAX2Factory(false));
    Document doc;/* www .  j  a  v a2 s .c o  m*/
    try {
        doc = b.build(browserTimeXML);
    } catch (JDOMException e) {
        throw new IOException(e);
    }

    return new PageTimings(getPageData("actualUrl", doc), getPageData("browserName", doc),
            getPageData("browserVersion", doc), doc.getRootElement().getChild("runs").getChildren("run").size(),
            getMeasurements(doc));
}

From source file:io.sitespeed.jenkins.xml.impl.XMLToSummaryJDOM.java

License:Open Source License

public SiteSummary get(File summaryXML) throws IOException {

    final SAXBuilder b = new SAXBuilder(new XMLReaderSAX2Factory(false));
    Document doc;/*www  .  ja v a  2 s . com*/
    try {
        doc = b.build(summaryXML);
    } catch (JDOMException e) {
        throw new IOException(e);
    }

    Map<String, HashMap<String, String>> values = new HashMap<String, HashMap<String, String>>();
    // TODO today the cache time is in seconds, probably should be converted to minutes?
    for (Element metric : doc.getRootElement().getChild("metrics").getChildren()) {
        String name = metric.getName();
        name = fixBrowserKey(name);
        HashMap<String, String> the = new HashMap<String, String>();
        for (Element valueType : metric.getChildren()) {
            the.put(valueType.getName(), valueType.getValue());
        }
        values.put(name, the);
    }

    int pages = new Integer(doc.getRootElement().getChild("pages").getValue());

    return new SiteSummary(values, pages);
}

From source file:io.smartspaces.domain.support.JdomActivityDescriptionReader.java

License:Apache License

@Override
public ActivityDescription readDescription(InputStream activityDescriptionStream) {
    try {/*from   w w w.j av  a2  s  .  c o  m*/
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(activityDescriptionStream);

        Element rootElement = doc.getRootElement();

        ActivityDescription description = new ActivityDescription();

        List<String> errors = new ArrayList<>();

        getMainData(description, rootElement, errors);
        getMetadata(description, rootElement, errors);
        getDependencies(description, rootElement, errors);

        return description;
    } catch (Exception e) {
        throw new SmartSpacesException("Unable to read activity descriptiuon", e);
    }

}

From source file:io.smartspaces.master.server.services.internal.support.JdomMasterDomainModelImporter.java

License:Apache License

/**
 * Parse the description.//  w  ww .ja  va  2s  . c  o  m
 *
 * @param description
 *          the model description
 *
 * @return the root element of the parse
 *
 * @throws SmartSpacesException
 *           if there was an error reading the description
 */
private Element readDescription(String description) throws SmartSpacesException {
    try {
        StringReader reader = new StringReader(description);

        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(reader);

        return doc.getRootElement();
    } catch (Exception e) {
        throw new SmartSpacesException("Unable to read master domain model description", e);
    }
}

From source file:io.smartspaces.workbench.project.jdom.JdomReader.java

License:Apache License

/**
 * Get the root element for a given input file.
 *
 * @param inputFile// w  ww  .  j  ava 2  s .  com
 *          input project file
 *
 * @return top-level element
 */
Element getRootElement(File inputFile) {
    Document doc;
    try {
        SAXBuilder builder = new SAXBuilder();
        builder.setJDOMFactory(new LocatedJDOMFactory());
        builder.setFeature(XML_PARSER_FEATURE_XINCLUDE, true);
        builder.setEntityResolver(new MyEntityResolver());
        doc = builder.build(inputFile);
    } catch (Exception e) {
        throw new SmartSpacesException(
                String.format("Exception while processing %s", inputFile.getAbsolutePath()), e);
    }

    return doc.getRootElement();
}

From source file:io.wcm.handler.richtext.util.RichTextUtil.java

License:Apache License

/**
 * Parses XHTML text string. Adds a wrapping "root" element before parsing and returns this root element.
 * @param text XHTML text string (root element not needed)
 * @param xhtmlEntities If set to true, Resolving of XHtml entities in XHtml fragment is supported.
 * @return Root element with parsed xhtml content
 * @throws JDOMException Is thrown if the text could not be parsed as XHTML
 *//*w w  w.ja va2s.  c  o  m*/
public static Element parseText(String text, boolean xhtmlEntities) throws JDOMException {

    // add root element
    String xhtmlString = (xhtmlEntities ? "<!DOCTYPE root [" + XHTML_ENTITY_DEF + "]>" : "") + "<root>" + text
            + "</root>";

    try {
        SAXBuilder saxBuilder = new SAXBuilder();

        if (xhtmlEntities) {
            saxBuilder.setEntityResolver(XHtmlEntityResolver.getInstance());
        }

        Document doc = saxBuilder.build(new StringReader(xhtmlString));
        return doc.getRootElement();
    } catch (IOException ex) {
        throw new RuntimeException("Error parsing XHTML fragment.", ex);
    }

}

From source file:io.wcm.maven.plugins.contentpackage.unpacker.ContentUnpacker.java

License:Apache License

private void writeXmlWithExcludes(InputStream inputStream, OutputStream outputStream)
        throws IOException, JDOMException {
    SAXBuilder saxBuilder = new SAXBuilder();
    Document doc = saxBuilder.build(inputStream);
    applyXmlExcludes(doc.getRootElement(), "");

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setLineSeparator(LineSeparator.UNIX));
    outputter.setXMLOutputProcessor(new OneAttributePerLineXmlProcessor());
    outputter.output(doc, outputStream);
    outputStream.flush();//from www. j av  a 2 s.c  o m
}