Example usage for org.jdom2 Element getAttributeValue

List of usage examples for org.jdom2 Element getAttributeValue

Introduction

In this page you can find the example usage for org.jdom2 Element getAttributeValue.

Prototype

public String getAttributeValue(final String attname) 

Source Link

Document

This returns the attribute value for the attribute with the given name and within no namespace, null if there is no such attribute, and the empty string if the attribute value is empty.

Usage

From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java

License:Apache License

private TEIValidator.Errors extractMainCorpusHeader(Document doc)
        throws LaudatioException, IOException, SAXException {
    TEIValidator validator = corpusSchemeURL == null ? new TEICorpusValidator()
            : new FromURLValidator(corpusSchemeURL);

    Element corpusHeader = doc.getRootElement().getChild("teiHeader", null);

    if (corpusHeader != null) {
        File corpusDir = new File(outputDirectory, "CorpusHeader");
        if (!corpusDir.exists() && !corpusDir.mkdir()) {
            throw new LaudatioException(
                    messages.getString("COULD NOT CREATE DIRECTORY") + corpusDir.getAbsolutePath());
        }/*from  w w w.  ja v a2s .  c o m*/

        // create the subtree for the global corpus header
        Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0");
        Element newRootForCorpus = new Element("TEI", teiNS);
        newRootForCorpus.addContent(corpusHeader.clone());
        Document corpusDoc = new Document(newRootForCorpus);

        if (corpusSchemeURL == null) {
            corpusDoc.addContent(0, new ProcessingInstruction("xml-model",
                    "href=\"" + TEICorpusValidator.DEFAULT_SCHEME_URL + "\""));
        } else {
            corpusDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + corpusSchemeURL + "\""));
        }

        // we need to append an empty "text" element after the header
        Element text = new Element("text", teiNS);
        text.setText("");
        newRootForCorpus.addContent(text);

        // we work with the copy from now
        corpusHeader = newRootForCorpus.getChild("teiHeader", null);
        Preconditions.checkNotNull(corpusHeader, messages.getString("ERROR NO CORPUS TITLE GIVEN"));

        Preconditions.checkState("CorpusHeader".equals(corpusHeader.getAttributeValue("type")));

        Preconditions.checkNotNull(corpusHeader.getChild("fileDesc", null),
                messages.getString("ERROR NO CORPUS TITLE GIVEN"));
        Preconditions.checkNotNull(corpusHeader.getChild("fileDesc", null).getChild("titleStmt", null),
                messages.getString("ERROR NO CORPUS TITLE GIVEN"));

        String title = corpusHeader.getChild("fileDesc", null).getChild("titleStmt", null)
                .getChildTextNormalize("title", null);
        Preconditions.checkNotNull(title, messages.getString("ERROR NO CORPUS TITLE GIVEN"));

        // save the file with the title as file name
        File outputFile = new File(corpusDir, title + ".xml");
        XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
        xmlOut.output(corpusDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
        log.info(messages.getString("WRITTEN CORPUS HEADER"), outputFile.getPath());

        validator.validate(outputFile);

    }
    return validator.getErrors();
}

From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java

License:Apache License

private TEIValidator.Errors extractDocumentHeaders(Document doc)
        throws LaudatioException, IOException, SAXException {
    TEIValidator validator = documentSchemeURL == null ? new TEIDocumentValidator()
            : new FromURLValidator(documentSchemeURL);

    File documentDir = new File(outputDirectory, "DocumentHeader");
    if (!documentDir.exists() && !documentDir.mkdir()) {
        throw new LaudatioException(
                messages.getString("COULD NOT CREATE DIRECTORY") + documentDir.getAbsolutePath());
    }/*from w  ww .j  a va 2s . co  m*/

    Element documentRoot = Preconditions.checkNotNull(doc.getRootElement().getChild("teiCorpus", null));

    for (Element docHeader : documentRoot.getChildren("teiHeader", null)) {
        Preconditions.checkState("DocumentHeader".equals(docHeader.getAttributeValue("type")));

        // create the subtree for the global corpus header
        Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0");
        Element tei = new Element("TEI", teiNS);
        tei.addContent(docHeader.clone());
        Document newDoc = new Document(tei);

        if (documentSchemeURL == null) {
            newDoc.addContent(0, new ProcessingInstruction("xml-model",
                    "href=\"" + TEIDocumentValidator.DEFAULT_SCHEME_URL + "\""));
        } else {
            newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + documentSchemeURL + "\""));
        }

        // we need to append an empty "text" element after the header
        Element text = new Element("text", teiNS);
        text.setText("");
        tei.addContent(text);

        Element fileDesc = Preconditions
                .checkNotNull(tei.getChild("teiHeader", null).getChild("fileDesc", null));

        String outName = UUID.randomUUID().toString();

        String id = fileDesc.getAttributeValue("id", Namespace.XML_NAMESPACE);
        if (id != null) {
            outName = id;
        } else {
            Element titleStmt = Preconditions.checkNotNull(fileDesc.getChild("titleStmt", null));

            String title = titleStmt.getChildText("title", null);
            if (title != null) {
                outName = title;
            }
        }

        File outputFile = new File(documentDir, outName + ".xml");
        XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
        xmlOut.output(newDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
        log.info(messages.getString("WRITTEN DOCUMENT HEADER"), outputFile.getPath());

        validator.validate(outputFile);

    }
    return validator.getErrors();
}

From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java

License:Apache License

private TEIValidator.Errors extractPreparationSteps(Document doc)
        throws LaudatioException, IOException, SAXException {
    TEIValidator validator = preparationSchemeURL == null ? new TEIPreparationValidator()
            : new FromURLValidator(preparationSchemeURL);
    Multiset<String> knownPreparationTitles = HashMultiset.create();

    File documentDir = new File(outputDirectory, "PreparationHeader");
    if (!documentDir.exists() && !documentDir.mkdir()) {
        throw new LaudatioException(
                messages.getString("COULD NOT CREATE DIRECTORY") + documentDir.getAbsolutePath());
    }/*from ww  w.j  a  v  a2  s.co  m*/

    Preconditions.checkNotNull(doc.getRootElement().getChild("teiCorpus", null));
    Element preparationRoot = Preconditions
            .checkNotNull(doc.getRootElement().getChild("teiCorpus", null).getChild("teiCorpus", null));

    for (Element preparationHeader : preparationRoot.getChildren("teiHeader", null)) {
        Preconditions.checkState("PreparationHeader".equals(preparationHeader.getAttributeValue("type")));

        // create the subtree for the global corpus header
        Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0");
        Element tei = new Element("TEI", teiNS);
        tei.addContent(preparationHeader.clone());
        Document newDoc = new Document(tei);

        if (preparationSchemeURL == null) {
            newDoc.addContent(0, new ProcessingInstruction("xml-model",
                    "href=\"" + TEIPreparationValidator.DEFAULT_SCHEME_URL + "\""));
        } else {
            newDoc.addContent(0,
                    new ProcessingInstruction("xml-model", "href=\"" + preparationSchemeURL + "\""));
        }

        // we need to append an empty "text" element after the header
        Element text = new Element("text", teiNS);
        text.setText("");
        tei.addContent(text);

        Element fileDesc = Preconditions
                .checkNotNull(tei.getChild("teiHeader", null).getChild("fileDesc", null));

        String outName = UUID.randomUUID().toString();

        Element titleStmt = Preconditions.checkNotNull(fileDesc.getChild("titleStmt", null));
        Element title = Preconditions.checkNotNull(titleStmt.getChild("title", null));
        String corresp = title.getAttributeValue("corresp");
        if (corresp != null) {
            if (knownPreparationTitles.contains(corresp)) {
                knownPreparationTitles.add(corresp);
                outName = corresp + "_" + knownPreparationTitles.count(corresp);
                log.warn(messages.getString("MORE THAN ONE PREPARATION HEADER"), corresp);
            } else {
                outName = corresp;
                knownPreparationTitles.add(corresp);
            }
        }

        File outputFile = new File(documentDir, outName + ".xml");
        XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
        xmlOut.output(newDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
        log.info(messages.getString("WRITTEN PREPARATION HEADER"), outputFile.getPath());

        validator.validate(outputFile);

    }
    return validator.getErrors();
}

From source file:de.intranda.goobi.plugins.sru.SRUHelper.java

License:Open Source License

public static Node parseHaabResult(GbvMarcSruImport opac, String catalogue, String schema, String searchField,
        String searchValue, String resultString, String packing, String version, boolean ignoreAnchor)
        throws IOException, JDOMException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
    builder.setFeature("http://xml.org/sax/features/validation", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document doc = builder.build(new StringReader(resultString), "utf-8");
    Element record = getRecordWithoutSruHeader(doc);
    if (record == null) {
        opac.setHitcount(0);/* ww w.jav a  2s.  c  om*/
        return null;
    }
    opac.setHitcount(1);
    boolean isPeriodical = false;
    boolean isManuscript = false;
    boolean isCartographic = false;
    boolean isMultiVolume = false;
    boolean isFSet = false;

    String anchorPpn = null;
    String otherAnchorPpn = null;
    String otherAnchorEpn = null;

    String otherPpn = null;
    String currentEpn = null;
    String otherEpn = null;
    boolean foundMultipleEpns = false;

    // generate an answer document
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    org.w3c.dom.Document answer = docBuilder.newDocument();
    org.w3c.dom.Element collection = answer.createElement("collection");
    answer.appendChild(collection);

    boolean shelfmarkFound = false;
    List<Element> data = record.getChildren();
    for (Element el : data) {
        if (el.getName().equalsIgnoreCase("leader")) {
            String value = el.getText();
            if (value.length() < 24) {
                value = "00000" + value;
            }
            char c6 = value.toCharArray()[6];
            char c7 = value.toCharArray()[7];
            char c19 = value.toCharArray()[19];
            if (c6 == 'a' && (c7 == 's' || c7 == 'd')) {
                isPeriodical = true;
            } else if (c6 == 't') {
                isManuscript = true;
            } else if (c6 == 'e') {
                isCartographic = true;
            }
            if (c19 == 'b' || c19 == 'c') {
                isFSet = true;
            }

        }
        if (el.getName().equalsIgnoreCase("datafield")) {
            String tag = el.getAttributeValue("tag");
            List<Element> subfields = el.getChildren();
            boolean isCurrentEpn = false;
            for (Element sub : subfields) {
                String code = sub.getAttributeValue("code");
                // anchor identifier
                if (tag.equals("773") && code.equals("w")) {
                    if (ignoreAnchor) {
                        sub.setText("");
                    } else if (isFSet || isPeriodical) {
                        isMultiVolume = true;
                        anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    }
                } else if (tag.equals("800") && code.equals("w")) {
                    isMultiVolume = true;
                    anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                } else if (isManuscript && tag.equals("810") && code.equals("w")) {
                    isMultiVolume = true;
                    anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                } else if (tag.equals("830") && code.equals("w")) {
                    if (isCartographic || (isFSet && anchorPpn == null)) {
                        isMultiVolume = true;
                        anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    }
                } else if (tag.equals("776") && code.equals("w")) {
                    if (otherPpn == null) {
                        // found first/only occurrence
                        otherPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    } else {
                        otherPpn = null;
                        foundMultipleEpns = true;
                    }

                } else if (tag.equals("954")) {
                    if (code.equals("b")) {
                        if (searchField.equals("pica.epn")) {
                            // remove wrong epns
                            currentEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                            isCurrentEpn = true;
                            if (!searchValue.trim().equals(currentEpn)) {
                                sub.setAttribute("code", "invalid");
                                for (Element exemplarData : subfields) {
                                    if (exemplarData.getAttributeValue("code").equals("d")) {
                                        exemplarData.setAttribute("code", "invalid");
                                    }
                                }
                            }
                        } else {
                            if (currentEpn == null) {
                                isCurrentEpn = true;
                                currentEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                            } else {
                                foundMultipleEpns = true;
                            }
                        }
                    } else if (code.equals("d")) {
                        if (!shelfmarkFound && isCurrentEpn) {
                            shelfmarkFound = true;
                        } else {
                            sub.setAttribute("code", "invalid");
                        }
                    }
                }
            }
        }
    }

    //  search for pica.zdb for periodca
    // get digital epn from digital ppn record
    if (otherPpn != null) {
        String otherResult = SRUHelper.search(catalogue, schema, isPeriodical ? "pica.zdb" : "pica.ppn",
                otherPpn, packing, version);
        Document otherDocument = new SAXBuilder().build(new StringReader(otherResult), "utf-8");
        if (otherDocument != null) {
            Element otherRecord = getRecordWithoutSruHeader(otherDocument);
            if (otherRecord == null) {
                Helper.setFehlerMeldung("import_OtherEPNNotFound");
            } else {

                List<Element> controlList = otherRecord.getChildren("controlfield", MARC);
                for (Element field : controlList) {
                    if (field.getAttributeValue("tag").equals("001")) {
                        otherPpn = field.getText();
                    }
                }

                List<Element> fieldList = otherRecord.getChildren("datafield", MARC);
                for (Element field : fieldList) {
                    String tag = field.getAttributeValue("tag");

                    List<Element> subfields = field.getChildren();
                    for (Element sub : subfields) {
                        String code = sub.getAttributeValue("code");
                        // anchor identifier
                        if (tag.equals("773") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (tag.equals("800") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (isManuscript && tag.equals("810") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "");
                        } else if (isCartographic && tag.equals("830") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (tag.equals("954") && code.equals("b")) {
                            if (otherEpn == null) {
                                otherEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                            } else {
                                foundMultipleEpns = true;
                                otherEpn = null;
                            }
                        }

                    }
                }
            }
            if (otherPpn != null) {
                Element datafield = new Element("datafield", MARC);
                datafield.setAttribute("tag", "ppnDigital");
                datafield.setAttribute("ind1", "");
                datafield.setAttribute("ind2", "");

                Element subfield = new Element("subfield", MARC);
                subfield.setAttribute("code", "a");
                subfield.setText(otherPpn);
                datafield.addContent(subfield);
                data.add(datafield);
            }
            if (otherEpn != null && !foundMultipleEpns) {
                Element datafield = new Element("datafield", MARC);
                datafield.setAttribute("tag", "epnDigital");
                datafield.setAttribute("ind1", "");
                datafield.setAttribute("ind2", "");

                Element subfield = new Element("subfield", MARC);
                subfield.setAttribute("code", "a");
                subfield.setText(otherEpn);
                datafield.addContent(subfield);
                data.add(datafield);
            }
        }
    }
    org.w3c.dom.Element marcRecord = getRecord(answer, data, opac);

    if (isMultiVolume) {
        // get anchor record
        String anchorResult = SRUHelper.search(catalogue, schema, "pica.ppn", anchorPpn, packing, version);
        Document anchorDoc = new SAXBuilder().build(new StringReader(anchorResult), "utf-8");

        Element anchorRecord = getRecordWithoutSruHeader(anchorDoc);

        if (anchorRecord != null) {
            List<Element> anchorData = anchorRecord.getChildren();

            // get EPN/PPN digital for anchor
            String otherAnchorResult = SRUHelper.search(catalogue, schema,
                    isPeriodical ? "pica.zdb" : "pica.ppn", otherAnchorPpn, packing, version);
            Document otherAnchorDoc = new SAXBuilder().build(new StringReader(otherAnchorResult), "utf-8");
            Element otherAnchorRecord = getRecordWithoutSruHeader(otherAnchorDoc);

            if (otherAnchorRecord == null) {
                Helper.setFehlerMeldung("import_OtherEPNNotFound");
            } else {

                List<Element> controlList = otherAnchorRecord.getChildren("controlfield", MARC);
                for (Element field : controlList) {
                    if (field.getAttributeValue("tag").equals("001")) {
                        otherAnchorPpn = field.getText();
                    }
                }

                List<Element> fieldList = otherAnchorRecord.getChildren("datafield", MARC);
                for (Element field : fieldList) {
                    if (field.getAttributeValue("tag").equals("954")) {
                        List<Element> subfields = field.getChildren();
                        for (Element sub : subfields) {
                            String code = sub.getAttributeValue("code");
                            if (code.equals("b")) {
                                if (otherAnchorEpn == null) {
                                    otherAnchorEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP",
                                            "");
                                    ;
                                } else {
                                    foundMultipleEpns = true;
                                }
                            }
                        }
                    }
                }

                if (otherAnchorPpn != null) {
                    Element datafield = new Element("datafield", MARC);
                    datafield.setAttribute("tag", "ppnDigital");
                    datafield.setAttribute("ind1", "");
                    datafield.setAttribute("ind2", "");

                    Element subfield = new Element("subfield", MARC);
                    subfield.setAttribute("code", "a");
                    subfield.setText(otherAnchorPpn);
                    datafield.addContent(subfield);
                    anchorData.add(datafield);
                }

                if (otherAnchorEpn != null && !foundMultipleEpns) {
                    Element datafield = new Element("datafield", MARC);
                    datafield.setAttribute("tag", "epnDigital");
                    datafield.setAttribute("ind1", "");
                    datafield.setAttribute("ind2", "");

                    Element subfield = new Element("subfield", MARC);
                    subfield.setAttribute("code", "a");
                    subfield.setText(otherAnchorEpn);
                    datafield.addContent(subfield);
                    anchorData.add(datafield);
                }
            }
            org.w3c.dom.Element anchorMarcRecord = getRecord(answer, anchorData, opac);

            collection.appendChild(anchorMarcRecord);
        }

    }

    if (foundMultipleEpns) {
        Helper.setFehlerMeldung("import_foundMultipleEPNs");
    }

    collection.appendChild(marcRecord);
    return answer.getDocumentElement();
}

From source file:de.intranda.goobi.plugins.sru.SRUHelper.java

License:Open Source License

public static Node parseGbvResult(GbvMarcSruImport opac, String catalogue, String schema, String searchField,
        String resultString, String packing, String version)
        throws IOException, JDOMException, ParserConfigurationException {
    // removed validation against external dtd
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);

    builder.setFeature("http://xml.org/sax/features/validation", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document doc = builder.build(new StringReader(resultString), "utf-8");
    // srw:searchRetrieveResponse
    Element record = getRecordWithoutSruHeader(doc);
    if (record == null) {
        opac.setHitcount(0);/*from  www  . j a v a2s  . c  o  m*/
        return null;
    } else {
        opac.setHitcount(1);
        // generate an answer document
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        org.w3c.dom.Document answer = docBuilder.newDocument();
        org.w3c.dom.Element collection = answer.createElement("collection");
        answer.appendChild(collection);

        boolean isMultiVolume = false;
        boolean isPeriodical = false;
        boolean isManuscript = false;
        boolean isCartographic = false;

        String anchorIdentifier = "";
        List<Element> data = record.getChildren();

        for (Element el : data) {
            if (el.getName().equalsIgnoreCase("leader")) {
                String value = el.getText();
                if (value.length() < 24) {
                    value = "00000" + value;
                }
                char c6 = value.toCharArray()[6];
                char c7 = value.toCharArray()[7];
                char c19 = value.toCharArray()[19];
                if (c6 == 'a' && (c7 == 's' || c7 == 'd')) {
                    isPeriodical = true;
                } else if (c6 == 't') {
                    isManuscript = true;
                } else if (c6 == 'e') {
                    isCartographic = true;
                }
                if (c19 == 'b' || c19 == 'c') {
                    isMultiVolume = true;
                }
            }

            if (el.getName().equalsIgnoreCase("datafield")) {
                String tag = el.getAttributeValue("tag");
                List<Element> subfields = el.getChildren();
                for (Element sub : subfields) {
                    String code = sub.getAttributeValue("code");
                    // anchor identifier
                    if (tag.equals("773") && code.equals("w")) {
                        if (!isMultiVolume && !isPeriodical) {
                            sub.setText("");
                        } else {
                            anchorIdentifier = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        }
                    } else if (tag.equals("800") && code.equals("w") && isMultiVolume) {
                        anchorIdentifier = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                    } else if (isManuscript && tag.equals("810") && code.equals("w")) {
                        isMultiVolume = true;
                        anchorIdentifier = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                    } else if (tag.equals("830") && code.equals("w")) {
                        if (isCartographic || (isMultiVolume && anchorIdentifier == null)) {
                            anchorIdentifier = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        }
                    }
                }
            }
        }

        org.w3c.dom.Element marcRecord = getRecord(answer, data, opac);

        if (isMultiVolume) {
            String anchorResult = SRUHelper.search(catalogue, schema, searchField, anchorIdentifier, packing,
                    version);
            Document anchorDoc = new SAXBuilder().build(new StringReader(anchorResult), "utf-8");

            Element anchorRecord = getRecordWithoutSruHeader(anchorDoc);
            if (anchorRecord != null) {
                List<Element> anchorData = anchorRecord.getChildren();
                org.w3c.dom.Element anchorMarcRecord = getRecord(answer, anchorData, opac);

                collection.appendChild(anchorMarcRecord);
            }

        }
        collection.appendChild(marcRecord);
        return answer.getDocumentElement();
    }

}

From source file:de.intranda.goobi.plugins.sru.SRUHelper.java

License:Open Source License

private static org.w3c.dom.Element getRecord(org.w3c.dom.Document answer, List<Element> data,
        IOpacPlugin plugin) {/*from  w ww. j a va2  s .c  o  m*/
    org.w3c.dom.Element marcRecord = answer.createElement("record");
    // fix for wrong leader in SWB
    org.w3c.dom.Element leader = null;
    String author = "";
    String title = "";
    for (Element datafield : data) {
        if (datafield.getName().equals("leader") && leader == null) {
            leader = answer.createElement("leader");
            marcRecord.appendChild(leader);
            String ldr = datafield.getText();
            if (ldr.length() < 24) {
                ldr = "00000" + ldr;
            }
            Text text = answer.createTextNode(ldr);
            leader.appendChild(text);

            // get the leader field as a datafield
            org.w3c.dom.Element leaderDataField = answer.createElement("datafield");
            leaderDataField.setAttribute("tag", "leader");
            leaderDataField.setAttribute("ind1", " ");
            leaderDataField.setAttribute("ind2", " ");

            org.w3c.dom.Element subfield = answer.createElement("subfield");
            leaderDataField.appendChild(subfield);
            subfield.setAttribute("code", "a");
            Text dataFieldtext = answer.createTextNode(datafield.getText());
            subfield.appendChild(dataFieldtext);
            marcRecord.appendChild(leaderDataField);

        } else if (datafield.getName().equals("controlfield")) {
            org.w3c.dom.Element field = answer.createElement("controlfield");

            Text text = answer.createTextNode(datafield.getText());
            field.appendChild(text);

            String tag = datafield.getAttributeValue("tag");
            field.setAttribute("tag", tag);
            marcRecord.appendChild(field);

            // get the controlfields as datafields
            org.w3c.dom.Element leaderDataField = answer.createElement("datafield");
            leaderDataField.setAttribute("tag", tag);
            leaderDataField.setAttribute("ind1", " ");
            leaderDataField.setAttribute("ind2", " ");

            org.w3c.dom.Element subfield = answer.createElement("subfield");
            leaderDataField.appendChild(subfield);
            subfield.setAttribute("code", "a");
            Text dataFieldtext = answer.createTextNode(datafield.getText());
            subfield.appendChild(dataFieldtext);
            marcRecord.appendChild(leaderDataField);

        } else if (datafield.getName().equals("datafield")) {
            String tag = datafield.getAttributeValue("tag");
            String ind1 = datafield.getAttributeValue("ind1");
            String ind2 = datafield.getAttributeValue("ind2");

            org.w3c.dom.Element field = answer.createElement("datafield");
            marcRecord.appendChild(field);

            field.setAttribute("tag", tag);
            field.setAttribute("ind1", ind1);
            field.setAttribute("ind2", ind2);
            List<Element> subfields = datafield.getChildren();

            for (Element sub : subfields) {
                org.w3c.dom.Element subfield = answer.createElement("subfield");
                field.appendChild(subfield);
                String code = sub.getAttributeValue("code");
                subfield.setAttribute("code", code);
                Text text = answer.createTextNode(sub.getText());
                subfield.appendChild(text);

                if (tag.equals("100") && code.equals("a")) {
                    author = sub.getText();
                }

                // main title, create sorting title
                if (tag.equals("245") && code.equals("a")) {
                    org.w3c.dom.Element sorting = answer.createElement("subfield");
                    field.appendChild(sorting);
                    sorting.setAttribute("code", "x");
                    String subtext = sub.getText();
                    if (!ind2.trim().isEmpty()) {
                        int numberOfNonfillingCharacter = new Integer(ind2).intValue();
                        subtext = subtext.substring(numberOfNonfillingCharacter);
                    }
                    title = subtext;
                    Text sortingtext = answer.createTextNode(subtext);
                    sorting.appendChild(sortingtext);

                }
            }
        }
    }
    plugin.setAtstsl(plugin.createAtstsl(title, author));
    return marcRecord;
}

From source file:de.knewcleus.openradar.view.groundnet.GroundnetReader.java

License:Open Source License

private void readGroundnetXml() {

    SAXBuilder builder = new SAXBuilder();
    InputStream xmlInputStream = null;

    try {/*from  w w  w  . j  a  v a2 s . c o  m*/
        xmlInputStream = getZipArchiveFileInputStream("data/airports.zip", airportCode);

        Document document = (Document) builder.build(xmlInputStream);
        Element rootNode = document.getRootElement();

        // read parking list
        List<Element> list = rootNode.getChild("parkingList").getChildren("Parking");
        for (Element p : list) {
            String index = p.getAttributeValue("index");
            String type = p.getAttributeValue("type");
            String name = p.getAttributeValue("name");
            String number = p.getAttributeValue("number");
            String lat = p.getAttributeValue("lat");
            String lon = p.getAttributeValue("lon");
            String heading = p.getAttributeValue("heading");
            String radius = p.getAttributeValue("radius");
            String airlineCodes = p.getAttributeValue("airlineCodes");
            ParkPos pos = new ParkPos(index, type, name, number, lat, lon, heading, radius, airlineCodes);
            parkPosList.add(pos);
            mapTaxiPoints.put(index, pos);
        }

        // read nodes
        list = rootNode.getChild("TaxiNodes").getChildren("node");
        for (Element p : list) {
            String index = p.getAttributeValue("index");
            String lat = p.getAttributeValue("lat");
            String lon = p.getAttributeValue("lon");
            boolean isOnRunway = !"0".equals(p.getAttributeValue("isOnRunway"));
            String holdPointType = p.getAttributeValue("holdPointType");
            TaxiPoint point = new TaxiPoint(index, lat, lon, isOnRunway, holdPointType);
            mapTaxiPoints.put(index, point);
        }
        // read segments
        list = rootNode.getChild("TaxiWaySegments").getChildren("arc");
        for (Element a : list) {
            String beginPoint = a.getAttributeValue("begin");
            String endPoint = a.getAttributeValue("end");
            boolean isPushBackRoute = !"0".equals(a.getAttributeValue("isPushBackRoute"));
            String name = a.getAttributeValue("name");
            TaxiWaySegment seg = new TaxiWaySegment(name, mapTaxiPoints.get(beginPoint),
                    mapTaxiPoints.get(endPoint), isPushBackRoute);
            taxiwaySegmentList.add(seg);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (xmlInputStream != null) {
            try {
                xmlInputStream.close();
                zipArchive.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:de.knewcleus.openradar.view.stdroutes.StdRouteReader.java

License:Open Source License

private void readRouteXml() {

    SAXBuilder builder = new SAXBuilder();
    InputStream xmlInputStream = null;

    File dir = new File("data/routes/" + data.getAirportCode());
    if (!dir.exists() || !dir.isDirectory()) {
        return;/*  ww  w .ja  v  a 2s . c  om*/
    }

    List<File> files = new ArrayList<File>(Arrays.asList(dir.listFiles()));

    data.getNavaidDB().clearAddPoints();

    while (files.size() > 0) {
        File file = files.remove(0);
        try {
            if (!file.getName().endsWith(".xml"))
                continue;
            // todo read all files
            xmlInputStream = new FileInputStream(file);

            Document document = (Document) builder.build(xmlInputStream);
            Element rootNode = document.getRootElement();

            //                String orFilename = "data/routes/" + data.getAirportCode() + "/" + file.getName().substring(0, file.getName().indexOf(".xml")) + ".or.xml";
            if ("ProceduresDB".equalsIgnoreCase(rootNode.getName())) {// && !(new File(orFilename).exists())) {
                // if converted file does not exist, convert it now.
                // deactivated for now convertProcedureDbFile(orFilename, rootNode);
            } else {
                // read or file
                List<Element> list = rootNode.getChildren("addPoint");
                for (Element eAddPoint : list) {
                    String code = eAddPoint.getAttributeValue("code");
                    String sPoint = eAddPoint.getAttributeValue("point");
                    try {
                        Point2D point = StdRoute.getPoint(data, mapViewAdapter, sPoint, null);
                        data.getNavaidDB().addPoint(code, point);
                    } catch (Exception e) {
                        log.error("Problem to parse file " + file.getAbsolutePath() + ", addPoint: " + code
                                + ": " + sPoint + ", Error:" + e.getMessage());
                    }
                }
                List<Element> includeList = rootNode.getChildren("include");
                for (Element eInclude : includeList) {
                    String fileName = eInclude.getAttributeValue("file");
                    files.add(new File(file.getAbsolutePath().substring(0,
                            file.getAbsolutePath().lastIndexOf(File.separator) + 1) + fileName));
                }
                // routes
                list = rootNode.getChildren("route");
                for (Element eRoute : list) {
                    String name = eRoute.getAttributeValue("name");
                    String displayMode = eRoute.getAttributeValue("displayMode");
                    String zoomMin = eRoute.getAttributeValue("zoomMin");
                    String zoomMax = eRoute.getAttributeValue("zoomMax");
                    String stroke = eRoute.getAttributeValue("stroke");
                    String lineWidth = eRoute.getAttributeValue("lineWidth");
                    String color = eRoute.getAttributeValue("color");
                    List<Element> sublist = eRoute.getChildren();
                    AStdRouteElement previous = null;
                    StdRoute route = new StdRoute(data, mapViewAdapter, name, displayMode, zoomMin, zoomMax,
                            stroke, lineWidth, color);
                    for (Element element : sublist) {
                        try {
                            if (element.getName().equalsIgnoreCase("activeLandingRunways")) {
                                route.setActiveLandingRunways(element.getText());
                            } else if (element.getName().equalsIgnoreCase("activeStartRunways")) {
                                route.setActiveStartingRunways(element.getText());
                            } else if (element.getName().equalsIgnoreCase("navaids")) {
                                color = element.getAttributeValue("color");
                                route.setNavaids(element.getText(), color);
                            } else if (element.getName().equalsIgnoreCase("include")) {
                                String routeName = element.getAttributeValue("routeName");
                                route.includeRoute(stdRoutes, routeName);
                            } else if (element.getName().equalsIgnoreCase("line")) {
                                String start = element.getAttributeValue("start");
                                String end = element.getAttributeValue("end");
                                String angle = element.getAttributeValue("angle");
                                String length = element.getAttributeValue("length");
                                String startOffset = element.getAttributeValue("startOffset");
                                String endOffset = element.getAttributeValue("endOffset");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                String text = element.getAttributeValue("text");
                                StdRouteLine line = new StdRouteLine(route, mapViewAdapter, previous, start,
                                        end, angle, length, startOffset, endOffset, stroke, lineWidth, arrows,
                                        color, text);
                                previous = line;
                                route.addElement(line);
                            } else if (element.getName().equalsIgnoreCase("bow")) {
                                String center = element.getAttributeValue("center");
                                String radius = element.getAttributeValue("radius");
                                String startAngle = element.getAttributeValue("startAngle");
                                String extentAngle = element.getAttributeValue("extentAngle");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                String text = element.getAttributeValue("text");
                                StdRouteBow bow = new StdRouteBow(route, mapViewAdapter, previous, center,
                                        radius, startAngle, extentAngle, stroke, lineWidth, color, arrows,
                                        text);
                                previous = bow;
                                route.addElement(bow);
                            } else if (element.getName().equalsIgnoreCase("curve")) {
                                String start = element.getAttributeValue("start");
                                String end = element.getAttributeValue("end");
                                String controlPoint = element.getAttributeValue("controlPoint");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                StdRouteCurve bow = new StdRouteCurve(route, mapViewAdapter, previous, start,
                                        end, controlPoint, stroke, lineWidth, color, arrows);
                                previous = bow;
                                route.addElement(bow);
                            } else if (element.getName().equalsIgnoreCase("intercept")) {
                                String start = element.getAttributeValue("start");
                                String startOffset = element.getAttributeValue("startOffset");
                                String startHeading = element.getAttributeValue("startHeading");
                                String startTurn = element.getAttributeValue("startTurn");
                                String radius = element.getAttributeValue("radius");
                                String speed = element.getAttributeValue("speed");
                                String end = element.getAttributeValue("end");
                                String radial = element.getAttributeValue("radial");
                                String endHeading = element.getAttributeValue("endHeading");
                                String direction = element.getAttributeValue("direction");
                                String endOffset = element.getAttributeValue("endOffset");
                                String text = element.getAttributeValue("text");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                StdRouteIntercept intercept = new StdRouteIntercept(route, mapViewAdapter,
                                        previous, start, startOffset, startHeading, startTurn, radius, speed,
                                        end, radial, endHeading, direction, endOffset, stroke, lineWidth,
                                        arrows, color, text);
                                previous = intercept;
                                route.addElement(intercept);
                            } else if (element.getName().equalsIgnoreCase("loop")) {
                                String navpoint = element.getAttributeValue("navpoint");
                                String inboundHeading = element.getAttributeValue("inboundHeading");
                                String length = element.getAttributeValue("length");
                                String width = element.getAttributeValue("width");
                                String right = element.getAttributeValue("right");
                                String arrows = element.getAttributeValue("arrows");
                                String minHeight = element.getAttributeValue("minHeight");
                                String maxHeight = element.getAttributeValue("maxHeight");
                                String misapHeight = element.getAttributeValue("misapHeight");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                color = element.getAttributeValue("color");
                                StdRouteLoop ellipse = new StdRouteLoop(route, mapViewAdapter, previous,
                                        navpoint, inboundHeading, length, width, right, arrows, minHeight,
                                        maxHeight, misapHeight, stroke, lineWidth, color);
                                previous = ellipse;
                                route.addElement(ellipse);
                            } else if (element.getName().equalsIgnoreCase("multiPointLine")) {
                                String close = element.getAttributeValue("close");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                color = element.getAttributeValue("color");
                                List<String> points = new ArrayList<String>();
                                List<Element> pointList = element.getChildren("point");
                                for (Element ePoint : pointList) {
                                    points.add(ePoint.getTextTrim());
                                }
                                StdRouteMultipointLine line = new StdRouteMultipointLine(route, mapViewAdapter,
                                        previous, points, close, stroke, lineWidth, color);
                                previous = line;
                                route.addElement(line);
                            } else if (element.getName().equalsIgnoreCase("text")) {
                                String position = element.getAttributeValue("position");
                                String angle = element.getAttributeValue("angle");
                                String alignHeading = element.getAttributeValue("alignHeading");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                boolean clickable = "true".equals(element.getAttributeValue("clickable"));
                                String sText = element.getAttributeValue("text");
                                StdRouteText text = new StdRouteText(route, mapViewAdapter, previous, position,
                                        angle, alignHeading, font, fontSize, color, clickable, sText);
                                previous = text;
                                route.addElement(text);
                            } else if (element.getName().equalsIgnoreCase("screenText")) {
                                String position = element.getAttributeValue("screenPos");
                                String angle = element.getAttributeValue("angle");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                String sText = element.getAttributeValue("text");
                                StdRouteScreenText text = new StdRouteScreenText(route, mapViewAdapter,
                                        previous, position, angle, font, fontSize, color, sText);
                                previous = text;
                                route.addElement(text);
                            } else if (element.getName().equalsIgnoreCase("minAlt")) {
                                String position = element.getAttributeValue("position");
                                String value = element.getAttributeValue("value");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                StdRouteMinAltitude minAlt = new StdRouteMinAltitude(route, mapViewAdapter,
                                        previous, position, value, font, fontSize, color);
                                previous = minAlt;
                                route.addElement(minAlt);
                            }

                        } catch (Exception e) {
                            log.error("Problem to parse file " + file.getAbsolutePath() + ", Route: "
                                    + route.getName() + ", Error:" + e.getMessage(), e);
                            break;
                        }
                    }
                    stdRoutes.add(route);
                }
            }

        } catch (Exception e) {
            log.error("Problem to parse file " + file.getAbsolutePath() + ", Error:" + e.getMessage());

        } finally {
            if (xmlInputStream != null) {
                try {
                    xmlInputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }
    data.getNavaidDB().setStdRoutes(stdRoutes);
}

From source file:de.nava.informa.parsers.Atom_0_3_Parser.java

License:Open Source License

static String getValue(Element elt) {
    return AtomParserUtils.getValue(elt, elt.getAttributeValue("mode"));
}

From source file:de.nava.informa.parsers.Atom_0_3_Parser.java

License:Open Source License

/**
 * Returns the content type of element. Default is 'text/plain' according to Atom draft 0.3.
 *///from w w w  . j  ava  2s. c  o  m
private static String getContentType(Element elt) {
    String type = elt.getAttributeValue("type");

    return (type == null) ? "text/plain" : type;
}