Example usage for org.jdom2 Element addContent

List of usage examples for org.jdom2 Element addContent

Introduction

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

Prototype

@Override
public Element addContent(final Collection<? extends Content> newContent) 

Source Link

Document

Appends all children in the given collection to the end of the content list.

Usage

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void setTargetSegment(Element p_trgElement, String p_target, String p_encoding)
        throws UnsupportedEncodingException {
    if (p_target == null || p_target.trim().length() == 0)
        return;/*from  www.  ja v a  2s .  co  m*/

    String target = new String(p_target.getBytes("UTF-8"), p_encoding);
    try {
        StringReader stringReader = new StringReader("<target>" + p_target + "</target>");
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(stringReader);
        Element elem = doc.getRootElement().clone().detach();
        setNamespace(elem, p_trgElement.getNamespace());
        //Delete Original Target Segment.
        p_trgElement.removeContent();
        for (int i = 0; i < elem.getContentSize(); i++) {
            p_trgElement.addContent(elem.getContent(i).clone().detach());
        }
    } catch (Exception e) {
        p_trgElement.setText(target);
    }
}

From source file:com.googlecode.mipnp.mediaserver.cds.DidlLiteDocument.java

License:Open Source License

public void addCdsObject(CdsObject obj) {
    Element element = null;
    if (obj.isContainer()) {
        element = new Element("container", NS_DEFAULT);
        addProperty(element, obj, CdsConstants.PROPERTY_SEARCHABLE, "true");
    } else {//from  ww  w.ja v  a2s.com
        element = new Element("item", NS_DEFAULT);
    }

    for (String reqProp : REQUIRED_PROPERTIES) {
        addProperty(element, obj, reqProp);
    }

    // TODO: temp fix, res location should be added to CdsObject as a property
    Resource res = obj.getResource();
    if (res != null && (filter.equals("*") || filter.contains("res"))) {
        Element resEl = new Element(CdsConstants.PROPERTY_RES, NS_DEFAULT);
        resEl.setAttribute("protocolInfo", "http-get:*:" + res.getMimeType() + ":*");
        resEl.setText(mediaLocation.toString() + "/" + obj.getId());
        element.addContent(resEl);
    }
    // END temp fix

    if (filter.equals("*")) {
        for (String property : obj.getProperties()) {
            if (!REQUIRED_PROPERTIES.contains(property)) {
                addProperty(element, obj, property);
            }
        }
    } else {
        String[] filterParts = filter.split("(?<!\\\\),");
        for (int i = 0; i < filterParts.length; i++) {
            filterParts[i] = filterParts[i].replaceAll("\\\\,", ",");
            if (!REQUIRED_PROPERTIES.contains(filterParts[i])) {
                addProperty(element, obj, filterParts[i]);
            }
        }
    }

    document.getRootElement().addContent(element);
}

From source file:com.googlecode.mipnp.mediaserver.cds.DidlLiteDocument.java

License:Open Source License

private void addProperty(Element element, CdsObject obj, String property, String propertyValue) {

    if (property.contains("@")) {
        Element parentElement = null;
        String strParentElement = property.substring(0, property.indexOf('@'));
        if (strParentElement.equals("")) {
            parentElement = element;/*from  w w  w . j  a v  a2 s .  co  m*/
        } else {
            parentElement = element.getChild(removePrefix(strParentElement), getNamespace(strParentElement));
            if (parentElement == null) {
                parentElement = new Element(removePrefix(strParentElement), getNamespace(strParentElement));
                parentElement.setText(obj.getProperty(strParentElement));
                element.addContent(parentElement);
            }
        }
        parentElement.setAttribute(property.substring(property.indexOf('@') + 1), propertyValue);
    } else {
        Element newElement = new Element(removePrefix(property), getNamespace(property));
        newElement.setText(propertyValue);
        element.addContent(newElement);
    }
}

From source file:com.iana.dver.pdf.scrapper.DVERScrapperTask.java

/**
 * Step - 2 : Generate XML from Text stripper
 * /* w  w w  . j  ava 2  s. c o m*/
 * @param tempTextFile
 * @throws IOException
 */
private void generateDverXML(String fileName, PDFTextStripperByArea stripper) throws IOException {

    File outputFile = new File(xmlDir + fileName + ".xml");
    OutputStream fos = new FileOutputStream(outputFile);

    Element dver = new Element("DVER");
    Document doc = new Document(dver);

    // Generate Address Node
    String addressDetail = stripper.getTextForRegion("ADDRESS");
    String[] addressArr = addressDetail.split("\\n");
    Element addressNode = new Element("ADDRESS");
    addressNode.addContent(new Element("ADDRESS_1").setText(addressArr[0] + "\\n" + addressArr[1]));
    addressNode.addContent(new Element("ADDRESS_2").setText(addressArr[2] + "\\n" + addressArr[3]));
    if (addressArr.length > 4) {
        String[] tempContact = addressArr[4].split(" ");
        addressNode.addContent(new Element("PHONE").setText(tempContact[1]));
        addressNode.addContent(new Element("FAX").setText(tempContact[3]));
    } else {
        addressNode.addContent(new Element("PHONE").setText(""));
        addressNode.addContent(new Element("FAX").setText(""));
    }
    doc.getRootElement().addContent(addressNode);

    // Report Information Node
    String reportDetail = stripper.getTextForRegion("REPORT_INFO");
    String[] reportDetailArr = reportDetail.split("\\n");
    Element reportInfoNode = new Element("REPORT_INFO");

    for (int i = 0; i < reportDetailArr.length; i++) {
        if (i == 0) {
            String[] reportInfo = reportDetailArr[i].split(":");
            reportInfoNode.addContent(new Element("REPORT_NUMBER").setText(reportInfo[1]));
        } else if (i == 1) {
            String[] inspDetail = reportDetailArr[i].split(":");
            inspDetail[1] = inspDetail[1].replaceAll("Certification Date", "");
            reportInfoNode.addContent(new Element("INSPECTION_DATE").setText(inspDetail[1]));
            reportInfoNode.addContent(new Element("CERTIFICATION_DATE").setText(inspDetail[2]));
        } else if (i == 2) {
            String timings = reportDetailArr[i];
            timings = timings.replaceAll("Time Started:", "");
            timings = timings.replaceAll("Time Ended:", "");
            String[] timeDetail = timings.split(" ");
            reportInfoNode.addContent(new Element("START_TIME").setText(timeDetail[0]));
            reportInfoNode.addContent(new Element("END_TIME").setText(timeDetail[1]));
        } else if (i == 3) {
            String[] reportInfo = reportDetailArr[i].split(":");
            reportInfoNode.addContent(new Element("INSPECTION_LEVEL").setText(reportInfo[1]));
        } else if (i == 4) {
            String[] reportInfo = reportDetailArr[i].split(":");
            reportInfoNode.addContent(new Element("INSPECTION_TYPE").setText(reportInfo[1]));
        }
    }
    doc.getRootElement().addContent(reportInfoNode);

    // INTERMODAL EQUIPMENT PROVIDER INFORMATION
    String iepDetail = stripper.getTextForRegion("IEP_INFO");
    String[] iepDetailArr = iepDetail.split("\\n");
    Element iepInfoNode = new Element("IEP_INFO");

    for (int j = 0; j < iepDetailArr.length; j++) {
        if (j == 1) {
            iepInfoNode.addContent(new Element("IEP_NAME").setText(iepDetailArr[j]));
        } else if (j == 2) {
            String[] tempIepInfo = iepDetailArr[j].split(" ");
            iepInfoNode.addContent(new Element("US_DOT").setText(tempIepInfo[3]));
            iepInfoNode.addContent(new Element("DATA_SOURCE").setText(tempIepInfo[6]));
        }
    }
    doc.getRootElement().addContent(iepInfoNode);

    // MOTOR CARRIER INFORMATION
    String mcDetail = stripper.getTextForRegion("MC_INFO");
    String[] mcDetailArr = mcDetail.split("\\n");
    Element mcDetailNode = new Element("MC_INFO");

    for (int k = 0; k < mcDetailArr.length; k++) {
        if (k == 1) {
            String mcCompAndDriver = mcDetailArr[k].replaceAll("Driver:", "");
            mcDetailNode.addContent(new Element("MC_NAME").setText(mcCompAndDriver.split(" ")[0]));
            mcDetailNode.addContent(new Element("DRIVER").setText(mcCompAndDriver.split(" ")[1]));
        } else if (k == 2) {
            mcDetailNode.addContent(new Element("MC_ADD_1").setText(mcDetailArr[k]));
        } else if (k == 3) {
            mcDetailNode.addContent(new Element("MC_ADD_2").setText(mcDetailArr[k]));
        } else if (k == 4) {
            String tempStr = mcDetailArr[k];
            tempStr = tempStr.replaceAll("USDOT #:", "");
            tempStr = tempStr.replaceAll("Phone #:", "");
            String[] otherDetails = tempStr.trim().split(" ");
            mcDetailNode
                    .addContent(new Element("US_DOT").setText(otherDetails[0] != null ? otherDetails[0] : ""));
            mcDetailNode
                    .addContent(new Element("PHONE").setText(otherDetails[2] != null ? otherDetails[2] : ""));
        } else if (k == 5) {
            String tempStr = mcDetailArr[k];
            tempStr = tempStr.replaceAll("MC/MX #:", "");
            tempStr = tempStr.replaceAll("Fax #:", "");
            String[] otherDetails = tempStr.trim().split(" ");
            mcDetailNode
                    .addContent(new Element("MC_MX").setText(otherDetails[0] != null ? otherDetails[0] : ""));
            mcDetailNode.addContent(new Element("FAX")
                    .setText(otherDetails.length > 1 && otherDetails[1] != null ? otherDetails[2] : ""));
        } else if (k == 6) {
            mcDetailArr[k] = mcDetailArr[k].replaceAll("State #:", "");
            mcDetailNode.addContent(new Element("STATE").setText(mcDetailArr[k] != null ? mcDetailArr[k] : ""));
        } else if (k == 7) {
            mcDetailArr[k] = mcDetailArr[k].replaceAll("Origin:", "");
            mcDetailArr[k] = mcDetailArr[k].replaceAll("Destination:", "");
            mcDetailNode.addContent(
                    new Element("ORIGIN_DESTINATION").setText(mcDetailArr[k] != null ? mcDetailArr[k] : ""));
        }
    }
    doc.getRootElement().addContent(mcDetailNode);

    // VEHICLE IDENTIFICATION
    String vehicleIdentification = stripper.getTextForRegion("VEHICLE_ID");
    String[] vehicleIdArr = vehicleIdentification.split("\\n");
    Element vehicleIdNode = new Element("VEHICLE_IDENTIFICATION");

    for (int l = 0; l < vehicleIdArr.length; l++) {
        if (l == 2) {
            String[] vehicleDetails = vehicleIdArr[l].trim().split(" ");
            for (int m = 0; m < vehicleDetails.length; m++) {
                if (m == 0) {
                    vehicleIdNode.addContent(
                            new Element("UNIT").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 1) {
                    vehicleIdNode.addContent(
                            new Element("TYPE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 2) {
                    vehicleIdNode.addContent(
                            new Element("MAKE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 3) {
                    vehicleIdNode.addContent(
                            new Element("YEAR").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 4) {
                    vehicleIdNode.addContent(
                            new Element("STATE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 5) {
                    vehicleIdNode.addContent(
                            new Element("LICENSE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 6) {
                    vehicleIdNode.addContent(new Element("EQUIPMENT_ID")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 7) {
                    vehicleIdNode.addContent(new Element("UNIT_VIN")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 8) {
                    vehicleIdNode.addContent(
                            new Element("GVWR").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 9) {
                    vehicleIdNode.addContent(new Element("ISSUED_DECAL")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 10) {
                    vehicleIdNode.addContent(new Element("OOS_STKR")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                }
            }

        }
    }
    doc.getRootElement().addContent(vehicleIdNode);

    // Brake Adjustments
    String breakAdjustment = stripper.getTextForRegion("BREAK_ADJ");
    String[] breakAdjustmentArr = breakAdjustment.split("-");
    Element breakAdjustmentNode = new Element("BREAK_ADJUSTMENT");

    for (int n = 0; n < breakAdjustmentArr.length; n++) {
        if (n == 1) {
            breakAdjustmentNode.setText(breakAdjustmentArr[n] != null ? breakAdjustmentArr[n] : "");
        }
    }
    doc.getRootElement().addContent(breakAdjustmentNode);

    // Other Chassis Violation details
    String otherViolationDetail = stripper.getTextForRegion("OTHER_CHASSIS_VIOLATION");
    String[] otherViolationDetailArr = otherViolationDetail.split("\\n");
    Element otherViolationElement = new Element("OTHER_CHASSIS_VIOLATION");

    for (int ocnt = 0; ocnt < (otherViolationDetailArr.length - 1); ocnt++) {
        if (ocnt > 1) {
            String[] tempOtrDetail = otherViolationDetailArr[ocnt].split(" ");
            Element violations = new Element("OTHER_VIOLATIONS");
            for (int temp = 0; temp < tempOtrDetail.length; temp++) {
                if (temp == 0) {
                    violations.addContent(new Element("VIO_CODE").setText(tempOtrDetail[temp]));
                } else if (temp == 1) {
                    violations.addContent(new Element("SECTION").setText(tempOtrDetail[temp]));
                } else if (temp == 2) {
                    violations.addContent(new Element("UNIT").setText(tempOtrDetail[temp]));
                } else if (temp == 3) {
                    violations.addContent(new Element("OOS").setText(tempOtrDetail[temp]));
                } else if (temp == 4) {
                    violations.addContent(new Element("NUMBER").setText(tempOtrDetail[temp]));
                } else if (temp == 5) {
                    violations.addContent(new Element("VERIFY").setText(tempOtrDetail[temp]));
                } else if (temp == 6) {
                    violations.addContent(new Element("CRASH").setText(tempOtrDetail[temp]));
                } else if (temp == 7) {
                    violations.addContent(new Element("VIO_DESC").setText(tempOtrDetail[temp]));
                }
            }
            otherViolationElement.addContent(violations);
        }
    }
    doc.getRootElement().addContent(otherViolationElement);

    String driverNotes = stripper.getTextForRegion("DRIVER_NOTES");
    Element driverNotesNode = new Element("NOTES_TO_DRIVER");
    driverNotesNode.setText(driverNotes);
    doc.getRootElement().addContent(driverNotesNode);

    String iepNotes = stripper.getTextForRegion("IEP_NOTES");
    Element iepNotesNode = new Element("NOTES_TO_IEP");
    iepNotesNode.setText(iepNotes);
    doc.getRootElement().addContent(iepNotesNode);

    String creationNotes = stripper.getTextForRegion("CREATION_NOTES");
    Element creationNotesNode = new Element("CREATED_BY");
    creationNotesNode.setText(creationNotes.split("\\n")[1]);
    doc.getRootElement().addContent(creationNotesNode);

    XMLOutputter xmlOutput = new XMLOutputter();
    // display nice nice
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(doc, fos);
    fos.flush();
    fos.close();

}

From source file:com.init.octo.schema.XSDSchema.java

License:Open Source License

private void addElementToDocument(XSDElement schemaParent, Element documentParent, Element newChild) {

    /* If no schema defined or no children have been added to the parent then we can safely just add our child... */

    if (schemaParent == null || documentParent.getChildren().size() == 0) {
        documentParent.addContent(newChild);
    } else {//w ww  .  ja  v  a 2  s. co m
        List<XSDElement> xsdChildren = schemaParent.getChildren();
        Object[] children = documentParent.getChildren().toArray();
        Element child = null;
        String newChildName = newChild.getName();
        boolean afterFlag = false;
        int childIdx = 0;

        for (childIdx = 0; childIdx < children.length && afterFlag == false; childIdx++) {

            child = (Element) children[childIdx];

            if (child.getName().equals(newChildName) == false) {
                /* New child so check in XSD list of children to see if our new child goes before it... */
                for (XSDElement el : xsdChildren) {
                    /* If the new child name equals the XSD name then we can add after the current position... */
                    if (el.getName().equals(newChildName)) {
                        afterFlag = true;
                        childIdx--;
                        break;
                    } else if (el.getName().equals(child.getName())) {
                        break;
                    }
                }
            }

        }

        /* If the current child name equals the new child name then we need to go to the end of set of */
        /* those children before we can add our new child, i.e. new A must go after AAA<here>          */

        while (childIdx < children.length - 1 && child.getName().equals(newChildName)) {
            childIdx++;
            child = (Element) children[childIdx];
        }

        /* Now add the new child... */

        if (childIdx < children.length) {
            documentParent.addContent(childIdx, newChild);
        } else {
            documentParent.addContent(newChild);
        }
    }

}

From source file:com.izforge.izpack.util.xmlmerge.action.CompleteAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement) {
    if (originalElement != null) {
        outputParentElement.addContent((Element) originalElement.clone());
    } else {//from w ww.ja v  a2s.  c o  m
        if (patchElement != null) {
            outputParentElement.addContent((Element) patchElement.clone());
        }
    }
}

From source file:com.izforge.izpack.util.xmlmerge.action.DeleteAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement) {
    if (originalElement != null && patchElement == null) {
        outputParentElement.addContent((Element) originalElement.clone());
    }//  w w  w. j a  v a 2s. c  o  m
}

From source file:com.izforge.izpack.util.xmlmerge.action.DtdInsertAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement)
        throws AbstractXmlMergeException {

    Element element;/*  w w  w.j  av a  2  s .  c om*/

    if (originalElement != null) {
        element = (Element) originalElement.clone();
    } else {
        element = (Element) patchElement.clone();
    }

    DTD dtd = getDTD(outputParentElement);

    List<DTDElement> dtdElements = dtd.getItemsByType(DTDElement.class);

    // Find the corresponding element
    DTDElement parentDtdElement = null;
    for (DTDElement dtdElement : dtdElements) {
        if (dtdElement.getName().equals(outputParentElement.getName())) {
            parentDtdElement = dtdElement;
        }
    }

    if (parentDtdElement == null) {
        throw new ElementException(element, "Element " + outputParentElement.getName() + " not defined in DTD");
    } else {

        DTDItem item = parentDtdElement.getContent();

        if (item instanceof DTDAny) {
            // the parent element accepts anything in any order
            outputParentElement.addContent(element);
        } else if (item instanceof DTDContainer) {

            // List existing elements in output parent element
            List<Element> existingChildren = outputParentElement.getChildren();

            if (existingChildren.size() == 0) {
                // This is the first child
                outputParentElement.addContent(element);
            } else {

                List<String> orderedDtdElements = getOrderedDtdElements((DTDContainer) item);

                int indexOfNewElementInDtd = orderedDtdElements.indexOf(element.getName());
                logger.fine("index of element " + element.getName() + ": " + indexOfNewElementInDtd);

                int pos = existingChildren.size();

                // Calculate the position in the parent where we insert the
                // element
                for (int i = 0; i < existingChildren.size(); i++) {
                    String elementName = (existingChildren.get(i)).getName();
                    logger.fine(
                            "index of child " + elementName + ": " + orderedDtdElements.indexOf(elementName));
                    if (orderedDtdElements.indexOf(elementName) > indexOfNewElementInDtd) {
                        pos = i;
                        break;
                    }
                }

                logger.fine("adding element " + element.getName() + " add in pos " + pos);
                outputParentElement.addContent(pos, element);

            }

        }

    }

}

From source file:com.izforge.izpack.util.xmlmerge.action.FullMergeAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement)
        throws AbstractXmlMergeException {

    logger.fine("Merging: " + originalElement + " (original) and " + patchElement + " (patch)");

    Mapper mapper = (Mapper) m_mapperFactory.getOperation(originalElement, patchElement);

    if (originalElement == null) {
        outputParentElement.addContent(mapper.map(patchElement));
    } else if (patchElement == null) {
        outputParentElement.addContent((Content) originalElement.clone());
    } else {/*www .j a  v  a 2  s . c o  m*/

        Element workingElement = new Element(originalElement.getName(), originalElement.getNamespacePrefix(),
                originalElement.getNamespaceURI());
        addAttributes(workingElement, originalElement);

        logger.fine("Adding " + workingElement);
        outputParentElement.addContent(workingElement);

        doIt(workingElement, originalElement, patchElement);
    }

}

From source file:com.izforge.izpack.util.xmlmerge.action.FullMergeAction.java

License:Open Source License

/**
 * Performs the actual merge between two source elements.
 *
 * @param parentOut The merged element//from ww  w .j a  v  a2s.  c  om
 * @param origElement The first source element
 * @param patchElement The second source element
 * @throws AbstractXmlMergeException If an error occurred during the merge
 */
private void doIt(Element parentOut, Element origElement, Element patchElement)
        throws AbstractXmlMergeException {
    addAttributes(parentOut, patchElement);

    List<Content> origContentList = origElement.getContent();
    List<Content> patchContentList = patchElement.getContent();
    List<Content> unmatchedPatchContentList = new ArrayList<Content>();
    List<Content> matchedPatchContentList = new ArrayList<Content>();

    for (Content origContent : origContentList) {
        logger.fine("Checking original content: " + origContent + " for matching patch contents");
        if (origContent instanceof Element) {
            boolean patchMatched = false;

            for (Content patchContent : patchContentList) {
                logger.fine("Checking patch content: " + patchContent);

                if (patchContent instanceof Comment || patchContent instanceof Text) {
                    // skip and leave original comment or text
                    logger.fine("Skipped patch content: " + patchContent);
                } else if (!(patchContent instanceof Element)) {
                    throw new DocumentException(patchContent.getDocument(), "Contents of type "
                            + patchContent.getClass().getName() + " in patch document not supported");
                } else {
                    if (((Matcher) m_matcherFactory.getOperation((Element) patchContent, (Element) origContent))
                            .matches((Element) patchContent, (Element) origContent)) {
                        logger.fine("Apply matching patch: " + patchContent + " -> " + origContent);
                        applyAction(parentOut, (Element) origContent, (Element) patchContent);
                        patchMatched = true;
                        if (!matchedPatchContentList.contains(patchContent)) {
                            matchedPatchContentList.add(patchContent);
                        }
                    } else {
                        if (!unmatchedPatchContentList.contains(patchContent)) {
                            unmatchedPatchContentList.add(patchContent);
                        }
                    }
                    // Continue searching here for finding multiple matches
                }
            }

            if (!patchMatched) {
                logger.fine("Apply original: " + origContent);
                applyAction(parentOut, (Element) origContent, null);
            }
        } else if (origContent instanceof Comment || origContent instanceof Text) {
            // leave original comment or text
            parentOut.addContent((Content) origContent.clone());
        } else {
            throw new DocumentException(origContent.getDocument(), "Contents of type "
                    + origContent.getClass().getName() + " in original document not supported");
        }
    }

    for (Content unmatchedPatchContent : unmatchedPatchContentList) {
        if (!matchedPatchContentList.contains(unmatchedPatchContent)) {
            logger.fine("Apply unmatching patch: " + unmatchedPatchContent);
            applyAction(parentOut, null, (Element) unmatchedPatchContent);
        }
    }
}