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:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.FormulaConverter.java

License:Open Source License

/**
 * Replaces all formulas with the html representation of the mapped formula objects
 *
 * @param doc        JDOM Document where to replace the formulas
 * @param formulaMap Map of the indexed Formula Objects
 * @return JDOM Document with replaced formulas
 *///w ww.  j a v a 2 s.  com
public Document replaceFormulas(Document doc, Map<Integer, Formula> formulaMap) {
    List<Element> foundFormulas = xpath.evaluate(doc);

    if (foundFormulas.size() > 0) {
        Map<String, Element> formulaMarkupMap = new HashMap<>();

        // Initialize markup map
        for (Element element : foundFormulas) {
            formulaMarkupMap.put(element.getAttribute("id").getValue(), element);
        }

        // Replace all found formulas
        Iterator<Integer> formulaIterator = formulaMap.keySet().iterator();
        while (formulaIterator.hasNext()) {
            Integer id = formulaIterator.next();

            Element formulaMarkupRoot = formulaMarkupMap.get(FORMULA_ID_PREFIX + id);
            Formula formula = formulaMap.get(id);

            formulaMarkupRoot.removeAttribute("class");
            formulaMarkupRoot.removeContent();
            formulaMarkupRoot.setName("div");

            Element div = (Element) formulaMarkupRoot.getParent();
            div.setName("div");
            div.setAttribute("class", "formula");

            // Potentially there's text inside the paragraph...
            List<Text> texts = div.getContent(Filters.textOnly());
            if (texts.isEmpty() == false) {
                String textString = "";
                for (Text text : texts) {
                    textString += text.getText();
                }
                Element textSpan = new Element("span");
                textSpan.setAttribute("class", "text");
                textSpan.setText(textString);
                div.addContent(textSpan);

                List<Content> content = div.getContent();
                content.removeAll(texts);
            }

            if (generateDebugMarkup) {
                div.setAttribute("style", "border: 1px solid black;");

                // Header
                Element h4 = new Element("h4");
                h4.setText("DEBUG - Formula #" + formula.getId());
                div.addContent(h4);

                // Render LaTeX source
                Element latexPre = new Element("pre");
                latexPre.setAttribute("class", "debug-latex");
                latexPre.setText(formula.getLatexCode());
                div.addContent(latexPre);

                // Render MathML markup
                Element mathmlPre = new Element("pre");
                mathmlPre.setAttribute("class", "debug-mathml");
                mathmlPre.setText(formula.getMathMl());
                div.addContent(mathmlPre);

                // Render HTML Markup
                Element htmlPre = new Element("pre");
                htmlPre.setAttribute("class", "debug-html");
                XMLOutputter xmlOutputter = new XMLOutputter();
                xmlOutputter.setFormat(Format.getRawFormat());
                htmlPre.setText(xmlOutputter.outputString(formula.getHtml()));

                div.addContent(htmlPre);

            }

            // Set formula into
            formulaMarkupRoot.addContent(formula.getHtml());
        }
    }
    return doc;
}

From source file:com.eds.Model.XMLProcessor.java

License:Apache License

public Info ProcessInfoResponse(ServiceResponse serviceResponse) {
    BufferedReader reader = serviceResponse.getReader();
    Info info = new Info();
    if (!serviceResponse.getErrorStream().equals("")) {
        ApiErrorMessage errorMessage = ProcessError(serviceResponse.getErrorNumber(),
                serviceResponse.getErrorStream());
        info.setErrorMessage(errorMessage);
    } else {//from  ww w.ja  v  a  2s  . c  o m
        String InfoXML = "";
        try {
            String line = "";
            while ((line = reader.readLine()) != null) {
                InfoXML += line;
            }
            StringReader stringReader = new StringReader(InfoXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            Element infoResponseMessage = doc.getRootElement();

            Element availableSearchCriteria = infoResponseMessage.getChild("AvailableSearchCriteria",
                    infoResponseMessage.getNamespace());
            if (null != availableSearchCriteria) {
                // Process Sorts
                ArrayList<AvailableSort> sortsList = new ArrayList<AvailableSort>();
                Element availableSorts = availableSearchCriteria.getChild("AvailableSorts",
                        availableSearchCriteria.getNamespace());
                if (null != availableSorts) {
                    List<Element> availableSortsList = availableSorts.getChildren();
                    for (int i = 0; i < availableSortsList.size(); i++) {
                        Element eAvailableSort = (Element) availableSortsList.get(i);
                        if (null != eAvailableSort) {
                            AvailableSort as = new AvailableSort();
                            String Id = eAvailableSort.getChildText("Id", eAvailableSort.getNamespace());
                            String Label = eAvailableSort.getChildText("Label", eAvailableSort.getNamespace());
                            String AddAction = eAvailableSort.getChildText("AddAction",
                                    eAvailableSort.getNamespace());
                            as.setId(Id);
                            as.setLabel(Label);
                            as.setAddAction(AddAction);
                            sortsList.add(as);
                        }

                    }
                }
                info.setAvailableSortsList(sortsList);

                // Process available Search Field list
                ArrayList<AvailableSearchField> searchFieldsList = new ArrayList<AvailableSearchField>();
                Element availableSearchFields = availableSearchCriteria.getChild("AvailableSearchFields",
                        availableSearchCriteria.getNamespace());
                if (null != availableSearchFields) {
                    List<Element> availableSearchFieldsList = availableSearchFields.getChildren();
                    for (int i = 0; i < availableSearchFieldsList.size(); i++) {
                        Element eAvailableSearchField = (Element) availableSearchFieldsList.get(i);
                        AvailableSearchField asf = new AvailableSearchField();
                        String fieldCode = eAvailableSearchField.getContent(0).getValue();
                        String label = eAvailableSearchField.getContent(1).getValue();
                        asf.setFieldCode(fieldCode);
                        asf.setLabel(label);
                        searchFieldsList.add(asf);

                    }
                }
                info.setAvailableSearchFieldsList(searchFieldsList);

                // process available expanders
                ArrayList<AvailableExpander> expandersList = new ArrayList<AvailableExpander>();
                Element availableExpanders = availableSearchCriteria.getChild("AvailableExpanders",
                        availableSearchCriteria.getNamespace());
                if (null != availableExpanders) {
                    List<Element> availableExpandersList = availableExpanders.getChildren();
                    for (int i = 0; i < availableExpandersList.size(); i++) {

                        Element eAvailableExpander = (Element) availableExpandersList.get(i);
                        AvailableExpander ae = new AvailableExpander();
                        String id = eAvailableExpander.getChildText("Id", eAvailableExpander.getNamespace());
                        String label = eAvailableExpander.getChildText("Label",
                                eAvailableExpander.getNamespace());
                        String addAction = eAvailableExpander.getChildText("AddAction",
                                eAvailableExpander.getNamespace());
                        ae.setId(id);
                        ae.setLabel(label);
                        ae.setAddAction(addAction);
                        expandersList.add(ae);
                    }
                }
                info.setAvailableExpandersList(expandersList);

                // process available limiters
                ArrayList<AvailableLimiter> limitersList = new ArrayList<AvailableLimiter>();
                Element availableLimiters = availableSearchCriteria.getChild("AvailableLimiters",
                        availableSearchCriteria.getNamespace());
                if (null != availableLimiters) {
                    List<Element> availableLimitersList = availableLimiters.getChildren();
                    for (int i = 0; i < availableLimitersList.size(); i++) {
                        Element eAvailableLimiter = (Element) availableLimitersList.get(i);
                        AvailableLimiter al = new AvailableLimiter();
                        String id = eAvailableLimiter.getChildText("Id", eAvailableLimiter.getNamespace());
                        String label = eAvailableLimiter.getChildText("Label",
                                eAvailableLimiter.getNamespace());
                        String type = eAvailableLimiter.getChildText("Type", eAvailableLimiter.getNamespace());
                        String addAction = eAvailableLimiter.getChildText("AddAction",
                                eAvailableLimiter.getNamespace());
                        String defaultOn = eAvailableLimiter.getChildText("DefaultOn",
                                eAvailableLimiter.getNamespace());
                        String order = eAvailableLimiter.getChildText("Order",
                                eAvailableLimiter.getNamespace());
                        al.setId(id);
                        al.setLabel(label);
                        al.setType(type);
                        al.setAddAction(addAction);
                        al.setDefaultOn(defaultOn);
                        al.setOrder(order);

                        if (type.equals("multiselectvalue")) {
                            Element eLimiterValues = eAvailableLimiter.getChild("LimiterValues",
                                    eAvailableLimiter.getNamespace());
                            if (null != eLimiterValues) {
                                List<Element> limiterValues = eLimiterValues.getChildren();
                                ArrayList<LimiterValue> limiterValueList = new ArrayList<LimiterValue>();
                                for (int j = 0; j < limiterValues.size(); j++) {
                                    Element eLimiterValue = (Element) limiterValues.get(j);
                                    LimiterValue lv = new LimiterValue();

                                    String valueValue = eLimiterValue.getChildText("Id",
                                            eLimiterValue.getNamespace());
                                    String valueAddAction = eLimiterValue.getChildText("AddAction",
                                            eLimiterValue.getNamespace());
                                    // This sample application is only going
                                    // one
                                    // level deep
                                    lv.setValue(valueValue);
                                    lv.setAddAction(valueAddAction);
                                    limiterValueList.add(lv);
                                }
                                al.setLimitervalues(limiterValueList);
                            }
                        }
                        limitersList.add(al);
                    }
                    info.setAvailableLimitersList(limitersList);
                }

                // set available Search Modes
                ArrayList<AvailableSearchMode> searchModeList = new ArrayList<AvailableSearchMode>();
                Element availableSearchModes = availableSearchCriteria.getChild("AvailableSearchModes",
                        availableSearchCriteria.getNamespace());
                if (null != availableSearchModes) {
                    List<Element> availableSearchModeList = availableSearchModes.getChildren();
                    for (int i = 0; i < availableSearchModeList.size(); i++) {
                        Element eAvailableSearchMode = (Element) availableSearchModeList.get(i);
                        AvailableSearchMode asm = new AvailableSearchMode();
                        String mode = eAvailableSearchMode.getChildText("Mode",
                                eAvailableSearchMode.getNamespace());
                        String label = eAvailableSearchMode.getChildText("Label",
                                eAvailableSearchMode.getNamespace());
                        String addAction = eAvailableSearchMode.getChildText("AddAction",
                                eAvailableSearchMode.getNamespace());
                        String defaultOn = eAvailableSearchMode.getChildText("DefaultOn",
                                eAvailableSearchMode.getNamespace());
                        asm.setMode(mode);
                        asm.setLabel(label);
                        asm.setAddAction(addAction);
                        asm.setDefaultOn(defaultOn);
                        searchModeList.add(asm);
                    }
                }
                info.setAvailableSearchModeList(searchModeList);
            }

            // Set ViewResult settings
            Element viewResultSettings = infoResponseMessage.getChild("ViewResultSettings",
                    infoResponseMessage.getNamespace());
            if (null != viewResultSettings) {
                ViewResultSettings vrs = new ViewResultSettings();
                String resultsPerPage = viewResultSettings.getChildText("ResultsPerPage",
                        viewResultSettings.getNamespace());
                int rpp = 20;
                if (null != resultsPerPage) {
                    try {
                        rpp = Integer.parseInt(resultsPerPage);
                    } catch (NumberFormatException e) {
                    }
                }
                vrs.setResultsPerPage(rpp);
                vrs.setResultListView(
                        viewResultSettings.getChildText("ResultListView", viewResultSettings.getNamespace()));
                info.setViewResultSettings(vrs);
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing info response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            info.setErrorMessage(errorMessage);
        }
    }
    return info;
}

From source file:com.eds.Model.XMLProcessor.java

License:Apache License

public String ProcessEndSessionResponse(ServiceResponse serviceResponse) {
    BufferedReader reader = serviceResponse.getReader();
    String EndSessionXML = "";
    String IsSuccessful = "0";

    try {//  www .  j a v a 2  s. co m
        String line = "";
        while ((line = reader.readLine()) != null) {
            EndSessionXML += line;
        }
        StringReader stringReader = new StringReader(EndSessionXML);
        InputSource inputSource = new InputSource(stringReader);
        Document doc = (new SAXBuilder()).build(inputSource);
        Element EndSessionResponse = doc.getRootElement();
        IsSuccessful = EndSessionResponse.getContent(0).getValue();
    } catch (Exception e) {
    }

    return IsSuccessful;
}

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

/**
 * Constructs a result list in response to an EDS API Search Request
 *//*from  www. ja  v a 2  s  .co m*/
public ResultsList buildResultsList(Response response) {

    ResultsList resultsList = new ResultsList();
    String resultsListXML = "";

    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        resultsList.setApierrormessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {
        BufferedReader reader = response.getRead();
        if (null != reader) {
            try {
                String line = "";
                while ((line = reader.readLine()) != null) {
                    resultsListXML += line;
                }
            } catch (IOException e) {
                ApiErrorMessage errorMessage = new ApiErrorMessage();
                errorMessage.setErrorDescription("Error processing resultList response");
                errorMessage.setDetailedErrorDescription(e.getMessage());
                resultsList.setApierrormessage(errorMessage);
            }
        }
        try {
            StringReader stringReader = new StringReader(resultsListXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            // root element (level 1), handle resultsList
            Element searchResponseMessageGet = doc.getRootElement();

            // level 2 elements
            if (null == searchResponseMessageGet)
                return resultsList;

            Element searchRequestGet = searchResponseMessageGet.getChild("SearchRequestGet",
                    searchResponseMessageGet.getNamespace());
            Element searchResult = searchResponseMessageGet.getChild("SearchResult",
                    searchResponseMessageGet.getNamespace());
            // level 3 elements
            if (null != searchRequestGet) {
                Element queryString = searchRequestGet.getChild("QueryString", searchRequestGet.getNamespace());
                // Get Query String
                String querystring = queryString.getContent(0).getValue();
                resultsList.setQueryString(querystring);
            }

            Element statistics = searchResult.getChild("Statistics", searchResult.getNamespace());
            Element data = searchResult.getChild("Data", searchResult.getNamespace());

            /*
             * In next steps, elements will be analyzed separately
             */

            // Get Total Hits and Total Search Time
            String totalHits = "0";
            if (null != statistics) {
                totalHits = statistics.getContent(0).getValue();
                String totalSearchTime = statistics.getContent(1).getValue();
                resultsList.setHits(totalHits);
                resultsList.setSearchTime(totalSearchTime);
            }

            if (Integer.parseInt(totalHits) > 0 && null != data) {
                // Get Results
                Element records = data.getChild("Records", data.getNamespace());
                if (null != records && null != records.getChildren()) {
                    List<Element> recordsList = records.getChildren();
                    for (int i = 0; i < recordsList.size(); i++) {
                        Element xmlRecord = (Element) recordsList.get(i);
                        if (null == xmlRecord)
                            continue;
                        Record record = new Record();
                        record = constructRecord(xmlRecord);
                        resultsList.getResultsList().add(record);
                    }
                }
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            resultsList.setApierrormessage(errorMessage);
        }
    }
    return resultsList;

}

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

License:Apache License

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

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

From source file:com.tactfactory.harmony.platform.winphone.updater.XmlProjectWinphone.java

License:Open Source License

private void removeIfExists(Element element, String type, String file) {
    Filter<Element> filter = new ElementFilter(type);
    List<Element> content = element.getContent(filter);
    List<Element> elementToDelete = new ArrayList<>();

    for (Element node : content) {
        if (node.getAttribute("Include").getValue().equals(file)) {
            elementToDelete.add(node);/*from  w  w w.jav a 2  s .  co m*/
        }
    }

    for (Element node : elementToDelete) {
        element.removeContent(node);
    }
}

From source file:com.tactfactory.harmony.platform.winphone.updater.XmlProjectWinphone.java

License:Open Source License

private Element findFirstItemGroup(String groupType) {
    Element result = null;/*w ww  . j  a  va2 s  .c  om*/

    Filter<Element> filter = new ElementFilter(XML_ELEMENT_ITEM);
    List<Element> content = this.rootNode.getContent(filter);

    filter = new ElementFilter(groupType);

    for (Element element : content) {
        content = element.getContent(filter);

        if (!content.isEmpty()) {
            result = element;
            break;
        }
    }

    if (result == null) {
        result = new Element(XML_ELEMENT_ITEM);
        filter = new ElementFilter("Import");
        content = this.rootNode.getContent(filter);
        rootNode.addContent(rootNode.indexOf(content.get(0)), result);
    }

    return result;
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.modules.OperatorNormalizer.java

License:Apache License

private void normalizeUnicode(final Element ancestor, final Normalizer.Form form) {
    assert ancestor != null && form != null;
    final List<Text> texts = new ArrayList<Text>();
    final ContentFilter textFilter = new ContentFilter(ContentFilter.TEXT);
    for (Content text : ancestor.getContent(textFilter)) {
        texts.add((Text) text);/*from w w  w.j a  v a  2  s .c om*/
    }
    for (Element element : ancestor.getDescendants(new ElementFilter())) {
        for (Content text : element.getContent(textFilter)) {
            texts.add((Text) text);
        }
    }
    for (Text text : texts) {
        if (Normalizer.isNormalized(text.getText(), form)) {
            continue;
        }
        final String normalizedString = Normalizer.normalize(text.getText(), form);
        LOGGER.log(Level.FINE, "Text ''{0}'' normalized to ''{1}''",
                new Object[] { text.getText(), normalizedString });
        text.setText(normalizedString);
        assert Normalizer.isNormalized(text.getText(), form);
    }
}

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

License:Open Source License

/**
 * @param is/*from  ww w  .j  a va 2 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, StandardCharsets.UTF_8));
    } catch (FeedException e) {
        LOGGER.debug("Unable to read RSS/Atom feed.", e);
    }

    List<SyndEntry> entries;
    long totalResults = 0;
    List<Element> foreignMarkup = null;
    if (syndFeed != null) {
        entries = syndFeed.getEntries();
        for (SyndEntry entry : entries) {
            resultQueue.addAll(createResponseFromEntry(entry));
        }
        totalResults = entries.size();
        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);

    if (foreignMarkup != null) {
        this.foreignMarkupBiConsumer.accept(Collections.unmodifiableList(foreignMarkup), response);
    }

    return response;
}

From source file:ddf.catalog.source.opensearch.impl.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.// ww w.j  ava  2  s .c  om
 *
 * @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 = "";

    for (Element element : foreignMarkup) {
        if (element.getName().equals("score")) {
            relevance = element.getContent(0).getValue();
        }
        metacards.addAll(processAdditionalForeignMarkups(element, id));
    }
    // 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) {
        Metacard metacard = parseContent(content.getValue(), id);
        if (metacard != null) {
            metacard.setSourceId(this.shortname);
            String title = metacard.getTitle();
            if (StringUtils.isEmpty(title)) {
                metacard.setAttribute(new AttributeImpl(Core.TITLE, entry.getTitle()));
            }
            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())) {
            metacard.setAttribute(new AttributeImpl(Metacard.CONTENT_TYPE, 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;
}