Example usage for org.jdom2 Element getContent

List of usage examples for org.jdom2 Element getContent

Introduction

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

Prototype

@Override
    public Content getContent(final int index) 

Source Link

Usage

From source file:ddf.catalog.source.opensearch.OpenSearchSource.java

License:Open Source License

/**
 * @param is//from w ww . j  a v  a2 s  . c  o m
 * @param queryRequest
 * @return
 * @throws ddf.catalog.source.UnsupportedQueryException
 */
private SourceResponseImpl processResponse(InputStream is, QueryRequest queryRequest)
        throws UnsupportedQueryException {
    List<Result> resultQueue = new ArrayList<>();

    SyndFeedInput syndFeedInput = new SyndFeedInput();
    SyndFeed syndFeed = null;
    try {
        syndFeed = syndFeedInput.build(new InputStreamReader(is));
    } catch (FeedException e) {
        LOGGER.error("Unable to read RSS/Atom feed.", e);
    }

    List<SyndEntry> entries = null;
    long totalResults = 0;
    if (syndFeed != null) {
        entries = syndFeed.getEntries();
        for (SyndEntry entry : entries) {
            resultQueue.addAll(createResponseFromEntry(entry));
        }
        totalResults = entries.size();
        List<Element> foreignMarkup = syndFeed.getForeignMarkup();
        for (Element element : foreignMarkup) {
            if (element.getName().equals("totalResults")) {
                try {
                    totalResults = Long.parseLong(element.getContent(0).getValue());
                } catch (NumberFormatException | IndexOutOfBoundsException e) {
                    // totalResults is already initialized to the correct value, so don't change it here.
                    LOGGER.debug("Received invalid number of results.", e);
                }
            }
        }
    }

    SourceResponseImpl response = new SourceResponseImpl(queryRequest, resultQueue);
    response.setHits(totalResults);

    return response;
}

From source file:ddf.catalog.source.opensearch.OpenSearchSource.java

License:Open Source License

/**
 * Creates a single response from input parameters. Performs XPath operations on the document to
 * retrieve data not passed in./*from   w  ww . j  a  va  2  s .c o m*/
 *
 * @param entry
 *            a single Atom entry
 * @return single response
 * @throws ddf.catalog.source.UnsupportedQueryException
 */
private List<Result> createResponseFromEntry(SyndEntry entry) throws UnsupportedQueryException {
    String id = entry.getUri();
    if (id != null && !id.isEmpty()) {
        id = id.substring(id.lastIndexOf(':') + 1);
    }

    List<SyndContent> contents = entry.getContents();
    List<SyndCategory> categories = entry.getCategories();
    List<Metacard> metacards = new ArrayList<>();
    List<Element> foreignMarkup = entry.getForeignMarkup();
    String relevance = "";
    String source = "";
    for (Element element : foreignMarkup) {
        if (element.getName().equals("score")) {
            relevance = element.getContent(0).getValue();
        }
    }
    //we currently do not support downloading content via an RSS enclosure, this support can be added at a later date if we decide to include it
    for (SyndContent content : contents) {
        MetacardImpl metacard = getMetacardImpl(parseContent(content.getValue(), id));
        metacard.setSourceId(this.shortname);
        String title = metacard.getTitle();
        if (StringUtils.isEmpty(title)) {
            metacard.setTitle(entry.getTitle());
        }
        if (!source.isEmpty()) {
            metacard.setSourceId(source);
        }
        metacards.add(metacard);
    }
    for (int i = 0; i < categories.size() && i < metacards.size(); i++) {
        SyndCategory category = categories.get(i);
        Metacard metacard = metacards.get(i);
        if (StringUtils.isBlank(metacard.getContentTypeName())) {
            ((MetacardImpl) metacard).setContentTypeName(category.getName());
        }
    }

    List<Result> results = new ArrayList<>();
    for (Metacard metacard : metacards) {
        ResultImpl result = new ResultImpl(metacard);
        if (relevance == null || relevance.isEmpty()) {
            LOGGER.debug("couldn't find valid relevance. Setting relevance to 0");
            relevance = "0";
        }
        result.setRelevanceScore(new Double(relevance));
        results.add(result);
    }

    return results;
}

From source file:ditatools.translate.DitaTranslator.java

License:Apache License

/**
 * Translate an XML element by grabbing each text node
 * and sending it to Google Translate, and replacing the
  * source text with the translated text.
  *//*from w w  w . j a  v  a  2 s . c  o  m*/
private void process(Element element) {
    // filter selects elements and text nodes
    List<Content> children = element.getContent(filter);
    Iterator<Content> iterator = children.iterator();
    while (iterator.hasNext()) {
        Object o = iterator.next();
        if (o instanceof Element) {
            Element child = (Element) o;
            process(child);
        } else {
            // Due to filter, the only other possibility is Text
            Text text = (Text) o;
            handleText(text);
        }
    }
}

From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java

License:Apache License

/**
 * It generates the XSD file of the targetNamespace given at the constructor, taking into account that 
 * the main namespace is the one given at the constructor.
 * /*from  w w  w .  j  av  a 2 s .  c o  m*/
 * @param schema the schema object
 * @param configuration the inference configuration
 * 
 * @return a JDOM2 {@link Document} object containing the XSD contents.
 * 
 * @see SchemaDocumentGenerator#generateSchemaDocument(Schema, XSDInferenceConfiguration)
 */
@Override
public Document generateSchemaDocument(Schema schema, XSDInferenceConfiguration configuration) {
    //      if(!configuration.getElementsGlobal()==false || 
    //            !configuration.getComplexTypesGlobal()==true ||
    //            !configuration.getSimpleTypesGlobal()==true
    //            )
    //         throw new UnsupportedOperationException("Not implemented yet.");
    //
    checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(mainNamespace),
            "The main namespace must be a known namespace");
    checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(targetNamespace),
            "The target namespace must be a known namespace");
    //      checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSD_NAMESPACE_URI),"The XSD namespace must not be a known namespace");
    //      checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSI_NAMESPACE_URI),"The XSI namespace must not be a known namespace");
    Map<String, String> namespaceURIToPrefixMappings = schema.getSolvedNamespaceMappings();
    if (configuration.getSkipNamespaces().contains(targetNamespace)) {
        throw new IllegalArgumentException("This is an skipped namespace, so its XSD should not be generated");
    }
    if (targetNamespace.equals(XSD_NAMESPACE_URI))
        System.err.println(
                "The XML Schema namespace is being considered as a target namespace in your documents. Independing of the inferred schemas, the only valid XSD for an XSD would be the normative one present at its first RFC");
    Namespace xsdNamespace = Namespace.getNamespace(XSD_NAMESPACE_PREFIX.replace(":", ""), XSD_NAMESPACE_URI);
    List<Namespace> namespaceDeclarations = getNamespaceDeclarations(namespaceURIToPrefixMappings,
            xsdNamespace);
    Element elementSchema = new Element("schema", xsdNamespace);
    for (int i = 0; i < namespaceDeclarations.size(); i++) {
        Namespace currentNamespace = namespaceDeclarations.get(i);
        elementSchema.addNamespaceDeclaration(currentNamespace);
        String currentNamespaceUri = currentNamespace.getURI();
        if (!targetNamespace.equals(mainNamespace) && !currentNamespaceUri.equals(mainNamespace))
            continue;
        if (currentNamespace.equals(Namespace.XML_NAMESPACE)
                && (!schema.getAttributes().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI)
                        && !schema.getElements().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI))) {
            continue;
        }
        if (currentNamespaceUri.equals(XSD_NAMESPACE_URI)
                && !namespaceURIToPrefixMappings.containsKey(XSD_NAMESPACE_URI))
            continue;
        if (targetNamespace.equals(currentNamespaceUri)
                || (currentNamespaceUri.equals("") && (fileNameGenerator == null)))
            continue;
        if (currentNamespaceUri.equals("") && !currentNamespaceUri.equals(mainNamespace)
                && !schema.getElements().containsRow(""))
            continue;
        Element importElement = new Element("import", xsdNamespace);
        if (!currentNamespaceUri.equals("")) {
            Attribute namespaceAttr = new Attribute("namespace", currentNamespaceUri);
            importElement.setAttribute(namespaceAttr);
        }
        if (fileNameGenerator != null && !configuration.getSkipNamespaces().contains(currentNamespaceUri)) {
            String fileName = fileNameGenerator.getSchemaDocumentFileName(currentNamespaceUri,
                    namespaceURIToPrefixMappings);
            Attribute schemaLocationAttr = new Attribute("schemaLocation", fileName);
            importElement.setAttribute(schemaLocationAttr);
        }
        elementSchema.addContent(importElement);
    }

    if (!targetNamespace.equals("")) {
        Attribute targetNamespaceAttr = new Attribute("targetNamespace", targetNamespace);
        elementSchema.setAttribute(targetNamespaceAttr);
    }
    SortedSet<SimpleType> sortedSimpleTypes = new TreeSet<>(new SimpleTypeComparator());
    sortedSimpleTypes.addAll(schema.getSimpleTypes().values());
    SortedSet<ComplexType> sortedComplexTypes = new TreeSet<>(new ComplexTypeComparator());
    sortedComplexTypes.addAll(schema.getComplexTypes().values());
    //CONTINUE FROM HERE: Generate sorted sets for SchemaElement and SchemaAttribute objects and use them where needed.
    Attribute elementFormDefault = new Attribute("elementFormDefault", "qualified");
    elementSchema.setAttribute(elementFormDefault);
    Document resultingDocument = new Document(elementSchema);
    if (targetNamespace.equals(mainNamespace)) {
        //First, we declare global SimpleTypes.
        //If simpleTypesGlobal is true, any enumeration will be declared as a global simple type.
        //if not, simple types of complex types which have attributes but not children will be declared globally 
        //(due to limitations of XSD, they may not be declared locally together with the attributes info)
        if (configuration.getSimpleTypesGlobal()) {
            for (SimpleType simpleType : sortedSimpleTypes) {
                if (!simpleType.isEnum() || simpleType.isEmpty())
                    continue;
                Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace);
                elementSchema.addContent(simpleTypeElement);
            }
        } else {
            for (ComplexType complexType : sortedComplexTypes) {
                SimpleType simpleType = complexType.getTextSimpleType();
                if (complexType.getAttributeList().isEmpty() || !(complexType.getAutomaton().nodeCount() == 0)
                        || !simpleType.isEnum() || simpleType.isEmpty())
                    continue;
                Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace);
                elementSchema.addContent(simpleTypeElement);
            }
        }
        //Global complexType elements are only generated in the main schema (i.e. the one whose targetNamespace is equal to mainNamespace)
        if (configuration.getComplexTypesGlobal()) {
            for (ComplexType complexType : sortedComplexTypes) {
                boolean hasNoChildren = complexType.getRegularExpression().equals(new EmptyRegularExpression());
                boolean hasNoAttributes = complexType.getAttributeList().size() == 0;
                boolean hasNoComments = complexType.getComments().size() == 0;
                //               boolean simpleTypeIsNotEmpty = !complexType.getTextSimpleType().isEmpty();
                boolean simpleTypeIsWhiteSpaceOnlyOrEmpty = !(complexType.getTextSimpleType().isEmpty()
                        || complexType.getTextSimpleType().consistOnlyOfWhitespaceCharacters());
                if (hasNoChildren && hasNoAttributes && simpleTypeIsWhiteSpaceOnlyOrEmpty && hasNoComments)
                    continue; //Because the elements which are linked to this ComplexType at our internal model 
                              //will be linked to an XSD simple type elsewhere, either a builtin or a custom one.
                Element complexTypeElement = generateComplexType(configuration, complexType, false,
                        targetNamespace, namespaceURIToPrefixMappings, mainNamespace, xsdNamespace);
                elementSchema.addContent(complexTypeElement);
            }
        }
    }
    //If there are many namespaces and the workaround is disabled, we must declare global attributes.
    //If the targetNamespace is not the mainNamespace, we must declare all the attributes.
    //if the target namespace is the main namespace, we do not need to declare anything, because the complex types which hold the attributes 
    //are also in the main namespace.
    if ((namespaceURIToPrefixMappings.size() - configuration.getSkipNamespaces().size()) > 1) {

        SortedMap<String, SchemaAttribute> globalAttributeCandidates = new TreeMap<>(
                schema.getAttributes().row(targetNamespace));
        if (!targetNamespace.equals(mainNamespace) && !targetNamespace.equals("")) {
            globalAttributesLoop: for (Map.Entry<String, SchemaAttribute> schemaAttributeEntry : globalAttributeCandidates
                    .entrySet()) {
                SchemaAttribute schemaAttribute = schemaAttributeEntry.getValue();
                //First, we check if the attribute has been already declared when the workaround is disabled. 
                //If so, we update the "use" property.
                //The type should have been already merged.
                if (!configuration.getStrictValidRootDefinitionWorkaround()) {
                    List<Element> alreadyGeneratedAttributeElements = elementSchema.getChildren("attribute",
                            xsdNamespace);
                    for (int i = 0; i < alreadyGeneratedAttributeElements.size(); i++) {
                        Element currentAttributeElement = alreadyGeneratedAttributeElements.get(i);
                        if (currentAttributeElement.getAttributeValue("name")
                                .equals(schemaAttribute.getName())) {
                            continue globalAttributesLoop;
                        }
                    }
                }
                Element attributeOrAttributeGroupElement = generateAttribute(schemaAttribute, true,
                        configuration, namespaceURIToPrefixMappings, targetNamespace, mainNamespace,
                        schemaAttributeEntry.getKey(), xsdNamespace);
                elementSchema.addContent(attributeOrAttributeGroupElement);
            }
        }
    }

    //Now, we declare global elements.
    //An element will be declared globally if and only if: 
    //1-elementsGlobal is true in the configuration
    //2-The element is a valid root
    //3-The element is in a namespace other than the main namespace. Note that the element WILL be surrounded by the corresponding group if the workaround is enabled.
    //Another important remark: Iterating over a set copy implies iterating over DISTINCT SchemaElements, so if two keys pointed to equal SchemaElements, we would generate it only once-
    SortedSet<SchemaElement> schemaElementsAtTargetNamespace = new TreeSet<>(new SchemaElementComparator());
    schemaElementsAtTargetNamespace.addAll(schema.getElements().row(targetNamespace).values());
    globalSchemaElementsLoop: for (SchemaElement schemaElement : schemaElementsAtTargetNamespace) {
        //         if(!configuration.getElementsGlobal()&&
        //               !schemaElement.isValidRoot()&&
        //               (targetNamespace.equals(mainNamespace)||configuration.getStrictValidRootDefinitionWorkaround()))
        if (!configuration.getElementsGlobal() && !schemaElement.isValidRoot()
                && (targetNamespace.equals(mainNamespace)))
            continue;
        //         for(Element currentElement:elementSchema.getContent(Filters.element("element",xsdNamespace))){
        //            if(schemaElement.getName().equals(currentElement.getAttributeValue("name")))
        //               continue globalSchemaElementsLoop;
        //         }
        String possibleGroupName = schemaElement.getName() + configuration.getTypeNamesAncestorsSeparator()
                + schemaElement.getType().getName();
        for (Element currentElement : elementSchema.getContent(Filters.element("group", xsdNamespace))) {
            if (possibleGroupName.equals(currentElement.getAttributeValue("name")))
                continue globalSchemaElementsLoop;
        }
        Element elementOrGroupElement = generateElement(schemaElement, true, configuration, targetNamespace,
                mainNamespace, null, namespaceURIToPrefixMappings, xsdNamespace);
        if (elementOrGroupElement.getName().equals("element")) {
            for (Element currentElement : elementSchema.getChildren("element", xsdNamespace)) {
                if (schemaElement.getName().equals(currentElement.getAttributeValue("name")))
                    continue globalSchemaElementsLoop;
            }
        }
        elementSchema.addContent(elementOrGroupElement);
    }
    return resultingDocument;
}

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

License:Open Source License

private void parseOcrWord(Element ocrWord) {
    String text = ocrWord.getText();
    text = adjuster.adjust(new String[] { "monotonic2polytonic", "ocr2u" }, normalizer2.normalize(text));
    String upText = low2upL1Trans.parse(text);
    if (text.endsWith("-")) {
        ocrWord.setAttribute("idx", "" + id++);
        hyphenPart1 = ocrWord;/*from w  w w.j a va 2  s. c o m*/
        return;
    } else if (hyphenPart1 != null) {
        text = adjuster.adjust(new String[] { "monotonic2polytonic", "ocr2u" },
                normalizer2.normalize(parseOcrHyphenatedWord(hyphenPart1, ocrWord)));
        upText = low2upL1Trans.parse(text);
    }
    Element infoSpan = new Element("span", xmlns);
    infoSpan.setText(adjuster.adjust(new String[] { "monotonic2polytonic", "ocr2u" },
            normalizer2.normalize(ocrWord.getText())));
    upText = upText.replaceAll(l1NonAlphabeticFilter, "");
    infoSpan.setAttribute("id", "" + id++);
    Integer occ;
    occ = ((occ = occHm.get(upText)) == null ? 1 : ++occ);
    occHm.put(upText, occ);
    infoSpan.setAttribute("uc", upText);
    try {
        ocrWord.getContent(0).detach();
    } catch (Exception ex) {
    }
    Token token = new Token(text);
    token = setClassiFicationAndScore(token);
    infoSpan = setInfoSpanClass(token, infoSpan);
    ocrWord.addContent(infoSpan);
    l1Fm.addSuitableElement(ocrWord);
    l1Fm.adjustPreviousSuitableElement();
    if (hyphenPart1 != null) {
        text = hyphenPart1.getText();
        hyphenPart1.getContent(0).detach();
        Element infoSpan1 = new Element("span", xmlns);
        infoSpan1.setAttribute("class", infoSpan.getAttributeValue("class"));
        infoSpan1.setText(text);
        hyphenPart1.addContent(infoSpan1);
        hyphenPart1 = null; //TODO: ???
    }
}

From source file:fr.crnan.videso3d.databases.aip.AIP.java

License:Open Source License

/**
 * Liste tous les lments dont le champ fieldParam <b>commence</b> par la chane de caractres "value", parmi les fils de l'lment racine.
 * <i>A n'utiliser que pour chercher des volumes par leur nom.</i>
 * @param root Le noeud contenant les lments parmi lesquels on effectue la recherche
 * @param fieldParam Le champ sur lequel porte la recherche
 * @param value La valeur du champ fieldParam
 * @return la liste des lments rpondant au critre.
 *///w ww .j a v a  2 s .  co m
public List<Element> findVolumes(Element root, String fieldParam, String value) {
    final String field = fieldParam;
    final String identity = value;
    Filter<Element> f = new AbstractFilter<Element>() {

        @Override
        public Element filter(Object o) {
            if (o instanceof Element) {
                Element element = (Element) o;
                String name = getVolumeName(element.getAttributeValue(field));
                if (name.startsWith(identity)) {
                    return element;
                }
            }
            return null;
        }

    };
    return root.getContent(f);
}

From source file:fr.crnan.videso3d.databases.aip.AIP.java

License:Open Source License

/**
 * Renvoie l'lment dont l'attribut "pk" correspond  <code>idNumber</code> parmi les fils de l'lment <code>racine</code>
 * @param racine /*from w w w  .j  a va  2 s  .c  o m*/
 * @param idNumber
 * @return L'lment demand ou <code>null</code> si celui-ci n'a pas t trouv.
 */
public Element findElement(Element racine, String idNumber) {
    final String id = idNumber;
    Filter<Element> f = new AbstractFilter<Element>() {

        @Override
        public Element filter(Object o) {
            if (o instanceof Element) {
                Element element = (Element) o;
                if (element.getAttributeValue("pk").equals(id)) {
                    return element;
                }
            }
            return null;
        }

    };

    List<Element> elements = racine.getContent(f);
    if (elements != null) {
        if (elements.size() > 0)
            return elements.get(0);
    }
    return null;
}

From source file:fr.crnan.videso3d.databases.aip.AIP.java

License:Open Source License

public List<Element> findElementsByChildId(Element root, String childParam, String value) {
    final String child = childParam;
    final String childID = value;

    Filter<Element> f = new AbstractFilter<Element>() {

        @Override/*from www .j  a  v a 2  s  .  c  o m*/
        public Element filter(Object o) {
            if (o instanceof Element) {
                Element element = (Element) o;
                String pkChild = element.getChild(child).getAttributeValue("pk");
                if (pkChild.equals(childID)) {
                    return (Element) o;
                }
            }
            return null;
        }
    };

    return root.getContent(f);
}

From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java

License:Apache License

@Override
public Document process(final Map<String, Object> context, final Document document, final Slide slide,
        final Resources resources, final Configuration configuration) throws JODTemplateException {
    final IteratorIterable<Element> atElements = document
            .getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace()));
    final List<Element> atElementsList = new ArrayList<>();
    while (atElements.hasNext()) {
        atElementsList.add(atElements.next());
    }//from  w  ww . j  a v a  2 s.c o m
    for (Element at : atElementsList) {
        if (at.getContentSize() != 0) {
            final Content content = at.getContent(0);
            if (content instanceof Comment) {
                final Comment comment = (Comment) content;
                processComment(comment, at, slide, configuration);
            }
        }
    }
    return document;
}

From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java

License:Apache License

private List<Element> getRemainingElements(final int fromIndex, final Element ap) {
    final List<Element> remains = new ArrayList<>();
    for (int i = fromIndex; i < ap.getContentSize(); ++i) {
        final Content apChild = ap.getContent(i);
        if (apChild instanceof Element) {
            final Element apChildElement = (Element) apChild;
            if (PPTXDocument.R_ELEMENT.equals(apChildElement.getName())
                    || PPTXDocument.BR_ELEMENT.equals(apChildElement.getName())) {
                remains.add(apChildElement);
            }/*  w  w w.j  av  a2  s  .co  m*/
        }
    }
    return remains;
}