Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:de.rallye.api.LandingPage.java

License:Open Source License

private void replaceKgRooms(Document doc, String groupsCode) {
    List<Element> days = doc.getRootElement().getChild("days").getChildren("day");
    for (Element day : days) {
        String dateStr = formatDate(day.getChildText("heading"));

        List<Element> events = day.getChild("events").getChildren("event");
        for (Element event : events) {
            if (event.getChildText("type").equals("kleingruppe")) {

                String locCode = event.getChildText("location");
                RoomCode code = roomCodeMap.get(locCode);
                if (code == null)
                    continue;

                String room = "Kleingruppe";
                if (groupsCode != null) {
                    char ch = groupsCode.charAt(code.digit);
                    int groupIdx = Character.getNumericValue(ch);

                    room = code.rooms.get(groupIdx);
                }// w w  w  .  ja va  2  s.c  o  m

                event.getChild("location").removeContent();
                event.getChild("location").addContent(room);
            }
        }
    }
}

From source file:de.rallye.api.LandingPage.java

License:Open Source License

@GET
@Produces("text/calendar")
@Path("timetable/{groupsCode}.ics")
@Template(name = "/calendar")
public List<Event> getCalendar(@PathParam("groupsCode") String groupsCode) throws JDOMException, IOException {
    try {/*from w  w  w .j  a va2s  .co  m*/
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));

        Document doc = new SAXBuilder()
                .build(StadtRallye.class.getResourceAsStream("timetable/stundenplan.xml"));
        replaceKgRooms(doc, groupsCode);

        List<Event> result = new ArrayList<>();

        List<Element> days = doc.getRootElement().getChild("days").getChildren("day");
        for (Element day : days) {
            String dateStr = formatDate(day.getChildText("heading"));

            List<Element> events = day.getChild("events").getChildren("event");
            for (int i = 0; i < events.size(); i++) {
                Element event = events.get(i);

                if (event.getChildText("type").equals("spacer"))
                    continue;

                Time startT = Time.fromString(event.getChildText("starttime"));
                String start = startT.toString();

                Time endT = new Time(20, 200);
                if (i < events.size() - 1) {
                    Element next = events.get(i + 1);
                    String endStr = next.getChildText("starttime");
                    endT = Time.fromString(endStr);

                    endT = endT.subtractMinutes(10);
                } else {
                    float dur = Float.parseFloat(event.getChildText("duration")) * 55;
                    endT = startT.addMinutes((int) dur);
                }

                String title = event.getChildText("title");
                String titleR = title.replace("&amp;", "&");

                Event e = new Event(year + dateStr + "T" + start + "00",
                        year + dateStr + "T" + endT.toString() + "00", titleR, event.getChildText("location"));
                result.add(e);
            }
        }

        return result;
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.smartics.maven.plugin.jboss.modules.parser.ModulesXmlParser.java

License:Apache License

/**
 * Parses the given document from the stream.
 *
 * @param systemId the identifier of the XML document for error handling and
 *          link resolution./*ww w .  j a  v a  2 s .c  o m*/
 * @param input the stream to parse the modules XML document.
 * @return the descriptors found in a given document.
 * @throws NullPointerException if {@code input} or {@code systemId} is
 *           <code>null</code>.
 * @throws IllegalArgumentException if {@code systemId} is blank.
 * @throws JDOMException when errors occur in parsing
 * @throws IOException when an I/O error prevents a document from being fully
 *           parsed
 */
public ModulesDescriptor parse(final String systemId, final InputStream input)
        throws NullPointerException, IllegalArgumentException, JDOMException, IOException {
    final Document document = builder.build(Arg.checkNotNull("input", input),
            Arg.checkNotBlank("systemId", systemId));

    ModulesDescriptor rc = null;
    if (document.getRootElement().getNamespace() == ModulesDescriptorBuilderV2.NS) {
        rc = new ModulesDescriptorBuilderV2(systemId, document).build();
    } else {
        rc = new ModulesDescriptorBuilder(systemId, document).build();
    }
    // System.out.println("Loaded: "+rc+"\n");
    return rc;
}

From source file:de.smartics.maven.plugin.jboss.modules.xml.XmlFragmentParser.java

License:Apache License

/**
 * Parses the given XML fragment.//  ww  w  .ja  va2 s  .c o  m
 *
 * @param xmlFragment the fragment to be parsed in UTF-8 encoding.
 * @return the parsed root element.
 * @throws IllegalArgumentException on any parsing problem.
 */
public Element parse(final String xmlFragment) throws IllegalArgumentException {
    try {
        final InputStream input = IOUtils.toInputStream(xmlFragment, "UTF-8");
        final Document document = builder.build(input);
        final Element root = document.getRootElement();
        return root.detach();
    } catch (final IOException e) {
        throw new IllegalStateException("UTF-8 encoding not supported on this platform.");
    } catch (final JDOMException e) {
        throw new IllegalArgumentException("Cannot parse XML fragment: " + xmlFragment, e);
    }
}

From source file:de.sub.goobi.config.DigitalCollections.java

License:Open Source License

public static List<String> possibleDigitalCollectionsForProcess(Process process)
        throws JDOMException, IOException {

    List<String> result = new ArrayList<String>();
    String filename = ConfigurationHelper.getInstance().getConfigurationFolder()
            + "goobi_digitalCollections.xml";
    if (!Files.exists(Paths.get(filename))) {
        throw new FileNotFoundException("File not found: " + filename);
    }/*from ww w.  j a va  2  s. c om*/

    /* Datei einlesen und Root ermitteln */
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(filename);
    Element root = doc.getRootElement();
    /* alle Projekte durchlaufen */
    List<Element> projekte = root.getChildren();
    for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
        Element projekt = iter.next();
        List<Element> projektnamen = projekt.getChildren("name");
        for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
            Element projektname = iterator.next();

            /*
             * wenn der Projektname aufgefhrt wird, dann alle Digitalen Collectionen in die Liste
             */
            if (projektname.getText().equalsIgnoreCase(process.getProjekt().getTitel())) {
                List<Element> myCols = projekt.getChildren("DigitalCollection");
                for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                    Element col = it2.next();
                    result.add(col.getText());
                }
            }
        }
    }
    return result;
}

From source file:de.sub.goobi.config.DigitalCollections.java

License:Open Source License

public static String getDefaultDigitalCollectionForProcess(Process process) throws JDOMException, IOException {

    String filename = ConfigurationHelper.getInstance().getConfigurationFolder()
            + "goobi_digitalCollections.xml";
    if (!Files.exists(Paths.get(filename))) {
        throw new FileNotFoundException("File not found: " + filename);
    }// w ww .ja  v a 2s .c  om

    String firstCollection = "";

    /* Datei einlesen und Root ermitteln */
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(filename);
    Element root = doc.getRootElement();
    /* alle Projekte durchlaufen */
    List<Element> projekte = root.getChildren();
    for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
        Element projekt = iter.next();
        List<Element> projektnamen = projekt.getChildren("name");
        for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
            Element projektname = iterator.next();

            /*
             * wenn der Projektname aufgefhrt wird, dann alle Digitalen Collectionen in die Liste
             */
            if (projektname.getText().equalsIgnoreCase(process.getProjekt().getTitel())) {
                List<Element> myCols = projekt.getChildren("DigitalCollection");
                for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                    Element col = it2.next();
                    String collectionName = col.getText();
                    String defaultCollection = col.getAttributeValue("default");
                    if (defaultCollection.equalsIgnoreCase("true")) {
                        return collectionName;
                    }
                    if (StringUtils.isBlank(firstCollection)) {
                        firstCollection = collectionName;
                    }
                }
            }
        }
    }
    return firstCollection;
}

From source file:de.sub.goobi.forms.MassImportForm.java

License:Open Source License

/**
 * generate a list with all possible collections for given project
 *///w  w  w .  j  av  a  2 s. c o  m

private void initializePossibleDigitalCollections() {
    this.possibleDigitalCollection = new ArrayList<>();
    ArrayList<String> defaultCollections = new ArrayList<>();
    String filename = this.help.getGoobiConfigDirectory() + "goobi_digitalCollections.xml";
    if (!StorageProvider.getInstance().isFileExists(Paths.get(filename))) {
        Helper.setFehlerMeldung("File not found: ", filename);
        return;
    }
    this.digitalCollections = new ArrayList<>();
    try {
        /* Datei einlesen und Root ermitteln */
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(filename);
        Element root = doc.getRootElement();
        /* alle Projekte durchlaufen */
        List<Element> projekte = root.getChildren();
        for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
            Element projekt = iter.next();

            // collect default collections
            if (projekt.getName().equals("default")) {
                List<Element> myCols = projekt.getChildren("DigitalCollection");
                for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                    Element col = it2.next();

                    if (col.getAttribute("default") != null
                            && col.getAttributeValue("default").equalsIgnoreCase("true")) {
                        digitalCollections.add(col.getText());
                    }

                    defaultCollections.add(col.getText());
                }
            } else {
                // run through the projects
                List<Element> projektnamen = projekt.getChildren("name");
                for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
                    Element projektname = iterator.next();
                    // all all collections to list
                    if (projektname.getText().equalsIgnoreCase(this.template.getProjekt().getTitel())) {
                        List<Element> myCols = projekt.getChildren("DigitalCollection");
                        for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                            Element col = it2.next();

                            if (col.getAttribute("default") != null
                                    && col.getAttributeValue("default").equalsIgnoreCase("true")) {
                                digitalCollections.add(col.getText());
                            }

                            this.possibleDigitalCollection.add(col.getText());
                        }
                    }
                }
            }
        }
    } catch (JDOMException e1) {
        log.error("error while parsing digital collections", e1);
        Helper.setFehlerMeldung("Error while parsing digital collections", e1);
    } catch (IOException e1) {
        log.error("error while parsing digital collections", e1);
        Helper.setFehlerMeldung("Error while parsing digital collections", e1);
    }

    if (this.possibleDigitalCollection.size() == 0) {
        this.possibleDigitalCollection = defaultCollections;
    }
}

From source file:de.sub.goobi.forms.ProzesskopieForm.java

License:Open Source License

private void initializePossibleDigitalCollections() {
    this.possibleDigitalCollection = new ArrayList<>();
    ArrayList<String> defaultCollections = new ArrayList<>();

    String filename = this.help.getGoobiConfigDirectory() + "goobi_digitalCollections.xml";
    if (!StorageProvider.getInstance().isFileExists(Paths.get(filename))) {
        Helper.setFehlerMeldung("File not found: ", filename);
        return;//  w w w  . ja v  a 2 s. c  o  m
    }
    this.digitalCollections = new ArrayList<>();
    try {
        /* Datei einlesen und Root ermitteln */
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(filename);
        Element root = doc.getRootElement();
        /* alle Projekte durchlaufen */
        List<Element> projekte = root.getChildren();
        for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
            Element projekt = iter.next();

            // collect default collections
            if (projekt.getName().equals("default")) {
                List<Element> myCols = projekt.getChildren("DigitalCollection");
                for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                    Element col = it2.next();

                    if (col.getAttribute("default") != null
                            && col.getAttributeValue("default").equalsIgnoreCase("true")) {
                        digitalCollections.add(col.getText());
                    }

                    defaultCollections.add(col.getText());
                }
            } else {
                // run through the projects
                List<Element> projektnamen = projekt.getChildren("name");
                for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
                    Element projektname = iterator.next();
                    // all all collections to list
                    if (projektname.getText().equalsIgnoreCase(this.prozessKopie.getProjekt().getTitel())) {
                        List<Element> myCols = projekt.getChildren("DigitalCollection");
                        for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                            Element col = it2.next();

                            if (col.getAttribute("default") != null
                                    && col.getAttributeValue("default").equalsIgnoreCase("true")) {
                                digitalCollections.add(col.getText());
                            }

                            this.possibleDigitalCollection.add(col.getText());
                        }
                    }
                }
            }
        }
    } catch (JDOMException e1) {
        logger.error("error while parsing digital collections", e1);
        Helper.setFehlerMeldung("Error while parsing digital collections", e1);
    } catch (IOException e1) {
        logger.error("error while parsing digital collections", e1);
        Helper.setFehlerMeldung("Error while parsing digital collections", e1);
    }

    if (this.possibleDigitalCollection.size() == 0) {
        this.possibleDigitalCollection = defaultCollections;
    }

    // if only one collection is possible take it directly

    if (isSingleChoiceCollection()) {
        this.digitalCollections.add(getDigitalCollectionIfSingleChoice());
    }
}

From source file:de.sub.goobi.helper.HelperSchritte.java

License:Open Source License

public static void extractMetadata(Path metadataFile, Map<String, List<String>> metadataPairs) {
    SAXBuilder builder = new SAXBuilder();
    Document doc;
    try {/*from w  ww .jav  a 2s  .  com*/
        doc = builder.build(metadataFile.toString());
    } catch (JDOMException | IOException e1) {
        return;
    }
    Element root = doc.getRootElement();
    try {
        Element goobi = root.getChildren("dmdSec", mets).get(0).getChild("mdWrap", mets)
                .getChild("xmlData", mets).getChild("mods", mods).getChild("extension", mods)
                .getChild("goobi", goobiNamespace);
        List<Element> metadataList = goobi.getChildren();
        addMetadata(metadataList, metadataPairs);
        for (Element el : root.getChildren("dmdSec", mets)) {
            if (el.getAttributeValue("ID").equals("DMDPHYS_0000")) {
                Element phys = el.getChild("mdWrap", mets).getChild("xmlData", mets).getChild("mods", mods)
                        .getChild("extension", mods).getChild("goobi", goobiNamespace);
                List<Element> physList = phys.getChildren();
                addMetadata(physList, metadataPairs);
            }
        }
        // create field for "DocStruct"
        String docType = root.getChildren("structMap", mets).get(0).getChild("div", mets)
                .getAttributeValue("TYPE");
        metadataPairs.put("DocStruct", Collections.singletonList(docType));

    } catch (Exception e) {
        logger.error(e);
        logger.error("Cannot extract metadata from " + metadataFile.toString());
    }
}

From source file:de.sub.goobi.helper.tasks.ProcessSwapInTask.java

License:Open Source License

/**
 * Aufruf als Thread ================================================================
 *///from w w  w.j a  va  2  s . c  om
@SuppressWarnings("deprecation")
@Override
public void run() {
    setStatusProgress(5);
    String swapPath = null;
    //      ProzessDAO dao = new ProzessDAO();
    String processDirectory = "";

    if (ConfigurationHelper.getInstance().isUseSwapping()) {
        swapPath = ConfigurationHelper.getInstance().getSwapPath();
    } else {
        setStatusMessage("swapping not activated");
        setStatusProgress(-1);
        return;
    }
    if (swapPath == null || swapPath.length() == 0) {
        setStatusMessage("no swappingPath defined");
        setStatusProgress(-1);
        return;
    }
    Path swapFile = Paths.get(swapPath);
    if (!StorageProvider.getInstance().isFileExists(swapFile)) {
        setStatusMessage("Swap folder does not exist or is not mounted");
        setStatusProgress(-1);
        return;
    }
    try {
        processDirectory = getProzess().getProcessDataDirectoryIgnoreSwapping();
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage(
                "Error while getting process data folder: " + e.getClass().getName() + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    Path fileIn = Paths.get(processDirectory);
    Path fileOut = Paths.get(swapPath + getProzess().getId() + FileSystems.getDefault().getSeparator());

    if (!StorageProvider.getInstance().isFileExists(fileOut)) {
        setStatusMessage(getProzess().getTitel() + ": swappingOutTarget does not exist");
        setStatusProgress(-1);
        return;
    }
    if (!StorageProvider.getInstance().isFileExists(fileIn)) {
        setStatusMessage(getProzess().getTitel() + ": process data folder does not exist");
        setStatusProgress(-1);
        return;
    }

    SAXBuilder builder = new SAXBuilder();
    Document docOld;
    try {
        Path swapLogFile = Paths.get(processDirectory, "swapped.xml");
        docOld = builder.build(swapLogFile.toFile());
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage("Error while reading swapped.xml in process data folder: " + e.getClass().getName()
                + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    /*
     * --------------------- alte Checksummen in HashMap schreiben -------------------
     */
    setStatusMessage("reading checksums");
    Element rootOld = docOld.getRootElement();

    HashMap<String, String> crcMap = new HashMap<String, String>();

    // TODO: Don't use Iterators
    for (Iterator<Element> it = rootOld.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        crcMap.put(el.getAttribute("path").getValue(), el.getAttribute("crc32").getValue());
    }
    StorageProvider.getInstance().deleteDataInDir(fileIn);

    /*
     * --------------------- Dateien kopieren und Checksummen ermitteln -------------------
     */
    Document doc = new Document();
    Element root = new Element("goobiArchive");
    doc.setRootElement(root);

    /*
     * --------------------- Verzeichnisse und Dateien kopieren und anschliessend den Ordner leeren -------------------
     */
    setStatusProgress(50);
    try {
        setStatusMessage("copying process files");
        Helper.copyDirectoryWithCrc32Check(fileOut, fileIn, swapPath.length(), root);
    } catch (IOException e) {
        logger.warn("IOException:", e);
        setStatusMessage("IOException in copyDirectory: " + e.getMessage());
        setStatusProgress(-1);
        return;
    }
    setStatusProgress(80);

    /*
     * --------------------- Checksummen vergleichen -------------------
     */
    setStatusMessage("checking checksums");
    // TODO: Don't use Iterators
    for (Iterator<Element> it = root.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        String newPath = el.getAttribute("path").getValue();
        String newCrc = el.getAttribute("crc32").getValue();
        if (crcMap.containsKey(newPath)) {
            if (!crcMap.get(newPath).equals(newCrc)) {
                setLongMessage(getLongMessage() + "File " + newPath + " has different checksum<br/>");
            }
            crcMap.remove(newPath);
        }
    }

    setStatusProgress(85);
    /*
     * --------------------- prfen, ob noch Dateien fehlen -------------------
     */
    setStatusMessage("checking missing files");
    if (crcMap.size() > 0) {
        for (String myFile : crcMap.keySet()) {
            setLongMessage(getLongMessage() + "File " + myFile + " is missing<br/>");
        }
    }

    setStatusProgress(90);

    /* in Prozess speichern */
    StorageProvider.getInstance().deleteDir(fileOut);
    try {
        setStatusMessage("saving process");
        Process myProzess = ProcessManager.getProcessById(getProzess().getId());
        myProzess.setSwappedOutGui(false);
        ProcessManager.saveProcess(myProzess);
    } catch (DAOException e) {
        setStatusMessage("DAOException while saving process: " + e.getMessage());
        logger.warn("DAOException:", e);
        setStatusProgress(-1);
        return;
    }
    setStatusMessage("done");

    setStatusProgress(100);
}