Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

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

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:com.astronomy.project.Project.java

/**
 * Parse XML project//from   ww  w. j ava 2s . co  m
 * @param file XML file
 * @throws JDOMException XML error
 * @throws IOException IO error
 * @throws ProcessException Format error
 */
public void parseXML(File file) throws JDOMException, IOException, ProcessException {
    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = saxBuilder.build(file);
    Element raiz = document.getRootElement();
    name = raiz.getAttributeValue("nombre");
    List<Element> aa = raiz.getChild("alineamientos").getChildren();
    data.clear();

    for (Element e : aa) {
        data.add(new Alignment(e));
    }
}

From source file:com.athena.chameleon.engine.core.analyzer.parser.IbmWebBndXMIParser.java

License:Apache License

@Override
public Object parse(File file, AnalyzeDefinition analyzeDefinition) {
    Assert.notNull(file, "file cannot be null.");
    Assert.notNull(analyzeDefinition, "analyzeDefinition cannot be null.");

    this.analyzeDefinition = analyzeDefinition;

    // only zip and war
    String key = ChameleonConstants.ZIP_ROOT_DIR;

    if (StringUtils.isEmpty((String) ThreadLocalUtil.get(key))) {
        key = ChameleonConstants.WAR_ROOT_DIR;
    }/*w  w  w. j  ava  2 s . co  m*/

    PDFMetadataDefinition metadataDefinition = (PDFMetadataDefinition) ThreadLocalUtil
            .get(ChameleonConstants.PDF_METADATA_DEFINITION);
    EjbRecommend ejbRecommend = new EjbRecommend();

    try {
        ejbRecommend = new EjbRecommend();
        ejbRecommend.setItem(file.getName());
        ejbRecommend.setTransFlag(false);
        // zip, war
        ejbRecommend.setLocation(removeTempDir(file.getParent(), key));
        ejbRecommend.setContents(fileToString(file.getAbsolutePath()));

        metadataDefinition.getWebRecommendList().add(ejbRecommend);
    } catch (IOException e) {
        logger.error("IOException has occurred.", e);
    }

    SAXBuilder builder = null;
    Document doc = null;
    String context = null;

    try {
        builder = new SAXBuilder();
        doc = builder.build(file);

        // src/main/resources/jbossweb/jboss-web.xml
        String jbossWeb = fileToString(this.getClass().getResource("/jbossweb/jboss-web.xml").getFile());
        jbossWeb = jbossWeb.replaceAll("\\$\\{loaderRepository\\}",
                "com.athena.chameleon:loader=" + ThreadLocalUtil.get(ChameleonConstants.PROJECT_NAME));

        if (doc.getRootElement().getChild("context-root", doc.getRootElement().getNamespace()) != null) {
            context = doc.getRootElement().getChild("context-root", doc.getRootElement().getNamespace())
                    .getText();
            jbossWeb = jbossWeb.replaceAll("\\$\\{contextRoot\\}", context);
        } else {
            jbossWeb = jbossWeb.replaceAll("<context-root>\\$\\{contextRoot\\}</context-root>", "");
        }

        rewrite(new File(file.getParentFile(), "jboss-web.xml"), jbossWeb);

        ejbRecommend = new EjbRecommend();
        ejbRecommend.setItem("jboss-web.xml");
        ejbRecommend.setTransFlag(true);
        ejbRecommend.setLocation(removeTempDir(file.getParent(), key));
        ejbRecommend.setContents(jbossWeb);

        metadataDefinition.getWebRecommendList().add(ejbRecommend);
        metadataDefinition.getWebTransFileList()
                .add(ejbRecommend.getLocation() + File.separator + "jboss-web.xml");
    } catch (Exception e) {
        logger.error("Unhandled exception has occurred.", e);
        location = removeTempDir(file.getAbsolutePath(), key);
        stackTrace = StackTracer.getStackTrace(e);
        comments = "jboss-web.xml ? ?  ? ?.";
    } finally {
        if (StringUtils.isNotEmpty(stackTrace)) {
            exceptionInfo = new ExceptionInfo();
            exceptionInfo.setLocation(location);
            exceptionInfo.setStackTrace(stackTrace);
            exceptionInfo.setComments(comments);
            ((PDFMetadataDefinition) ThreadLocalUtil.get(ChameleonConstants.PDF_METADATA_DEFINITION))
                    .getExceptionInfoList().add(exceptionInfo);
        }
    }

    return ejbRecommend.getContents();
}

From source file:com.athena.chameleon.engine.core.analyzer.parser.JeusWebDDXMLParser.java

License:Apache License

@Override
public Object parse(File file, AnalyzeDefinition analyzeDefinition) {
    Assert.notNull(file, "file cannot be null.");
    Assert.notNull(analyzeDefinition, "analyzeDefinition cannot be null.");

    this.analyzeDefinition = analyzeDefinition;

    // only zip and war
    String key = ChameleonConstants.ZIP_ROOT_DIR;

    if (StringUtils.isEmpty((String) ThreadLocalUtil.get(key))) {
        key = ChameleonConstants.WAR_ROOT_DIR;
    }/*from   ww  w  .ja  v  a 2 s  .co  m*/

    PDFMetadataDefinition metadataDefinition = (PDFMetadataDefinition) ThreadLocalUtil
            .get(ChameleonConstants.PDF_METADATA_DEFINITION);
    EjbRecommend ejbRecommend = new EjbRecommend();

    try {
        ejbRecommend = new EjbRecommend();
        ejbRecommend.setItem(file.getName());
        ejbRecommend.setTransFlag(false);
        // zip, war
        ejbRecommend.setLocation(removeTempDir(file.getParent(), key));
        ejbRecommend.setContents(fileToString(file.getAbsolutePath()));

        metadataDefinition.getWebRecommendList().add(ejbRecommend);
    } catch (IOException e) {
        logger.error("IOException has occurred.", e);
    }

    //        try {
    //            CommonAnalyze commonAnalyze = new CommonAnalyze();
    //            commonAnalyze.setItem(file.getName());
    //            commonAnalyze.setLocation(removeTempDir(file.getParent()));
    //            commonAnalyze.setContents(fileToString(file.getAbsolutePath()));
    //            
    //            analyzeDefinition.getDescripterList().add(commonAnalyze);
    //        } catch (IOException e) {
    //            logger.error("IOException has occurred.", e);
    //        }

    SAXBuilder builder = null;
    Document doc = null;
    String context = null;

    try {
        builder = new SAXBuilder();
        doc = builder.build(file);

        // src/main/resources/jbossweb/jboss-web.xml
        String jbossWeb = fileToString(this.getClass().getResource("/jbossweb/jboss-web.xml").getFile());
        jbossWeb = jbossWeb.replaceAll("\\$\\{loaderRepository\\}",
                "com.athena.chameleon:loader=" + ThreadLocalUtil.get(ChameleonConstants.PROJECT_NAME));

        if (doc.getRootElement().getChild("context-root", doc.getRootElement().getNamespace()) != null) {
            context = doc.getRootElement().getChild("context-root", doc.getRootElement().getNamespace())
                    .getText();
            jbossWeb = jbossWeb.replaceAll("\\$\\{contextRoot\\}", context);
        } else {
            jbossWeb = jbossWeb.replaceAll("<context-root>\\$\\{contextRoot\\}</context-root>", "");
        }

        rewrite(new File(file.getParentFile(), "jboss-web.xml"), jbossWeb);

        ejbRecommend = new EjbRecommend();
        ejbRecommend.setItem("jboss-web.xml");
        ejbRecommend.setTransFlag(true);
        ejbRecommend.setLocation(removeTempDir(file.getParent(), key));
        ejbRecommend.setContents(jbossWeb);

        metadataDefinition.getWebRecommendList().add(ejbRecommend);
        metadataDefinition.getWebTransFileList()
                .add(ejbRecommend.getLocation() + File.separator + "jboss-web.xml");
    } catch (Exception e) {
        logger.error("Unhandled exception has occurred.", e);
        location = removeTempDir(file.getAbsolutePath(), key);
        stackTrace = StackTracer.getStackTrace(e);
        comments = "jboss-web.xml ? ?  ? ?.";
    } finally {
        if (StringUtils.isNotEmpty(stackTrace)) {
            exceptionInfo = new ExceptionInfo();
            exceptionInfo.setLocation(location);
            exceptionInfo.setStackTrace(stackTrace);
            exceptionInfo.setComments(comments);
            ((PDFMetadataDefinition) ThreadLocalUtil.get(ChameleonConstants.PDF_METADATA_DEFINITION))
                    .getExceptionInfoList().add(exceptionInfo);
        }
    }

    return doc;
}

From source file:com.bc.ceres.binio.binx.BinX.java

License:Open Source License

private CompoundType parseDocument(URI uri) throws IOException, BinXException {
    SAXBuilder builder = new SAXBuilder();
    Document document;
    try {/*from ww  w  . j  ava 2 s. c o m*/
        document = builder.build(uri.toURL());
    } catch (JDOMException e) {
        throw new BinXException(MessageFormat.format("Failed to read ''{0}''", uri), e);
    }
    Element binxElement = document.getRootElement();
    this.namespace = binxElement.getNamespace();
    parseParameters(binxElement);
    parseDefinitions(binxElement);
    return parseDataset(binxElement);
}

From source file:com.bc.ceres.jai.opimage.XmlRIF.java

License:Open Source License

private RenderedImage create(URI location, Map<String, Object> configuration, RenderingHints renderingHints)
        throws JDOMException, IOException, IllegalArgumentException {
    configuration = new HashMap<String, Object>(configuration);

    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(location.toURL());
    Element rootElement = document.getRootElement();
    Map<String, Element> sourceMap = getElementMap(rootElement, ENAME_SOURCE);
    Map<String, Element> parameterMap = getElementMap(rootElement, ENAME_PARAMETER);
    Element targetElement = rootElement.getChild(ENAME_TARGET);
    return parseImage(targetElement, sourceMap, parameterMap, configuration, renderingHints, "rendered");
}

From source file:com.bennavetta.util.tycho.impl.DefaultWrapperGenerator.java

License:Apache License

private void writeModules(List<String> modules, File pomFile) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Document pom = builder.build(pomFile);
    Namespace pomNs = pom.getRootElement().getNamespace();
    Element modulesElem = pom.getRootElement().getChild("modules", pomNs);
    if (modulesElem == null) {
        modulesElem = new Element("modules", pomNs);
        pom.getRootElement().addContent(modulesElem);
    }/*from w  w w .  j  a v a 2  s.c om*/
    for (String module : modules) {
        boolean exists = false;
        for (Element existingModule : modulesElem.getChildren()) {
            if (existingModule.getTextTrim().equals(module)) {

                exists = true;
                break;
            }
        }
        if (!exists) {
            Element moduleElem = new Element("module", pomNs);
            moduleElem.setText(module);
            modulesElem.addContent(moduleElem);
        }
    }
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat().setIndent("\t"));
    try (FileOutputStream out = new FileOutputStream(pomFile)) {
        xout.output(pom, out);
    }
}

From source file:com.bennavetta.util.tycho.XmlWrapDescriptorParser.java

License:Apache License

public WrapRequest createRequest(Document doc) throws Exception {
    log.info("Parsing wrapper configuration {} from {}", doc, doc.getBaseURI());

    DefaultWrapRequest req = new DefaultWrapRequest();

    if (doc.getRootElement().getChild("repositories") != null) {
        for (Element repoDescriptor : doc.getRootElement().getChild("repositories").getChildren("repository")) {
            Repository repo = new Repository();
            repo.setId(repoDescriptor.getAttributeValue("id"));
            repo.setLayout(repoDescriptor.getAttributeValue("layout", "default"));
            repo.setName(repoDescriptor.getAttributeValue("name"));
            repo.setUrl(repoDescriptor.getAttributeValue("url"));
            log.debug("Adding repository {}", repo);
            req.addRepository(repo);/*  ww  w.j a  va  2s  .c  om*/
        }
    }

    String bndDir = doc.getRootElement().getChildText("bndDir");
    if (bndDir != null) {
        req.setBndDirectory(new File(bndDir));
        log.debug("Bnd directory: {}", bndDir);
    }

    Model parent = Maven.createModel(new File(doc.getRootElement().getChildText("parent")));
    req.setParent(parent);
    log.debug("Parent: {}", parent);
    for (Element artifactDescriptor : doc.getRootElement().getChild("artifacts").getChildren("artifact")) {
        String groupId = artifactDescriptor.getAttributeValue("groupId");
        String artifactId = artifactDescriptor.getAttributeValue("artifactId");
        String version = artifactDescriptor.getAttributeValue("version");
        log.debug("Adding artifact {}:{}:{}", groupId, artifactId, version);
        DefaultArtifactInfo info = new DefaultArtifactInfo(
                new DefaultArtifact(groupId + ":" + artifactId + ":" + version),
                artifactDescriptor.getAttributeValue("symbolicName"));
        req.addArtifact(info);
    }
    return req;
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.objectivesextractor.SchematronBasedExtractor.java

License:Apache License

/**
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.objectivesextractor.ObjectivesExtractor#extractObjectives(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext)
 *///from   www.  j a va2  s.  co  m
@Override
public void extractObjectives(ConfigurationAnalysisContext context) throws ObjectivesExtractionException {
    Document svrlResult = performSchematronValidation(schematronSchema, inputCandidateDocument,
            workingDirectory);
    if (svrlResult.getRootElement().getChildren("failed-assert", CommonXMLConstants.NAMESPACE_SVRL)
            .size() > 0) {
        Objective<Document> extractedObjective = new ModifyXMLFromSVRLResultObjective(suggestedId, sourceTarget,
                svrlResult, suggestedSolveHint, suggestedRequired);
        context.getObjectivesToSatisfy().add(extractedObjective);
    }
}

From source file:com.c4om.autoconf.ulysses.extra.svinchangesetgenerator.SVINChangesetGenerator.java

License:Apache License

/**
 * This method generates a changeset document, which describes what nodes
 * must be added and replaced. It generates it from the SVRLInterpreter
 * report passed at constructor./* w w  w . j  a v a 2  s.c  om*/
 * 
 * @param pathToConfiguration path to the runtime configuration.
 * 
 * @param reportDocument the report document (objective solution description).
 * 
 * @return The generated changeset document.
 * 
 * @throws JDOMException
 *             If there are problems at JDOM2 XML parsings
 * @throws IOException
 *             I/O problems
 * @throws SaxonApiException
 *             problems with Saxon API while transforming metamodel
 *             suggestions into partial autocomplete nodes
 * @throws ParserConfigurationException
 *             problems with javax.xml APIs while transforming metamodel
 *             suggestions into partial autocomplete nodes
 */
public Document getSingleChangesetDocument(String pathToConfiguration, Document reportDocument)
        throws JDOMException, IOException, SaxonApiException, ParserConfigurationException {
    Element resultRoot = new Element("changeset", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
    resultRoot.addNamespaceDeclaration(NAMESPACE_AUTOCONF_METADATA); // To
    // prevent
    // several
    // "xmlns:*****"
    // attributes
    // to
    // appear
    // everywhere
    Document result = new Document(resultRoot);
    Element reportElement = reportDocument.getRootElement();
    for (Element currentDiscrepancyElement : reportElement.getChildren()) {
        boolean isCreate = false;
        Element interestingPathsElement = currentDiscrepancyElement.getChild("interestingPaths",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        String searchPathText = interestingPathsElement.getAttributeValue("search-path");
        String basePathText = interestingPathsElement.getAttributeValue("base-path");
        String keySubpathText = interestingPathsElement.getAttributeValue("key-subpath");
        // First, we look for a path to search the element where discrepancy
        // took place (if it exists)
        String[] docAndPath;
        String searchPathInternal;
        if (searchPathText == null) {
            docAndPath = divideDocAndPath(basePathText);
            searchPathInternal = docAndPath[1] + "[" + keySubpathText + "]";
        } else {
            docAndPath = divideDocAndPath(searchPathText);
            searchPathInternal = docAndPath[1];
        }
        if (!documentCache.containsKey(docAndPath[0])) {
            documentCache.put(docAndPath[0],
                    loadJDOMDocumentFromFile(new File(pathToConfiguration + "/" + docAndPath[0])));
        }
        Document currentDoc = documentCache.get(docAndPath[0]);
        List<Element> discordingElementAtDocList = performJAXENXPath(searchPathInternal, currentDoc,
                Filters.element(), xpathNamespaces);
        if (discordingElementAtDocList.size() == 0) {
            isCreate = true;
        }
        if (isCreate) {
            Element nodeToCreate = currentDiscrepancyElement
                    .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                    .clone();
            //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it.
            nodeToCreate.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT);
            boolean thereAreMetamodelSuggestions = currentDiscrepancyElement
                    .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren()
                    .size() > 0;
            if (thereAreMetamodelSuggestions) {
                Element metamodelSuggestionUntransformed = currentDiscrepancyElement
                        .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                        .clone();
                Document suggestionMiniDocument = new Document(metamodelSuggestionUntransformed);
                Document suggestionMiniDocumentTransformed = performXSLT(suggestionMiniDocument,
                        xsltTransformMetamodelDocument);
                Element metamodelSuggestion = suggestionMiniDocumentTransformed.getRootElement();
                Attribute metadataAttribute = new Attribute("autogen-from", "metamodel",
                        NAMESPACE_AUTOCONF_METADATA);
                mixTreesRecursive(metamodelSuggestion, nodeToCreate, metadataAttribute,
                        NAMESPACE_AUTOCONF_METADATA.getURI());
            } else {
                Attribute mayNeedManualCompletion = new Attribute("may-need-completion", "true",
                        NAMESPACE_AUTOCONF_METADATA);
                nodeToCreate.setAttribute(mayNeedManualCompletion);
            }
            Element createNodeElement = new Element("add-node", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
            final String REGEXP_TO_GET_PARENT_PATH = "(.+)(/[^\\[\\]/]+(\\[.+\\])?)$";
            Pattern patternToGetParentPath = Pattern.compile(REGEXP_TO_GET_PARENT_PATH);
            Matcher matcherToGetParentPath = patternToGetParentPath.matcher(searchPathInternal);
            matcherToGetParentPath.matches();
            String pathToParent = matcherToGetParentPath.group(1);
            Attribute pathToParentAttr = new Attribute("underParentAtPath", pathToParent);
            Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]);
            createNodeElement.setAttribute(documentToChangeAttr);
            createNodeElement.setAttribute(pathToParentAttr);
            createNodeElement.addContent(nodeToCreate);
            resultRoot.addContent(createNodeElement);

        } else {
            for (int i = 0; i < discordingElementAtDocList.size(); i++) {
                Element nodeToModify = currentDiscrepancyElement
                        .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                        .clone();
                //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it.
                nodeToModify.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT);
                Element discordingElementAtDoc = discordingElementAtDocList.get(i);
                mixTreesRecursive(discordingElementAtDoc, nodeToModify, null,
                        NAMESPACE_AUTOCONF_METADATA.getURI());
                Element replaceNodeElement = new Element("replace-node",
                        AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
                Attribute pathToElementAttr = new Attribute("atPath",
                        generateAttributeBasedPath(discordingElementAtDoc));
                Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]);
                replaceNodeElement.setAttribute(documentToChangeAttr);
                replaceNodeElement.setAttribute(pathToElementAttr);
                replaceNodeElement.addContent(nodeToModify);
                resultRoot.addContent(replaceNodeElement);
            }
        }
    }
    return result;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlinterpreter.SVRLInterpreterProcessor.java

License:Apache License

/**
 * Method that actually performs the process
 * @param intermediateResults a list of intermediate results.
 * @return the resulting report//from   w  ww.jav  a2  s.  c o m
 * @throws SaxonApiException if a XQuery query fails.
 * @throws IOException required by internal methods, but it will never be thrown (normally)
 * @throws JDOMException if there are problems at XML Parsing
 */
public Document process(List<List<String>> intermediateResults)
        throws SaxonApiException, JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Element rootElement = new Element("report", NAMESPACE_SVRL_INTERPETER_REPORT);
    Document result = new Document(rootElement);
    Map<String, List<Element>> queryCache = performXPathMetamodelSuggestionQueries(
            listOfListsToSingleList(intermediateResults, 0));
    for (int i = 0; i < intermediateResults.size(); i++) {
        List<String> intermediateResult = intermediateResults.get(i);
        Element currentDiscrepancyElement = new Element("discrepancy", NAMESPACE_SVRL_INTERPETER_REPORT);
        rootElement.addContent(currentDiscrepancyElement);

        String partialNodeString = saxonQuery(intermediateResult.get(1));
        Reader partialNodeStringReader = new StringReader(partialNodeString);
        Document partialNodeDoc = builder.build(partialNodeStringReader);
        Element partialNode = partialNodeDoc.getRootElement().detach();

        Element currentInterestingPathsElement = new Element("interestingPaths",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "mandatory-path",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "base-path",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "key-subpath",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "search-path",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(currentInterestingPathsElement);

        Element currentSuggestedPartialNodeElement = new Element("suggestedPartialNode",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(currentSuggestedPartialNodeElement);

        currentSuggestedPartialNodeElement.addContent(partialNode);

        Element currentMetamodelSuggestionsElement = new Element("metamodelSuggestions",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(currentMetamodelSuggestionsElement);

        List<Element> queryResults = queryCache.get(intermediateResult.get(0));
        for (Element queryResult : queryResults) {
            currentMetamodelSuggestionsElement.addContent(queryResult.clone());
        }

    }
    return result;
}