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.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);
    }/*  ww w.j  ava  2s  .  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.bio4j.neo4jdb.model.util.GoUtil.java

License:Open Source License

/**
 * /*from w  w w .j  a  v a2s.c om*/
 * @param proteins
 * @param slimSetXML
 * @param manager
 * @param goAnnotationXML
 * @return GO Slim in xml format
 */
public static GOSlimXML getGoSlim(ArrayList<ProteinXML> proteins, SlimSetXML slimSetXML, Bio4jManager manager,
        GoAnnotationXML goAnnotationXML) {

    GOSlimXML goSlimXML = new GOSlimXML();

    if (goAnnotationXML == null) {
        goAnnotationXML = GoUtil.getGoAnnotation(proteins, manager);
    }

    //int goTermsLostNotIncludedInSlimSet = 0;

    Index<Node> goTermIdIndex = manager.getGoTermIdIndex();

    if (goAnnotationXML != null) {

        List<GoTermXML> goAnnotators = goAnnotationXML.getAnnotatorGoTerms();

        //IndexService indexService = manager.getIndexService();

        // in this hash map there is one entry for each annotator go term
        // the hash-set contains every slim-set go term including the annotator
        HashMap<String, HashSet<String>> goAnnotatorsIncludingSlimSetTermsMap = new HashMap<String, HashSet<String>>();

        //Here are the xml elements of the Go terms from the slim set termid --> term xml
        HashMap<String, GoTermXML> slimSetGos = new HashMap<String, GoTermXML>();

        //Here are the number of proteins annotated for each go term of the slim set termid --> number of proteins annotated
        HashMap<String, Integer> slimSetTermsAnnotationCounts = new HashMap<String, Integer>();

        //Now I extract the ids of the SlimSet
        List<Element> slimElements = slimSetXML.asJDomElement().getChildren(GoTermXML.TAG_NAME);
        for (Element slimElement : slimElements) {
            GoTermXML tempGo = new GoTermXML(slimElement);

            //--completing data of slimset go terms-----
            GoTermNode tempGoNode = new GoTermNode(
                    manager.getGoTermIdIndex().get(GoTermNode.GO_TERM_ID_INDEX, tempGo.getId()).getSingle());
            tempGo.setAspect(tempGoNode.getNamespace());
            tempGo.setGoName(tempGoNode.getName());
            //------------------------

            slimSetGos.put(tempGo.getId(), tempGo);

            //initializing annotation counts map
            slimSetTermsAnnotationCounts.put(tempGo.getId(), 0);
        }
        //--------------------------------------------

        //            logger.log(Level.INFO, "slimsetIds:");
        //            for (String slimId : slimSetIds) {
        //                logger.log(Level.INFO, ("slimId:" + slimId));
        //            }

        //Now it is time for goAnnotatorsIncludingSlimSetTermsMap initialization
        for (GoTermXML goAnnotator : goAnnotators) {
            goAnnotatorsIncludingSlimSetTermsMap.put(goAnnotator.getId(), new HashSet<String>());
        }
        //------------------------------------------------------

        try {

            IsAGoRel goParentRel = new IsAGoRel(null);

            //Now I search the way up of every go Annotator and check if in the way I find
            //any of the terms included in the slim set.

            //logger.log(Level.INFO, "lalalala");

            int callCounter = 0;

            for (GoTermXML goAnnotator : goAnnotators) {
                //this array includes the term own id and every ancestor id
                HashSet<String> ancestorsIds = new HashSet<String>();

                GoTermNode goTermNode = new GoTermNode(
                        goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, goAnnotator.getId()).getSingle());

                //logger.log(Level.INFO, goTermNode.toString());

                fillUpAncestorIds(goTermNode, ancestorsIds, goParentRel, manager.getIsAGoRelIndex(),
                        callCounter);

                for (String ancestorId : ancestorsIds) {
                    //If the ancestor is included in the slim set, it means that this term
                    //from the slim set includes the goAnnotator 
                    if (slimSetGos.keySet().contains(ancestorId)) {
                        HashSet<String> hashSet = goAnnotatorsIncludingSlimSetTermsMap.get(goAnnotator.getId());
                        hashSet.add(ancestorId); //ancestorId is actually one of the slim-set terms ids.
                    }
                }

                callCounter++;
            }

            //So now I should have every goAnnotator with its corresponing slimSet terms

            List<Element> proteinList = goAnnotationXML.getProteinAnnotations()
                    .getChildren(ProteinXML.TAG_NAME);

            Element proteinsElem = new Element(GOSlimXML.PROTEINS_TAG_NAME);

            int sampleAnnotatedGeneNumber = 0;

            for (Element currentElem : proteinList) {

                boolean annotated = false;

                //getting the protein
                ProteinXML currentProteinXML = new ProteinXML(currentElem);

                //initializing inductors map                    
                HashMap<String, String> currentProteinSlimTermInductors = new HashMap<String, String>();
                //proteinSlimTermsAndInductorTermsMap.put(currentProteinXML.getId(), currentProteinSlimTermInductors);

                //System.out.println("currentProteinXML.getId() = " + currentProteinXML.getId());

                //--------now we access to its go annotations-------------
                List<GoTermXML> proteinTerms = new ArrayList<GoTermXML>();
                List<GoTermXML> bpTerms = currentProteinXML.getBiologicalProcessGoTerms();
                List<GoTermXML> ccTerms = currentProteinXML.getCellularComponentGoTerms();
                List<GoTermXML> mfTerms = currentProteinXML.getMolecularFunctionGoTerms();
                if (bpTerms != null) {
                    proteinTerms.addAll(bpTerms);
                }
                if (ccTerms != null) {
                    proteinTerms.addAll(ccTerms);
                }
                if (mfTerms != null) {
                    proteinTerms.addAll(mfTerms);
                }
                //------------------------------------------------------
                //creating the result xml protein
                ProteinXML proteinResult = new ProteinXML();
                proteinResult.setId(currentProteinXML.getId());
                HashSet<String> proteinSlimTems = new HashSet<String>();
                for (GoTermXML goTermXML : proteinTerms) {
                    HashSet<String> hashSet = goAnnotatorsIncludingSlimSetTermsMap.get(goTermXML.getId());

                    System.out.println("");

                    if (hashSet != null) {
                        if (hashSet.size() > 0) {
                            proteinSlimTems.addAll(hashSet);
                            for (String tempSlimTermId : hashSet) {
                                currentProteinSlimTermInductors.put(tempSlimTermId, goTermXML.getId());
                            }
                            annotated = true;
                        } else {
                            //-----The go term annotation lost is stored-------
                            goSlimXML.addGoTermLostNotIncludedInSlimSet(
                                    new GoTermXML((Element) goTermXML.asJDomElement().clone()));
                            System.out.println("holaaa!" + goTermXML.getId());
                        }
                    }
                }

                //now we get the info from the slimset go terms
                for (String string : proteinSlimTems) {
                    //logger.log(Level.INFO, ("string: " + string));
                    GoTermXML tempGoTerm = new GoTermXML(
                            (Element) slimSetGos.get(string).asJDomElement().clone());

                    //------Adding protein annotation term leading to slim set term -----------
                    String termInductorId = currentProteinSlimTermInductors.get(tempGoTerm.getId());
                    //look for inductor info                        
                    for (GoTermXML goTermXML : proteinTerms) {
                        //System.out.println("goTermXML = " + goTermXML);
                        if (goTermXML.getId().equals(termInductorId)) {
                            tempGoTerm.setProteinAnnotationLeadingToSlimTerm(
                                    new GoTermXML((Element) goTermXML.asJDomElement().clone()));
                            break;
                        }
                    }
                    //--------------------------------------------------------------------------

                    //logger.log(Level.INFO, ("tempGoTerm: " + tempGoTerm));
                    proteinResult.addGoTerm(tempGoTerm, true);

                    //updating annotation counts
                    slimSetTermsAnnotationCounts.put(string, slimSetTermsAnnotationCounts.get(string) + 1);
                }

                proteinsElem.addContent(proteinResult.asJDomElement());

                if (annotated) {
                    sampleAnnotatedGeneNumber++;
                }

            }

            //updating slimset annotation counts
            List<Element> slimSetElems = slimSetXML.asJDomElement().getChildren(GoTermXML.TAG_NAME);
            for (Element slimSetElem : slimSetElems) {
                GoTermXML slimSetGo = new GoTermXML(slimSetElem);
                slimSetGo.setAnnotationsCount(slimSetTermsAnnotationCounts.get(slimSetGo.getId()));
            }

            goSlimXML.asJDomElement().addContent(proteinsElem);
            slimSetXML.detach();
            goSlimXML.setSlimSet(slimSetXML);
            goSlimXML.setSampleGeneNumber(proteinList.size());
            goSlimXML.setSampleAnnotatedGeneNumber(sampleAnnotatedGeneNumber);
            //goSlimXML.set

        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
            StackTraceElement[] trace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : trace) {
                logger.log(Level.SEVERE, stackTraceElement.toString());
            }
            goSlimXML = null;
        }

    } else {
        goSlimXML = null;
    }

    return goSlimXML;
}

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.//from  w  w  w  . j  a va  2  s.c o  m
 * 
 * @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 w w  . j  a  v  a 2  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;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.PartialNodeGenerator.java

License:Apache License

/**
 * Given a selectFromPath, it queries the runtime configuration to get the selectable values pointed by that path
 * and generates the met:possibleValues element that describes it.
 * @param selectFromPath the path to select from (including a document function, relative to the runtime configuration)
 * @param metamodelDoc the metamodel document, to extract probabilities from.
 * @param originalPath the path of the original element at the document
 * @return the desired met:possibleValues
 * @throws IOException If there are I/O errors while loading documents to select values from.
 * @throws JDOMException If there are problems at XML parsing while loading documents to select values from.
 *//*from   w w  w .  j  a  v a2  s. c  om*/
private Element getPossibleValuesElement(String selectFromPath, Document metamodelDoc, String originalPath)
        throws JDOMException, IOException {
    Element possibleValuesElement = new Element("possibleValues",
            AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA);

    List<String> gatheredPossibleValues = new ArrayList<>();

    if (selectFromPath.contains("|")) {
        String[] singlePaths = selectFromPath.split("\\|");
        for (int i = 0; i < singlePaths.length; i++) {
            String singlePath = singlePaths[i];
            gatheredPossibleValues.addAll(getSelectableValuesFromSinglePath(singlePath));
        }
    } else {
        gatheredPossibleValues = getSelectableValuesFromSinglePath(selectFromPath);
    }

    for (String possibleValue : gatheredPossibleValues) {
        Element currentPosibleValueElement = new Element("possibleValue",
                AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA);
        String queryFrequencyStr = "sum(" + originalPath + "/" + metamodelAttributesPrefix + "Value[./@"
                + metamodelAttributesPrefix + "ValueAttr='" + possibleValue + "']/@" + metamodelAttributesPrefix
                + "Frequency)";
        String queryParentFrequencyStr = "sum(" + originalPath + "/@" + metamodelAttributesPrefix
                + "Frequency)";
        List<Double> queryFrequencyResults;
        List<Double> queryParentFrequencyResults;
        if (metamodelDoc != null) {
            queryFrequencyResults = performJAXENXPath(queryFrequencyStr, metamodelDoc, Filters.fdouble());
            queryParentFrequencyResults = performJAXENXPath(queryParentFrequencyStr, metamodelDoc,
                    Filters.fdouble());

        } else {
            queryFrequencyResults = Collections.emptyList();
            queryParentFrequencyResults = Collections.emptyList();
        }

        if (queryParentFrequencyResults.size() > 0 && queryFrequencyResults.size() > 0) {
            double myFrequency = queryFrequencyResults.get(0);
            double myParentFrequency = queryParentFrequencyResults.get(0);
            double probability = myFrequency / myParentFrequency;
            String formattedProbability = String.format(Locale.US, "%.2f", probability);
            if (!formattedProbability.equalsIgnoreCase("nan")) {
                Attribute probabilityAttribute = new Attribute("probability", formattedProbability);
                currentPosibleValueElement.setAttribute(probabilityAttribute);
            }
        }

        currentPosibleValueElement.setText(possibleValue);
        possibleValuesElement.addContent(currentPosibleValueElement);
    }

    return possibleValuesElement;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.PartialNodeGenerator.java

License:Apache License

/**
 * Method that, given a {@link PathGroup} object (representing a group of paths), generates a partial element (as an {@link Element} object) with all the information present at it.
 * @param pathGroup the {@link PathGroup} object
 * @return the partial element /* ww  w . ja  va  2  s  . c om*/
 * @throws IOException If there are I/O errors while loading documents to select values from.
 * @throws JDOMException If there are problems at XML parsing while loading documents to select values from.
 * @throws IllegalArgumentException if the basePath or any subpath is invalid
 * @throws IndexOutOfBoundsException if a path token filter contains a count token and the number of attributes does not match.
 */
public Element generatePartialNode(PathGroup pathGroup) throws JDOMException, IOException {
    File metamodelDocFile = new File(pathGroup.getDocumentPath());
    if (!metamodelDocFile.isAbsolute()) {
        metamodelDocFile = new File(this.pathToMetamodel, pathGroup.getDocumentPath());
    }
    Document metamodelDoc;
    try {
        metamodelDoc = loadJDOMDocumentFromFile(metamodelDocFile);
    } catch (IOException e) {
        metamodelDoc = null;
    }

    List<String> basePathTokens = decomposePathTokens(pathGroup.getBasePath());
    String basePathToken = basePathTokens.get(basePathTokens.size() - 1);
    Pattern textAtCurrentNodePattern = Pattern.compile(REGEXP_TEXT_AT_CURRENT_NODE);
    Matcher textAtCurrentBasePathMatcher = textAtCurrentNodePattern.matcher(basePathToken);
    Element partialNode;
    if (textAtCurrentBasePathMatcher.matches()) {
        String text = textAtCurrentBasePathMatcher.group("textValue");
        basePathToken = basePathTokens.get(basePathTokens.size() - 2);
        partialNode = generateElementFromPathToken(basePathToken, xpathNamespaces);
        partialNode.setText(text);
    } else {
        partialNode = generateElementFromPathToken(basePathToken, xpathNamespaces);
    }
    String basePathSelectFrom = pathGroup.getBasePathSelectFrom();
    if (basePathSelectFrom != null && !(basePathSelectFrom.equals(""))) {
        partialNode.setText("");
        Element possibleValuesElement = getPossibleValuesElement(basePathSelectFrom, metamodelDoc,
                pathGroup.getBasePath());
        partialNode.addContent(possibleValuesElement);
    }
    for (String subpath : pathGroup.getSubPaths()) {
        List<String> subpathTokens = decomposePathTokens(subpath);
        Element currentElement = partialNode;
        for (int i = 0; i < subpathTokens.size(); i++) {
            String currentSubpathToken = subpathTokens.get(i);
            Matcher textAtCurrentNodeMatcher = textAtCurrentNodePattern.matcher(currentSubpathToken);
            if (textAtCurrentNodeMatcher.matches()) {
                String text = textAtCurrentNodeMatcher.group("textValue");
                currentElement.setText(text);
                continue;
            }
            List<Element> newChildList = performJAXENXPath("./" + currentSubpathToken, currentElement);
            if (newChildList.size() > 1) {
                throw new IllegalArgumentException(
                        "Subpath token '" + currentSubpathToken + "' yields more than one child");
            }
            Element newChild;
            if (newChildList.size() == 1) {
                newChild = newChildList.get(0);
            } else {
                newChild = generateElementFromPathToken(currentSubpathToken, xpathNamespaces);
                currentElement.addContent(newChild);
            }
            currentElement = newChild;
        }
        String subpathSelectFrom = pathGroup.getSubPathSelectFrom(subpath);
        if (subpathSelectFrom != null && !(subpathSelectFrom.equals(""))) {
            currentElement.setText("");
            Element possibleValuesElement = getPossibleValuesElement(subpathSelectFrom, metamodelDoc,
                    pathGroup.getBasePath() + "/" + subpath);
            currentElement.addContent(possibleValuesElement);
        }
    }
    return partialNode;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.SVRLMultipathInterpreterMain.java

License:Apache License

/**
 * This method performs the actual svrl interpretation process (which constitutes the objective solving process).
 * @param svrlDocument the SVRL document (i.e. the objective description)
 * @return the svrl interpreter report (i.e. the objective solution)
 * @throws JDOMException if there are XML problems
 * @throws IOException if there are I/O problems.
 *//*  w  w w . ja  va  2s .  c om*/
public Document interpret(Document svrlDocument) throws JDOMException, IOException {
    Element resultRootElement = new Element("report", AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);
    Document result = new Document(resultRootElement);
    List<String> pathsListRepeated = getPathsFromDocument(svrlDocument);
    PathGroupsGenerator pathGroupsGenerator = new PathGroupsGenerator();
    List<PathGroup> pathGroups = pathGroupsGenerator.getPathGroups(pathsListRepeated);
    PartialNodeGenerator partialNodeGenerator = new PartialNodeGenerator(this.xpathNamespaces,
            this.pathToConfiguration, this.pathToMetamodel, this.metamodelAttributesPrefix);
    for (PathGroup pathGroup : pathGroups) {
        Element currentDiscrepancyElement = new Element("discrepancy",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);

        Element currentInterestingPathsElement = new Element("interestingPaths",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);

        // '/.[text()=something]' tokens should not be used to look for elements at the metamodel and/or search paths, as text DOES NOT identify elements according to our convention.
        String fixedBasePath = pathGroup.getBasePath().replaceAll("\\]/\\.\\[(?<bracketContent>[^\\]]+)\\]$",
                "]");

        currentInterestingPathsElement.setAttribute("search-path",
                "doc('" + pathGroup.getDocumentPath() + "')" + fixedBasePath);
        currentDiscrepancyElement.addContent(currentInterestingPathsElement);

        Element suggestedPartialNodeElement = new Element("suggestedPartialNode",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(suggestedPartialNodeElement);
        Element partialNode = partialNodeGenerator.generatePartialNode(pathGroup);
        suggestedPartialNodeElement.addContent(partialNode);

        File metamodelDocFile = new File(pathGroup.getDocumentPath());
        if (!metamodelDocFile.isAbsolute()) {
            metamodelDocFile = new File(this.pathToMetamodel, pathGroup.getDocumentPath());
        }
        List<Element> metamodelSuggestedNodeList;
        try {
            Document metamodelDoc = documentCache.get(metamodelDocFile.getAbsolutePath());
            if (metamodelDoc == null) {
                metamodelDoc = loadJDOMDocumentFromFile(metamodelDocFile);
                documentCache.put(metamodelDocFile.getAbsolutePath(), metamodelDoc);
            }
            metamodelSuggestedNodeList = performJAXENXPath(fixedBasePath, metamodelDoc);
        } catch (IOException e) {
            metamodelSuggestedNodeList = Collections.emptyList();
        }

        Element metamodelSuggestionsElement = new Element("metamodelSuggestions",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);
        for (Element metamodelSuggestedNode : metamodelSuggestedNodeList) {
            metamodelSuggestionsElement.addContent(metamodelSuggestedNode.clone());
        }
        currentDiscrepancyElement.addContent(metamodelSuggestionsElement);

        resultRootElement.addContent(currentDiscrepancyElement);
    }

    return result;
}

From source file:com.cats.version.VersionCfgParseAndSave.java

License:Apache License

public boolean saveVersionInfo(List<VersionInfo> infos, String fullPath) {
    try {//  w w  w . j  a v  a 2s  .  c  o  m
        Document doc = new Document();
        Element root = new Element("software-group");
        for (VersionInfo info : infos) {
            Element softEle = new Element("software");
            softEle.setAttribute("name", info.getAppName());
            Element versionCodeEle = new Element("latest-version-code");
            Element versionNameEle = new Element("latest-version");
            Element versionPathEle = new Element("latest-version-abspath");
            Element startupNameEle = new Element("latest-version-startup");

            versionCodeEle.setText(String.valueOf(info.getVersionCode()));
            versionNameEle.setText(info.getVersion());
            versionPathEle.setText(info.getPath());
            startupNameEle.setText(info.getStartupName());
            softEle.addContent(versionCodeEle);
            softEle.addContent(versionNameEle);
            softEle.addContent(versionPathEle);
            softEle.addContent(startupNameEle);

            List<VersionInfoDetail> details = info.getDetails();
            if (null != details) {
                Element detailEles = new Element("latest-version-detail");
                for (VersionInfoDetail verDetail : details) {
                    Element itemElem = new Element("item");
                    itemElem.setAttribute("name", verDetail.getTitle());

                    List<String> detailList = verDetail.getDetail();
                    for (String detailInfo : detailList) {
                        Element detailEle = new Element("detail");
                        detailEle.setText(detailInfo);
                        itemElem.addContent(detailEle);
                    }
                    detailEles.addContent(itemElem);
                }
                softEle.addContent(detailEles);
            }

            List<String> ignoreFiles = info.getIgnoreFiles();
            if (ignoreFiles != null) {
                Element ignoreEles = new Element("ignore-files");
                for (String ignoreInfo : ignoreFiles) {
                    Element ignoreItemEle = new Element("item");
                    ignoreItemEle.setText(ignoreInfo);
                    ignoreEles.addContent(ignoreItemEle);
                }
                softEle.addContent(ignoreEles);
            }
            root.addContent(softEle);
        }
        doc.setRootElement(root);

        //Save to xml file
        XMLOutputter xmlOut = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fullPath);
            xmlOut = new XMLOutputter(Format.getPrettyFormat());
            xmlOut.output(doc, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.collir24.policyextractor.Extract.java

License:Apache License

private static Document buildDocument(List<ModulePermissions> modulePermissions) {
    Element modulePolicy = new Element("modulePolicy");
    for (ModulePermissions mps : modulePermissions) {
        Element module = new Element("module");
        module.setAttribute("name", mps.getModuleName());
        Set<String> policySet = new HashSet<String>();
        for (ModulePermission mp : mps.getPermissions()) {
            Element permRequired = new Element("permRequired");
            permRequired.setAttribute("line", Integer.toString(mp.getLine()));
            permRequired.setAttribute("className", mp.getClassName());
            for (String s : mp.getPolicy()) {
                Element perm = new Element("perm");
                perm.setText(s);//  w  ww  .jav a  2  s  .com
                permRequired.addContent(perm);
            }
            module.addContent(permRequired);
            // TODO: say what caused the permission to be required - see key
            policySet.addAll(mp.getPolicy());
        }
        CDATA policyData = new CDATA(generatePolicy(policySet));
        module.addContent(policyData);
        modulePolicy.addContent(module);
    }
    return new Document(modulePolicy);
}

From source file:com.cybernostics.jsp2thymeleaf.api.elements.CopyElementConverter.java

@Override
public List<Content> process(JSPParser.JspElementContext node, JSPElementNodeConverter context) {
    Optional<Element> maybeElement = createElement(node, context);
    if (maybeElement.isPresent()) {
        Element element = maybeElement.get();
        element.removeNamespaceDeclaration(XMLNS);
        element.addContent(getNewChildContent(node, context));
        addAttributes(element, node, context);
        return Stream.concat(Stream.of(element), getNewAppendedContent(node, context).stream())
                .collect(toList());//  w  w w  . j a  va  2 s. com
    }

    return EMPTY_LIST;
}