Example usage for org.jdom2 Element setNamespace

List of usage examples for org.jdom2 Element setNamespace

Introduction

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

Prototype

public Element setNamespace(Namespace namespace) 

Source Link

Document

Sets the element's Namespace .

Usage

From source file:de.nava.informa.utils.AtomParserUtils.java

License:Open Source License

/**
 * Clears namespace signature from the element and all of the children.
 *///from  w w w .  j a v a 2 s  . com
private static void clearNamespace(Element elt) {
    if (elt == null) {
        return;
    }

    elt.setNamespace(null);

    for (Object item : elt.getContent()) {
        if (item instanceof Element) {
            clearNamespace((Element) item);
        }
    }
}

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

License:Apache License

private void adjustNamespaces(final Element element) {
    element.setNamespace(null);
    final List<Namespace> namespaces = new ArrayList<Namespace>(element.getAdditionalNamespaces());
    for (final Namespace namespace : namespaces) {
        element.removeNamespaceDeclaration(namespace);
    }/*from w  w w.  j  av  a2s  .c o m*/
    element.setNamespace(ModuleXmlBuilder.NS);
    for (final Element child : element.getChildren()) {
        adjustNamespaces(child);
    }
}

From source file:de.smartics.maven.plugin.jboss.modules.util.XmlUtils.java

License:Apache License

public static void adjustNamespaces(final Element element, Namespace ns) {
    element.setNamespace(null);
    final List<Namespace> namespaces = new ArrayList<Namespace>(element.getAdditionalNamespaces());
    for (final Namespace namespace : namespaces) {
        element.removeNamespaceDeclaration(namespace);
    }/*w  ww  .  jav a 2  s .  co m*/
    element.setNamespace(ns);
    for (final Element child : element.getChildren()) {
        adjustNamespaces(child, ns);
    }
}

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java

License:Apache License

/**
 * This method sets a given namespace to the given element and any of its descendants whose 
 * name is a provided one and have no namespace.
 * @param name the name of the searched elements
 * @param rootElement the root element to begin the search at
 * @param namespace the namespace to set
 *//*www  .  j a  v a2  s  .  c  o m*/
private void setNamespaceToElementsByName(String name, Element rootElement, Namespace namespace) {
    IteratorIterable<Element> descendants = rootElement
            .getDescendants(Filters.element(name, Namespace.NO_NAMESPACE));
    for (Element descendant : descendants) {
        descendant.setNamespace(namespace);
    }
    if (rootElement.getName().equals(name) && rootElement.getNamespace().equals(Namespace.NO_NAMESPACE)) {
        rootElement.setNamespace(namespace);
    }
}

From source file:eu.himeros.hocr.FlatXml.java

License:Open Source License

private void init(File inFile, File outFile) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(inFile);
    Element root = doc.getRootElement();
    Namespace oldns = root.getNamespace();
    Element newRoot = new Element("html", "http://www.w3.org/1999/xhtml");
    Namespace xmlns = newRoot.getNamespace();
    Element head = root.getChild("head", oldns);
    head.setNamespace(xmlns);
    for (Element child : head.getChildren())
        child.setNamespace(xmlns);/*from  w w w .ja va2 s  . co m*/
    Element title = new Element("title", xmlns);
    title.addContent("ocr");
    if (head != null)
        head.addContent(title);
    Element body = root.getChild("body", oldns);
    body.setNamespace(xmlns);
    /*Element oldPage;
    try{
    oldPage=body.getChild("div",xmlns);
    }catch(Exception ex){
    oldPage=new Element("div",xmlns);
    }*/
    Element page = new Element("div", xmlns);
    page.setAttribute("class", "ocr_page");
    page.setAttribute("id", "i" + inFile.getName().substring(1).replace(".html", ".png"));
    XPathExpression<Element> xpath = XPathFactory.instance().compile("//*[@class='ocr_carea']",
            Filters.element(), null, Namespace.getNamespace("ns", "http://www.w3.org/1999/xhtml"));
    List<Element> careaElL = xpath.evaluate(body);
    for (Element careaEl : careaElL) {
        page.addContent(new Comment("<div class=\"" + careaEl.getAttributeValue("class") + "\" title=\""
                + careaEl.getAttributeValue("title") + "\">"));
        for (Element pEl : careaEl.getChildren()) {
            page.addContent(new Comment("<p>"));
            for (Element lineEl : pEl.getChildren()) {
                lineEl.removeAttribute("id");
                lineEl.setNamespace(xmlns);
                for (Element child : lineEl.getChildren()) {
                    child.removeAttribute("id");
                    child.removeAttribute("lang");
                    child.removeAttribute("lang", xmlns);
                    child.setNamespace(xmlns);
                }
                page.addContent(lineEl.clone());
            }
            page.addContent(new Comment("</p>"));
        }
        page.addContent(new Comment("</div>"));
    }
    //oldPage.detach();
    if (body != null) {
        body.removeContent();
        body.addContent(page);
    }
    newRoot.addContent(root.removeContent());
    doc.detachRootElement();
    doc.setRootElement(newRoot);
    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    xmlOutputter.output(doc, new BufferedWriter(new FileWriter(outFile)));
}

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

License:Apache License

/**
 * Recursively apply a default namespace to an element tree. This will log
 * instances that are changed at the root of a tree (but not elements
 * underneath that root).//  www .j av a2s. co  m
 *
 * @param element
 *          target root element
 * @param namespace
 *          namespace to apply as default
 * @param shouldLog
 *          {@code true} if logging should be applied to any matches
 */
void applyDefaultNamespaceRecursively(Element element, Namespace namespace, boolean shouldLog) {
    if (Namespace.NO_NAMESPACE.equals(element.getNamespace())) {
        if (shouldLog) {
            getLog().info(
                    String.format("Applying default namespace to element tree root '%s'", element.getName()));
            shouldLog = false;
        }
        element.setNamespace(namespace);
    }
    for (Element child : element.getChildren()) {
        applyDefaultNamespaceRecursively(child, namespace, shouldLog);
    }
}

From source file:nl.nn.adapterframework.util.XmlBuilder.java

License:Apache License

private void addNamespaceRecursive(Element element, Namespace namespace) {
    if (StringUtils.isEmpty(element.getNamespaceURI())) {
        element.setNamespace(namespace);
        List<Element> childList = element.getChildren();
        if (!childList.isEmpty()) {
            for (Element child : childList) {
                addNamespaceRecursive(child, namespace);
            }/*from   ww  w .j  a v a 2s  . co  m*/
        }
    }
}

From source file:org.artifactory.version.converter.NamespaceConverter.java

License:Open Source License

private void changeNameSpace(Element element, Namespace ns) {
    element.setNamespace(ns);
    for (Object childElements : element.getChildren()) {
        changeNameSpace((Element) childElements, ns);
    }//from ww w  .  jav a2 s.  co  m
}

From source file:org.dvlyyon.net.netconf.exception.NetconfException.java

License:Open Source License

/**
 * Converts the NetconfException to its XML version.
 *
 * @return  XML-ized version of the exception, similar to what you would see on the wire.
 *///ww  w.  j a  v  a 2s  . c om
public Element toXml() {
    final Element root = new Element("rpc-error", s_xmlns);
    final Element type = new Element("error-type", s_xmlns);
    type.setText(m_type.toString());
    root.addContent(type);
    final Element tag = new Element("error-tag", s_xmlns);
    type.setText(m_tag.getNetconfTag());
    root.addContent(tag);
    final Element severity = new Element("error-severity", s_xmlns);
    type.setText(m_severity.toString());
    root.addContent(severity);
    final Element message = new Element("error-message", s_xmlns);
    type.setText(m_message);
    root.addContent(message);
    if (m_path != null) {
        final Element path = new Element("error-path", s_xmlns);
        path.addContent(m_path);
        root.addContent(path);
    }
    if (m_info != null) {
        try {
            // Note: the info tag may have a different namespace; we lose it in the transformation
            Element info = XmlUtils.fromXmlString(m_info);
            info.setNamespace(s_xmlns);
            root.addContent(info);
        } catch (final Exception ex) {
            s_logger.error("Error converting NetconfException to XML");
            if (s_logger.isDebugEnabled()) {
                s_logger.error(ex, ex);
            }
        }
    }
    return root;
}

From source file:org.goobi.production.export.ExportXmlLog.java

License:Open Source License

/**
 * This method creates a new xml document with process metadata
 * //  w w w.  j  a va  2  s  .  co  m
 * @param process the process to export
 * @return a new xml document
 * @throws ConfigurationException
 */
public Document createDocument(Process process, boolean addNamespace) {

    Element processElm = new Element("process");
    Document doc = new Document(processElm);

    processElm.setAttribute("processID", String.valueOf(process.getId()));

    Namespace xmlns = Namespace.getNamespace("http://www.goobi.io/logfile");
    processElm.setNamespace(xmlns);
    // namespace declaration
    if (addNamespace) {

        Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        processElm.addNamespaceDeclaration(xsi);
        Attribute attSchema = new Attribute("schemaLocation",
                "http://www.goobi.io/logfile" + " XML-logfile.xsd", xsi);
        processElm.setAttribute(attSchema);
    }
    // process information

    ArrayList<Element> processElements = new ArrayList<>();
    Element processTitle = new Element("title", xmlns);
    processTitle.setText(process.getTitel());
    processElements.add(processTitle);

    Element project = new Element("project", xmlns);
    project.setText(process.getProjekt().getTitel());
    processElements.add(project);

    Element date = new Element("time", xmlns);
    date.setAttribute("type", "creation date");
    date.setText(String.valueOf(process.getErstellungsdatum()));
    processElements.add(date);

    Element ruleset = new Element("ruleset", xmlns);
    ruleset.setText(process.getRegelsatz().getDatei());
    processElements.add(ruleset);

    Element comment = new Element("comments", xmlns);
    List<LogEntry> log = process.getProcessLog();
    for (LogEntry entry : log) {
        Element commentLine = new Element("comment", xmlns);
        commentLine.setAttribute("type", entry.getType().getTitle());
        commentLine.setAttribute("user", entry.getUserName());
        commentLine.setText(entry.getContent());
        if (StringUtils.isNotBlank(entry.getSecondContent())) {
            comment.setAttribute("secondField", entry.getSecondContent());
        }
        if (StringUtils.isNotBlank(entry.getThirdContent())) {
            comment.setAttribute("thirdField", entry.getThirdContent());
        }
        comment.addContent(commentLine);
    }

    processElements.add(comment);

    if (process.getBatch() != null) {
        Element batch = new Element("batch", xmlns);
        batch.setText(String.valueOf(process.getBatch().getBatchId()));
        if (StringUtils.isNotBlank(process.getBatch().getBatchName())) {
            batch.setAttribute("batchName", process.getBatch().getBatchName());
        }
        if (process.getBatch().getStartDate() != null) {
            batch.setAttribute("startDate", Helper.getDateAsFormattedString(process.getBatch().getStartDate()));
        }

        if (process.getBatch().getEndDate() != null) {
            batch.setAttribute("endDate", Helper.getDateAsFormattedString(process.getBatch().getEndDate()));
        }

        processElements.add(batch);
    }

    List<Element> processProperties = new ArrayList<>();
    List<ProcessProperty> propertyList = PropertyParser.getInstance().getPropertiesForProcess(process);
    for (ProcessProperty prop : propertyList) {
        Element property = new Element("property", xmlns);
        property.setAttribute("propertyIdentifier", prop.getName());
        if (prop.getValue() != null) {
            property.setAttribute("value", prop.getValue());
        } else {
            property.setAttribute("value", "");
        }

        Element label = new Element("label", xmlns);

        label.setText(prop.getName());
        property.addContent(label);
        processProperties.add(property);
    }
    if (processProperties.size() != 0) {
        Element properties = new Element("properties", xmlns);
        properties.addContent(processProperties);
        processElements.add(properties);
    }

    // step information
    Element steps = new Element("steps", xmlns);
    List<Element> stepElements = new ArrayList<>();
    for (Step s : process.getSchritteList()) {
        Element stepElement = new Element("step", xmlns);
        stepElement.setAttribute("stepID", String.valueOf(s.getId()));

        Element steptitle = new Element("title", xmlns);
        steptitle.setText(s.getTitel());
        stepElement.addContent(steptitle);

        Element state = new Element("processingstatus", xmlns);
        state.setText(s.getBearbeitungsstatusAsString());
        stepElement.addContent(state);

        Element begin = new Element("time", xmlns);
        begin.setAttribute("type", "start time");
        begin.setText(s.getBearbeitungsbeginnAsFormattedString());
        stepElement.addContent(begin);

        Element end = new Element("time", xmlns);
        end.setAttribute("type", "end time");
        end.setText(s.getBearbeitungsendeAsFormattedString());
        stepElement.addContent(end);

        if (s.getBearbeitungsbenutzer() != null && s.getBearbeitungsbenutzer().getNachVorname() != null) {
            Element user = new Element("user", xmlns);
            user.setText(s.getBearbeitungsbenutzer().getNachVorname());
            stepElement.addContent(user);
        }
        Element editType = new Element("edittype", xmlns);
        editType.setText(s.getEditTypeEnum().getTitle());
        stepElement.addContent(editType);

        stepElements.add(stepElement);
    }
    if (stepElements != null) {
        steps.addContent(stepElements);
        processElements.add(steps);
    }

    // template information
    Element templates = new Element("originals", xmlns);
    List<Element> templateElements = new ArrayList<>();
    for (Template v : process.getVorlagenList()) {
        Element template = new Element("original", xmlns);
        template.setAttribute("originalID", String.valueOf(v.getId()));

        List<Element> templateProperties = new ArrayList<>();
        for (Templateproperty prop : v.getEigenschaftenList()) {
            Element property = new Element("property", xmlns);
            property.setAttribute("propertyIdentifier", prop.getTitel());
            if (prop.getWert() != null) {
                property.setAttribute("value", prop.getWert());
            } else {
                property.setAttribute("value", "");
            }

            Element label = new Element("label", xmlns);

            label.setText(prop.getTitel());
            property.addContent(label);

            templateProperties.add(property);
            if (prop.getTitel().equals("Signatur")) {
                Element secondProperty = new Element("property", xmlns);
                secondProperty.setAttribute("propertyIdentifier", prop.getTitel() + "Encoded");
                if (prop.getWert() != null) {
                    secondProperty.setAttribute("value", "vorl:" + prop.getWert());
                    Element secondLabel = new Element("label", xmlns);
                    secondLabel.setText(prop.getTitel());
                    secondProperty.addContent(secondLabel);
                    templateProperties.add(secondProperty);
                }
            }
        }
        if (templateProperties.size() != 0) {
            Element properties = new Element("properties", xmlns);
            properties.addContent(templateProperties);
            template.addContent(properties);
        }
        templateElements.add(template);
    }
    if (templateElements != null) {
        templates.addContent(templateElements);
        processElements.add(templates);
    }

    // digital document information
    Element digdoc = new Element("digitalDocuments", xmlns);
    List<Element> docElements = new ArrayList<>();
    for (Masterpiece w : process.getWerkstueckeList()) {
        Element dd = new Element("digitalDocument", xmlns);
        dd.setAttribute("digitalDocumentID", String.valueOf(w.getId()));

        List<Element> docProperties = new ArrayList<>();
        for (Masterpieceproperty prop : w.getEigenschaftenList()) {
            Element property = new Element("property", xmlns);
            property.setAttribute("propertyIdentifier", prop.getTitel());
            if (prop.getWert() != null) {
                property.setAttribute("value", prop.getWert());
            } else {
                property.setAttribute("value", "");
            }

            Element label = new Element("label", xmlns);

            label.setText(prop.getTitel());
            property.addContent(label);
            docProperties.add(property);
        }
        if (docProperties.size() != 0) {
            Element properties = new Element("properties", xmlns);
            properties.addContent(docProperties);
            dd.addContent(properties);
        }
        docElements.add(dd);
    }
    if (docElements != null) {
        digdoc.addContent(docElements);
        processElements.add(digdoc);
    }
    // history
    List<HistoryEvent> eventList = HistoryManager.getHistoryEvents(process.getId());
    if (eventList != null && !eventList.isEmpty()) {
        List<Element> eventElementList = new ArrayList<>(eventList.size());

        for (HistoryEvent event : eventList) {
            Element element = new Element("historyEvent", xmlns);
            element.setAttribute("id", "" + event.getId());
            element.setAttribute("date", Helper.getDateAsFormattedString(event.getDate()));
            element.setAttribute("type", event.getHistoryType().getTitle());

            if (event.getNumericValue() != null) {
                element.setAttribute("numeric_value", "" + event.getNumericValue());
            }
            if (event.getStringValue() != null) {
                element.setText(event.getStringValue());
            }
            eventElementList.add(element);
        }

        if (!eventElementList.isEmpty()) {
            Element metadataElement = new Element("history", xmlns);
            metadataElement.addContent(eventElementList);
            processElements.add(metadataElement);
        }
    }

    // metadata
    List<StringPair> metadata = MetadataManager.getMetadata(process.getId());
    if (metadata != null && !metadata.isEmpty()) {
        List<Element> mdlist = new ArrayList<>();
        for (StringPair md : metadata) {
            String name = md.getOne();
            String value = md.getTwo();
            if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(name)) {
                Element element = new Element("metadata", xmlns);
                element.setAttribute("name", name);
                element.addContent(value);
                mdlist.add(element);
            }
        }
        if (!mdlist.isEmpty()) {
            Element metadataElement = new Element("metadatalist", xmlns);
            metadataElement.addContent(mdlist);
            processElements.add(metadataElement);
        }
    }
    // METS information
    Element metsElement = new Element("metsInformation", xmlns);
    List<Element> metadataElements = new ArrayList<>();

    try {
        String filename = process.getMetadataFilePath();
        Document metsDoc = new SAXBuilder().build(filename);
        Document anchorDoc = null;
        String anchorfilename = process.getMetadataFilePath().replace("meta.xml", "meta_anchor.xml");
        Path anchorFile = Paths.get(anchorfilename);
        if (StorageProvider.getInstance().isFileExists(anchorFile)
                && StorageProvider.getInstance().isReadable(anchorFile)) {
            anchorDoc = new SAXBuilder().build(anchorfilename);
        }

        List<Namespace> namespaces = getNamespacesFromConfig();

        HashMap<String, String> fields = getMetsFieldsFromConfig(false);
        for (String key : fields.keySet()) {
            List<Element> metsValues = getMetsValues(fields.get(key), metsDoc, namespaces);
            for (Element element : metsValues) {
                Element ele = new Element("property", xmlns);
                ele.setAttribute("name", key);
                ele.addContent(element.getTextTrim());
                metadataElements.add(ele);
            }
        }

        if (anchorDoc != null) {
            fields = getMetsFieldsFromConfig(true);
            for (String key : fields.keySet()) {
                List<Element> metsValues = getMetsValues(fields.get(key), anchorDoc, namespaces);
                for (Element element : metsValues) {
                    Element ele = new Element("property", xmlns);
                    ele.setAttribute("name", key);
                    ele.addContent(element.getTextTrim());
                    metadataElements.add(ele);
                }
            }
        }

        if (metadataElements != null) {
            metsElement.addContent(metadataElements);
            processElements.add(metsElement);
        }

    } catch (SwapException e) {
        logger.error(e);
    } catch (DAOException e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    } catch (InterruptedException e) {
        logger.error(e);
    } catch (JDOMException e) {
        logger.error(e);
    } catch (JaxenException e) {
        logger.error(e);
    }

    processElm.setContent(processElements);
    return doc;
}