Example usage for org.jdom2 Element getChildren

List of usage examples for org.jdom2 Element getChildren

Introduction

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

Prototype

public List<Element> getChildren() 

Source Link

Document

This returns a List of all the child elements nested directly (one level deep) within this element, as Element objects.

Usage

From source file:de.hbrs.oryx.yawl.converter.handler.oryx.OryxAtomicTaskHandler.java

License:Open Source License

private void convertResourcing(final YAtomicTask task) throws ConversionException {

    String startInitiator = getShape().getProperty("startinitiator");
    String startInteraction = getShape().getProperty("startinteraction");
    String allocateInitiator = getShape().getProperty("allocateinitiator");
    String allocateInteraction = getShape().getProperty("allocateinteraction");
    String offerInitiator = getShape().getProperty("offerinitiator");
    String offerInteraction = getShape().getProperty("offerinteraction");
    String privilegesSource = getShape().getProperty("privileges");

    Element resourcingSpecs = new Element("resourcing", YAWLUtils.YAWL_NS);

    // Add in order Offer, Allocate, Start, Privileges to ensure exact same
    // result as on import
    if (offerInteraction != null) {
        Element offer = YAWLUtils
                .parseToElement("<offer xmlns=\"" + YAWLUtils.YAWL_NS + "\">" + offerInteraction + "</offer>")
                .detachRootElement();/*from   w w w .j a  v a2s . c o  m*/
        if (offerInitiator != null) {
            offer.setAttribute("initiator", offerInitiator);
        }
        resourcingSpecs.addContent(offer);
    }

    if (allocateInteraction != null) {
        Element allocate = YAWLUtils
                .parseToElement(
                        "<allocate xmlns=\"" + YAWLUtils.YAWL_NS + "\">" + allocateInteraction + "</allocate>")
                .detachRootElement();
        if (allocateInitiator != null) {
            allocate.setAttribute("initiator", allocateInitiator);
        }
        resourcingSpecs.addContent(allocate);
    }

    if (startInteraction != null) {
        Element start = YAWLUtils
                .parseToElement("<start xmlns=\"" + YAWLUtils.YAWL_NS + "\">" + startInteraction + "</start>")
                .detachRootElement();
        if (startInitiator != null) {
            start.setAttribute("initiator", startInitiator);
        }
        resourcingSpecs.addContent(start);
    }

    Element privileges = new Element("privileges", YAWLUtils.YAWL_NS);
    if (privilegesSource != null && !privilegesSource.isEmpty()) {
        privileges.addContent(YAWLUtils.parseToElement("<privileges>" + privilegesSource + "</privileges>")
                .getRootElement().cloneContent());
        resourcingSpecs.addContent(privileges);
    }

    if (resourcingSpecs.getChildren().size() > 0) {
        task.setResourcingSpecs(resourcingSpecs);
    }
}

From source file:de.hbrs.oryx.yawl.converter.handler.yawl.element.AtomicTaskHandler.java

License:Open Source License

private HashMap<String, String> convertResourcing(final Element resourcingSpecs) {
    HashMap<String, String> properties = new HashMap<String, String>();

    if (resourcingSpecs == null) {
        getContext().addConversionWarnings("No resourcing specification " + getNetElement().getID(), null);
        return properties;
    }/*from w w w  . java  2 s  . co m*/

    Element offer = resourcingSpecs.getChild("offer", resourcingSpecs.getNamespace());
    if (offer != null) {
        properties.put("offerinitiator", offer.getAttributeValue("initiator"));
        properties.put("offerinteraction", YAWLUtils.elementToString(offer.getChildren()));
    }

    Element allocate = resourcingSpecs.getChild("allocate", resourcingSpecs.getNamespace());
    if (allocate != null) {
        properties.put("allocateinitiator", allocate.getAttributeValue("initiator"));
        properties.put("allocateinteraction", YAWLUtils.elementToString(allocate.getChildren()));
    }

    Element start = resourcingSpecs.getChild("start", resourcingSpecs.getNamespace());
    if (start != null) {
        properties.put("startinitiator", start.getAttributeValue("initiator"));
        properties.put("startinteraction", YAWLUtils.elementToString(start.getChildren()));
    }

    Element privileges = resourcingSpecs.getChild("privileges", resourcingSpecs.getNamespace());
    if (privileges != null) {
        properties.put("privileges", YAWLUtils.elementToString(privileges.getChildren()));
    }

    return properties;
}

From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutArranger.java

License:Open Source License

private void createVertexesAndFlows(Element yawlProcessControlElements) {
    List<Element> vertexes = new LinkedList<Element>();
    vertexes.addAll(yawlProcessControlElements.getChildren());
    List<String> flowOpenTags = new LinkedList<String>();
    for (Element element : vertexes) {
        sb.append("<vertex id=\"" + element.getAttributeValue("id") + "\">");
        createFakeAttributes();//from w ww. j  a v  a  2s .  co m
        sb.append("</vertex>");
        flowOpenTags.addAll(searchFlows(element));
    }
    for (String flowOpenTag : flowOpenTags) {
        createFlow(flowOpenTag);
    }

}

From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutConverter.java

License:Open Source License

/**
 * @param netLayout//w  ww . j  av a 2 s . co  m
 * @param yawlFlow
 * @return
 */
private ArrayList<Point> convertFlowDockers(final NetLayout netLayout, final Element yawlFlow) {

    Element flowPorts = yawlFlow.getChild("ports", yawlNamespace);
    Integer inPort = Integer.valueOf(flowPorts.getAttributeValue("in"));
    Integer outPort = Integer.valueOf(flowPorts.getAttributeValue("out"));

    Point inDocker;
    Point outDocker;

    String targetId = yawlFlow.getAttributeValue("target");
    String sourceId = yawlFlow.getAttributeValue("source");

    // Source may have a SPLIT decorator or may be a condition
    if (netLayout.getVertexLayout(sourceId).isCondition()) {
        inDocker = YAWLMapping.CONDITION_PORT_MAP.get(inPort);
    } else {
        inDocker = convertTaskDocker(netLayout.getVertexLayout(sourceId).getSplitDecorator(), inPort);
    }

    // Target may have a JOIN decorator or may be a condition
    if (netLayout.getVertexLayout(targetId).isCondition()) {
        outDocker = YAWLMapping.CONDITION_PORT_MAP.get(outPort);
    } else {
        outDocker = convertTaskDocker(netLayout.getVertexLayout(targetId).getJoinDecorator(), outPort);
    }

    // Fallback in case the values in XML are wrong
    if (outDocker == null) {
        outDocker = YAWLMapping.TASK_PORT_MAP.get(14);
    }

    if (inDocker == null) {
        inDocker = YAWLMapping.TASK_PORT_MAP.get(14);
    }

    ArrayList<Point> dockers = new ArrayList<Point>();

    // Important to add as first Docker with source BasicShape coordinates
    dockers.add(inDocker);

    // Add bends from YAWL with coordinates of Diagram
    Element pointElement = yawlFlow.getChild("attributes", yawlNamespace).getChild("points", yawlNamespace);
    // points may be omitted in YAWL
    if (pointElement != null) {
        @SuppressWarnings("rawtypes")
        List pointList = pointElement.getChildren();
        if (pointList.size() > 2) {
            // Skip the first and last element,
            // as those will be added according to the port information
            for (int i = 1; i < pointList.size() - 1; i++) {
                if (pointList.get(i) instanceof Element) {
                    Element point = (Element) pointList.get(i);
                    String x = point.getAttributeValue("x");
                    String y = point.getAttributeValue("y");
                    dockers.add(new Point(parseDouble(x), parseDouble(y)));
                }
            }
        }
    }

    // Important to add as last Docker with target BasicShape coordinates
    dockers.add(outDocker);
    return dockers;
}

From source file:de.herm_detlef.java.application.io.Import.java

License:Apache License

private static void createNode(Element child) {

    List<Element> children = child.getChildren();

    if (children.isEmpty()) {

        switch (TAG.getValueOf(child.getName())) {
        case ID:// www. ja  va 2s.  c o m
            exerciseItem.setItemId(Integer.parseInt(child.getTextTrim()));
            break;
        case TEXT: {
            final String str = child.getTextTrim();
            if (isQuestionPart) {
                exerciseItem.addQuestionText(str);
            } else if (isAnswerPart) {
                Attribute mark = child
                        .getAttribute(ApplicationConstants.NAME_OF_XML_ATTRIBUTE_ANSWER_TEXT_MARK);
                if (mark != null) {
                    try {
                        exerciseItem.addAnswerText(str, mark.getBooleanValue());
                    } catch (DataConversionException e) {
                        Utilities.showErrorMessage(e.getClass().getSimpleName(), e.getMessage());
                        assert false : String.format("DataConversionException: %s", mark.toString()); // TODO
                        exerciseItem.addAnswerText(str, false);
                    }
                } else {
                    exerciseItem.addAnswerText(str, false);
                }

            } else if (isSolutionPart) {
                exerciseItem.addSolutionText(str);
            }
            break;
        }
        case CODE:
            if (isQuestionPart) {
                exerciseItem.addQuestionCode(child.getTextTrim());
            }
            break;
        case TEXT2:
            if (isQuestionPart) {
                exerciseItem.addQuestionText2(child.getTextTrim());
            }
            break;
        case CATALOG:
            // TODO empty catalog file
            break;
        default:
            assert false : String.format("%s", TAG.getValueOf(child.getName()).name()); // TODO
        }

        return;
    }

    for (Element aChild : children) {

        switch (TAG.getValueOf(aChild.getName())) {
        case ITEM:
            exerciseItem = new ExerciseItem();
            exerciseItemList.add(exerciseItem);
            break;
        case QUESTION:
            signalQuestion();
            break;
        case SINGLE_CHOICE_ANSWER:
            signalSingleChoiceAnswer();
            exerciseItem.createSingleChoiceModel();
            break;
        case MULTIPLE_CHOICE_ANSWER:
            signalMultipleChoiceAnswer();
            exerciseItem.createMultipleChoiceModel();
            break;
        case SOLUTION:
            signalSolution();
            break;
        case ID:
        case TEXT:
        case CODE:
        case TEXT2:
            break;
        default:
            assert false : String.format("%s", TAG.getValueOf(aChild.getName()).name()); // TODO
        }

        createNode(aChild);
    }
}

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

License:Apache License

public void merge() throws LaudatioException {
    try {/* w w  w. j  ava  2  s  . c  om*/
        if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()
                && !outputFile.getParentFile().mkdirs()) {
            throw new LaudatioException(
                    messages.getString("COULD NOT CREATE MERGED OUTPUTFILE: I CAN'T CREATE THE DIRECTORIES"));
        }

        Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0");
        Element root = new Element("teiCorpus", teiNS);
        Element documentRoot = new Element("teiCorpus", teiNS);
        Element preparationRoot = new Element("teiCorpus", teiNS);

        mergeMainCorpusHeader(root);
        mergeDocumentHeader(documentRoot);
        mergePreparationHeader(preparationRoot);

        root.addContent(documentRoot);
        documentRoot.addContent(documentRoot.getChildren().size(), preparationRoot);

        Document mergedDoc = new Document(root);

        // output the new XML
        XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
        xmlOut.output(mergedDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
        log.info(messages.getString("WRITTEN MERGED TEI"), outputFile.getPath());
    } catch (SAXException ex) {
        throw new LaudatioException(ex.getLocalizedMessage());
    } catch (JDOMException ex) {
        throw new LaudatioException(ex.getLocalizedMessage());
    } catch (IOException ex) {
        throw new LaudatioException(ex.getLocalizedMessage());
    }
}

From source file:de.ing_poetter.binview.BinaryFormat.java

License:Open Source License

public static BinaryFormat loadFromFile(final File f) {
    final SAXBuilder builder = new SAXBuilder();
    Document doc;//  w ww  .  j  av a2s. c o  m
    try {
        doc = builder.build(f);
        Element root = null;
        root = doc.getRootElement();

        if (false == ROOT_ELEMENT_NAME.equalsIgnoreCase(root.getName())) {
            System.err.println("Format has invalid root Element of " + root.getName());
            return null;
        }

        final BinaryFormat res = new BinaryFormat();

        final List<Element> vars = root.getChildren();
        for (int i = 0; i < vars.size(); i++) {
            final Element curVar = vars.get(i);
            final Variable v = VariableFactory.createVariableFrom(curVar);
            res.addVariable(v);
        }
        return res;
    } catch (final JDOMException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return null;
}

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);/*from   w w  w.j  a va  2 s . 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 va 2s .  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) {// ww w.j av a2 s  .c om
    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;
}