List of usage examples for org.jdom2 Element getChildren
public List<Element> getChildren()
List
of all the child elements nested directly (one level deep) within this element, as Element
objects. From source file:com.c4om.autoconf.ulysses.extra.svinchangesetgenerator.SVINChangesetGenerator.java
License:Apache License
/** * Recursive method that mixes two XML trees in the following way: * <ul>/*w w w.ja v a 2 s . c o m*/ * <li>If a child exists at the source leaf but not at destination, the * element is copied as a child to the destination leaf</li> * <li>If a child exists at both the source and the destination leafs and * the source child has children, this method is recursively called to mix * both children</li> * </ul> * Some important remarks: * <ul> * <li>Equality comparison is not made via common methods but via * {@link JDOMUtils#elementsEqualAtCNameAndAttributes(Element, Element)} * .</li> * <li>Results of this method are returned as changes to the * destinationLeaf.</li> * <li>An attribute may be appended to all the elements added to the * destination leaf by this method.</li> * <li>Elements of a concrete namespace can be ignored by this method, if desired.</li> * </ul> * * @param sourceLeaf * The source leaf to mix into the destination leaf. It remains * unchanged. * @param destinationLeaf * The destination leaf, where the source leaf will be mixed * into. Results will be returned as changes at this element, so * IT WILL NOT REMAIN UNCHANGED AFTER THIS METHOD (normally). You * should consider using {@link Element#clone()} if necessary. * @param metadataAttributeToAppend * an attribute to be appended to each element added by this * method to the destinationLeaf. If a node with descendants is * added, the attribute will be added only to the top-level * element (not to all the descendants). If null, no attribute * will be added. * @param ignoreNamespaceURIIfTextPresent any element whose namespace URI matches this one * will be ignored if the source element has text content. * If null, no element is ignored. */ private void mixTreesRecursive(Element sourceLeaf, Element destinationLeaf, Attribute metadataAttributeToAppend, String ignoreNamespaceURIIfTextPresent) { List<Content> sourceLeafContent = sourceLeaf.getContent(); //j is the index for "only-element" content for (int i = 0, j = 0; i < sourceLeafContent.size(); i++) { Content currentContent = sourceLeafContent.get(i); if (!(currentContent instanceof Element)) { continue; } Element currentSourceChild = (Element) currentContent; Element currentDestinationChild = searchElementEqualAtCNameAndAttributes(destinationLeaf.getChildren(), currentSourceChild); if (currentDestinationChild == null) { if (ignoreNamespaceURIIfTextPresent != null && !destinationLeaf.getTextNormalize().equals("") && ignoreNamespaceURIIfTextPresent.equals(currentSourceChild.getNamespaceURI())) { continue; } // There is not equivalent node at destination, so we copy the // whole currentSourceChild. Element elementToAdd = currentSourceChild.clone(); if (metadataAttributeToAppend != null) { elementToAdd.setAttribute(metadataAttributeToAppend.clone()); } destinationLeaf.addContent(j, elementToAdd); } else { // Element exists at destination. If it has children, we recurse // to fill them (they might be not completely filled). if (currentSourceChild.getChildren().size() > 0) { mixTreesRecursive(currentSourceChild, currentDestinationChild, metadataAttributeToAppend, ignoreNamespaceURIIfTextPresent); } } j++; } }
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 ww . j a va 2 s . c om*/ * * @param pathToConfiguration path to the runtime configuration. * * @param reportDocument the report document (objective solution description). * * @return The generated changeset document. * * @throws JDOMException * If there are problems at JDOM2 XML parsings * @throws IOException * I/O problems * @throws SaxonApiException * problems with Saxon API while transforming metamodel * suggestions into partial autocomplete nodes * @throws ParserConfigurationException * problems with javax.xml APIs while transforming metamodel * suggestions into partial autocomplete nodes */ public Document getSingleChangesetDocument(String pathToConfiguration, Document reportDocument) throws JDOMException, IOException, SaxonApiException, ParserConfigurationException { Element resultRoot = new Element("changeset", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER); resultRoot.addNamespaceDeclaration(NAMESPACE_AUTOCONF_METADATA); // To // prevent // several // "xmlns:*****" // attributes // to // appear // everywhere Document result = new Document(resultRoot); Element reportElement = reportDocument.getRootElement(); for (Element currentDiscrepancyElement : reportElement.getChildren()) { boolean isCreate = false; Element interestingPathsElement = currentDiscrepancyElement.getChild("interestingPaths", NAMESPACE_SVRL_INTERPETER_REPORT); String searchPathText = interestingPathsElement.getAttributeValue("search-path"); String basePathText = interestingPathsElement.getAttributeValue("base-path"); String keySubpathText = interestingPathsElement.getAttributeValue("key-subpath"); // First, we look for a path to search the element where discrepancy // took place (if it exists) String[] docAndPath; String searchPathInternal; if (searchPathText == null) { docAndPath = divideDocAndPath(basePathText); searchPathInternal = docAndPath[1] + "[" + keySubpathText + "]"; } else { docAndPath = divideDocAndPath(searchPathText); searchPathInternal = docAndPath[1]; } if (!documentCache.containsKey(docAndPath[0])) { documentCache.put(docAndPath[0], loadJDOMDocumentFromFile(new File(pathToConfiguration + "/" + docAndPath[0]))); } Document currentDoc = documentCache.get(docAndPath[0]); List<Element> discordingElementAtDocList = performJAXENXPath(searchPathInternal, currentDoc, Filters.element(), xpathNamespaces); if (discordingElementAtDocList.size() == 0) { isCreate = true; } if (isCreate) { Element nodeToCreate = currentDiscrepancyElement .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0) .clone(); //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it. nodeToCreate.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT); boolean thereAreMetamodelSuggestions = currentDiscrepancyElement .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren() .size() > 0; if (thereAreMetamodelSuggestions) { Element metamodelSuggestionUntransformed = currentDiscrepancyElement .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0) .clone(); Document suggestionMiniDocument = new Document(metamodelSuggestionUntransformed); Document suggestionMiniDocumentTransformed = performXSLT(suggestionMiniDocument, xsltTransformMetamodelDocument); Element metamodelSuggestion = suggestionMiniDocumentTransformed.getRootElement(); Attribute metadataAttribute = new Attribute("autogen-from", "metamodel", NAMESPACE_AUTOCONF_METADATA); mixTreesRecursive(metamodelSuggestion, nodeToCreate, metadataAttribute, NAMESPACE_AUTOCONF_METADATA.getURI()); } else { Attribute mayNeedManualCompletion = new Attribute("may-need-completion", "true", NAMESPACE_AUTOCONF_METADATA); nodeToCreate.setAttribute(mayNeedManualCompletion); } Element createNodeElement = new Element("add-node", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER); final String REGEXP_TO_GET_PARENT_PATH = "(.+)(/[^\\[\\]/]+(\\[.+\\])?)$"; Pattern patternToGetParentPath = Pattern.compile(REGEXP_TO_GET_PARENT_PATH); Matcher matcherToGetParentPath = patternToGetParentPath.matcher(searchPathInternal); matcherToGetParentPath.matches(); String pathToParent = matcherToGetParentPath.group(1); Attribute pathToParentAttr = new Attribute("underParentAtPath", pathToParent); Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]); createNodeElement.setAttribute(documentToChangeAttr); createNodeElement.setAttribute(pathToParentAttr); createNodeElement.addContent(nodeToCreate); resultRoot.addContent(createNodeElement); } else { for (int i = 0; i < discordingElementAtDocList.size(); i++) { Element nodeToModify = currentDiscrepancyElement .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0) .clone(); //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it. nodeToModify.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT); Element discordingElementAtDoc = discordingElementAtDocList.get(i); mixTreesRecursive(discordingElementAtDoc, nodeToModify, null, NAMESPACE_AUTOCONF_METADATA.getURI()); Element replaceNodeElement = new Element("replace-node", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER); Attribute pathToElementAttr = new Attribute("atPath", generateAttributeBasedPath(discordingElementAtDoc)); Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]); replaceNodeElement.setAttribute(documentToChangeAttr); replaceNodeElement.setAttribute(pathToElementAttr); replaceNodeElement.addContent(nodeToModify); resultRoot.addContent(replaceNodeElement); } } } return result; }
From source file:com.dexterapps.android.translator.TranslateTextForAndroid.java
License:Apache License
private void parseXMLAndGenerateDom(String sourceFile) { SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(sourceFile); //System.out.println(xmlFile.getAbsolutePath()); try {/*from w w w . j a va 2s .co m*/ /*Navigate the XML DOM and populate the string array for translation We also map the XML in java object so we can use to navigate it again for generating the xml back */ Document document = (Document) builder.build(xmlFile); Element rootNode = document.getRootElement(); List list = rootNode.getChildren(); for (int i = 0; i < list.size(); i++) { AndroidStringMapping stringElement = new AndroidStringMapping(); Element stringNode = (Element) list.get(i); if (stringNode.getName().equalsIgnoreCase("string")) { stringElement.setType("string"); stringElement.setAttributeName(stringNode.getAttributeValue("name")); stringElement.setAttributeValue(stringNode.getText()); baseLanguageStringForTranslation.add(stringNode.getText()); baseStringResourcesMapping.put(stringNode.getText(), i); } else if (stringNode.getName().equalsIgnoreCase("string-array")) { List stringArrayNodeList = stringNode.getChildren(); ArrayList<String> stringArrayItems = new ArrayList<String>(); for (int j = 0; j < stringArrayNodeList.size(); j++) { Element stringArrayNode = (Element) stringArrayNodeList.get(j); baseLanguageStringForTranslation.add(stringArrayNode.getText()); baseStringResourcesMapping.put(stringArrayNode.getText(), i + j); stringArrayItems.add(stringArrayNode.getText()); } stringElement.setType("string-array"); stringElement.setAttributeName(stringNode.getAttributeValue("name")); stringElement.setAttributeValue(stringArrayItems); } else { List stringPluralNodeList = stringNode.getChildren(); ArrayList<AndroidStringPlurals> stringPluralsItems = new ArrayList<AndroidStringPlurals>(); for (int j = 0; j < stringPluralNodeList.size(); j++) { Element stringPluralNode = (Element) stringPluralNodeList.get(j); baseLanguageStringForTranslation.add(stringPluralNode.getText()); baseStringResourcesMapping.put(stringPluralNode.getText(), i + j); AndroidStringPlurals pluralItem = new AndroidStringPlurals(); pluralItem.setAttributeName(stringPluralNode.getAttributeValue("quantity")); pluralItem.setAttributeValue(stringPluralNode.getText()); stringPluralsItems.add(pluralItem); } stringElement.setType("plurals"); stringElement.setAttributeName(stringNode.getAttributeValue("name")); stringElement.setAttributeValue(stringPluralsItems); } stringXmlDOM.add(stringElement); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } }
From source file:com.eds.Model.XMLProcessor.java
License:Apache License
public SearchResponse ProcessSearchResponse(ServiceResponse serviceResponse) { BufferedReader reader = serviceResponse.getReader(); SearchResponse searchResponse = new SearchResponse(); if (null != serviceResponse.getErrorStream() && !serviceResponse.getErrorStream().isEmpty()) { searchResponse.setApierrormessage( ProcessError(serviceResponse.getErrorNumber(), serviceResponse.getErrorStream())); } else {/* w w w.j a va2s .c om*/ String resultsListXML = ""; try { String line = ""; while ((line = reader.readLine()) != null) { resultsListXML += line; } } catch (IOException e1) { ApiErrorMessage errorMessage = new ApiErrorMessage(); errorMessage.setErrorDescription("Error processing search response"); errorMessage.setDetailedErrorDescription(e1.getMessage()); searchResponse.setApierrormessage(errorMessage); } try { StringReader stringReader = new StringReader(resultsListXML); InputSource inputSource = new InputSource(stringReader); Document doc = (new SAXBuilder()).build(inputSource); // Process root element Element searchResponseMessageGet = doc.getRootElement(); Element searchResult = searchResponseMessageGet.getChild("SearchResult", searchResponseMessageGet.getNamespace()); // Process search request message returned in the response. Element searchRequestGet = searchResponseMessageGet.getChild("SearchRequestGet", searchResponseMessageGet.getNamespace()); if (null != searchRequestGet) { // process the querystring String queryString = searchRequestGet.getChildText("QueryString", searchRequestGet.getNamespace()); searchResponse.setQueryString(queryString); // Process search criteria Element searchCriteriaWithActions = searchRequestGet.getChild("SearchCriteriaWithActions", searchRequestGet.getNamespace()); if (null != searchCriteriaWithActions) { // Process Queries with actions ArrayList<QueryWithAction> queryList = new ArrayList<QueryWithAction>(); Element queriesWithAction = searchCriteriaWithActions.getChild("QueriesWithAction", searchCriteriaWithActions.getNamespace()); if (null != queriesWithAction) { List<Element> queriesWithActions = queriesWithAction.getChildren(); for (Element queryWithAction : queriesWithActions) { QueryWithAction queryObject = new QueryWithAction(); String removeAction = queryWithAction.getChildText("RemoveAction", queryWithAction.getNamespace()); queryObject.setRemoveAction(removeAction); Element query = queryWithAction.getChild("Query", queryWithAction.getNamespace()); if (null != query) { String term = query.getChildText("Term", queryWithAction.getNamespace()); String fieldCode = queryWithAction.getChildText("FieldCode", queryWithAction.getNamespace()); String booleanOperator = queryWithAction.getChildText("BooleanOperator", queryWithAction.getNamespace()); queryObject.setTerm(term); queryObject.setFieldCode(fieldCode); queryObject.setOperator(booleanOperator); } queryList.add(queryObject); } } searchResponse.setQueryList(queryList); if (null != searchResponse.getQueryList() && !searchResponse.getQueryList().isEmpty()) searchResponse.setQuery(searchResponse.getQueryList().get(0)); // process limiters with action ArrayList<LimiterWithAction> limiterList = new ArrayList<LimiterWithAction>(); Element limitersWithAction = searchCriteriaWithActions.getChild("LimitersWithAction", searchCriteriaWithActions.getNamespace()); if (limitersWithAction != null) { List<Element> eLimitersWithAction = limitersWithAction.getChildren(); for (int i = 0; i < eLimitersWithAction.size(); i++) { Element eLimiterWithAction = (Element) eLimitersWithAction.get(i); LimiterWithAction lwa = new LimiterWithAction(); String Id = eLimiterWithAction.getChildText("Id", eLimiterWithAction.getNamespace()); String removeAction = eLimiterWithAction.getChildText("RemoveAction", eLimiterWithAction.getNamespace()); lwa.setId(Id); lwa.setRemoveAction(removeAction); Element eLimiterValuesWithAction = eLimiterWithAction .getChild("LimiterValuesWithAction", eLimiterWithAction.getNamespace()); List<Element> limiterValuesWithActionList = eLimiterValuesWithAction.getChildren(); ArrayList<LimiterValueWithAction> lvalist = new ArrayList<LimiterValueWithAction>(); for (int j = 0; j < limiterValuesWithActionList.size(); j++) { LimiterValueWithAction lvwa = new LimiterValueWithAction(); Element eLimiterValueWithAction = (Element) limiterValuesWithActionList.get(j); String value = eLimiterValueWithAction.getChildText("Value", eLimiterValueWithAction.getNamespace()); String vRemoveAction = eLimiterValueWithAction.getChildText("RemoveAction", eLimiterValueWithAction.getNamespace()); lvwa.setValue(value); lvwa.setRemoveAction(vRemoveAction); lvalist.add(lvwa); } lwa.setLvalist(lvalist); limiterList.add(lwa); } } searchResponse.setSelectedLimiterList(limiterList); // Process applied expanders ArrayList<ExpandersWithAction> expanderList = new ArrayList<ExpandersWithAction>(); Element ExpandersWithAction = searchCriteriaWithActions.getChild("ExpandersWithAction", searchCriteriaWithActions.getNamespace()); if (ExpandersWithAction != null) { List<Element> expandersWithActionList = ExpandersWithAction.getChildren(); for (int i = 0; i < expandersWithActionList.size(); i++) { Element expanderWithAction = (Element) expandersWithActionList.get(i); ExpandersWithAction ewa = new ExpandersWithAction(); String id = expanderWithAction.getChildText("Id", expanderWithAction.getNamespace()); String removeAction = expanderWithAction.getChildText("RemoveAction", expanderWithAction.getNamespace()); ewa.setId(id); ewa.setRemoveAction(removeAction); expanderList.add(ewa); } } searchResponse.setExpanderwithActionList(expanderList); // process applied facets ArrayList<FacetFilterWithAction> facetFiltersList = new ArrayList<FacetFilterWithAction>(); Element facetFiltersWithAction = searchCriteriaWithActions .getChild("FacetFiltersWithAction", searchCriteriaWithActions.getNamespace()); if (facetFiltersWithAction != null) { for (Element facetFilterWithActionXML : facetFiltersWithAction.getChildren()) { FacetFilterWithAction facetWithAction = new FacetFilterWithAction(); String filterId = facetFilterWithActionXML.getChildText("FilterId", facetFilterWithActionXML.getNamespace()); String removeAction = facetFilterWithActionXML.getChildText("RemoveAction", facetFilterWithActionXML.getNamespace()); facetWithAction.setFilterId(filterId); facetWithAction.setRemoveAction(removeAction); ArrayList<FacetValueWithAction> facetValuesWithActionList = new ArrayList<FacetValueWithAction>(); Element facetValuesWithAction = facetFilterWithActionXML .getChild("FacetValuesWithAction", facetFilterWithActionXML.getNamespace()); for (Element facetValueWithAction : facetValuesWithAction.getChildren()) { FacetValueWithAction fvwa = new FacetValueWithAction(); String eRemoveAction = facetValueWithAction.getChildText("RemoveAction", facetValueWithAction.getNamespace()); fvwa.setRemoveAction(eRemoveAction); Element eFacetValue = facetValueWithAction.getChild("FacetValue", facetValueWithAction.getNamespace()); if (null != eFacetValue) { EachFacetValue efv = new EachFacetValue(); String id = eFacetValue.getChildText("Id", eFacetValue.getNamespace()); String value = eFacetValue.getChildText("Value", eFacetValue.getNamespace()); efv.setValue(value); efv.setId(id); fvwa.setEachfacetvalue(efv); } facetValuesWithActionList.add(fvwa); } facetWithAction.setFacetvaluewithaction(facetValuesWithActionList); facetFiltersList.add(facetWithAction); } } searchResponse.setFacetfiltersList(facetFiltersList); } } // Process the search result returned in the response // Get Total Hits and Total Search Time Element statistics = searchResult.getChild("Statistics", searchResult.getNamespace()); long hits = 0; if (null != statistics) { String totalHits = statistics.getChildText("TotalHits", statistics.getNamespace()); try { hits = Long.parseLong(totalHits); } catch (Exception e) { hits = 0; } String totalSearchTime = statistics.getChildText("TotalSearchTime", statistics.getNamespace()); searchResponse.setSearchTime(totalSearchTime); } searchResponse.setHits(String.valueOf(hits)); if (hits > 0) { // process results Results Element data = searchResult.getChild("Data", searchResult.getNamespace()); if (null != data) { Element records = data.getChild("Records", data.getNamespace()); if (null != records) { List<Element> recordsList = records.getChildren(); for (int i = 0; i < recordsList.size(); i++) { Element record = (Element) recordsList.get(i); Result result = constructRecord(record); searchResponse.getResultsList().add(result); } } } // Get Facets. if there are no hits, don't bother checking // facets Element availableFacets = searchResult.getChild("AvailableFacets", searchResult.getNamespace()); if (null != availableFacets) { List<Element> facetsList = availableFacets.getChildren(); for (int e = 0; e < facetsList.size(); e++) { Facet facet = new Facet(); Element availableFacet = (Element) facetsList.get(e); String id = availableFacet.getChildText("Id", availableFacet.getNamespace()); String label = availableFacet.getChildText("Label", availableFacet.getNamespace()); facet.setId(id); facet.setLabel(label); Element availableFacetValues = availableFacet.getChild("AvailableFacetValues", availableFacet.getNamespace()); if (null != availableFacetValues) { List<Element> availableFacetValuesList = availableFacetValues.getChildren(); for (int f = 0; f < availableFacetValuesList.size(); f++) { FacetValue facetValue = new FacetValue(); Element availableFacetValue = (Element) availableFacetValuesList.get(f); String value = availableFacetValue.getChildText("Value", availableFacetValue.getNamespace()); String count = availableFacetValue.getChildText("Count", availableFacetValue.getNamespace()); String addAction = availableFacetValue.getChildText("AddAction", availableFacetValue.getNamespace()); facetValue.setValue(value); facetValue.setCount(count); facetValue.setAddAction(addAction); facet.getFacetsValueList().add(facetValue); } } searchResponse.getFacetsList().add(facet); // --------end to handle resultsList } } } } catch (Exception e) { ApiErrorMessage errorMessage = new ApiErrorMessage(); errorMessage.setErrorDescription("Error processing search response"); errorMessage.setDetailedErrorDescription(e.getMessage()); searchResponse.setApierrormessage(errorMessage); } } return searchResponse; }
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 {/*w w w . j a v a 2 s .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
private Result constructRecord(Element xmlRecord, Boolean parse) { Result result = new Result(); // Get Record Id String resultId = xmlRecord.getChildText("ResultId", xmlRecord.getNamespace()); result.setResultId(resultId);/* ww w .ja va 2 s. co m*/ // Get Header Info Element header = xmlRecord.getChild("Header", xmlRecord.getNamespace()); if (null != header) { String dbId = header.getChildText("DbId", header.getNamespace()); String dbLabel = header.getChildText("DbLabel", header.getNamespace()); String an = header.getChildText("An", header.getNamespace()); String pubType = header.getChildText("PubType", header.getNamespace()); String pubTypeId = header.getChildText("PubTypeId", header.getNamespace()); result.setDbId(dbId); result.setDbLabel(dbLabel); result.setPubTypeID(pubTypeId); result.setAn(an); result.setPubType(pubType); } // Get PLink String pLink = xmlRecord.getChildText("PLink", xmlRecord.getNamespace()); result.setpLink(pLink); // Get ImageInfo Element imageInfo = xmlRecord.getChild("ImageInfo", xmlRecord.getNamespace()); if (imageInfo != null) { List<Element> coverArts = imageInfo.getChildren(); for (int b = 0; b < coverArts.size(); b++) { Element coverArt = (Element) coverArts.get(b); if (null != coverArt) { BookJacket bookJacket = new BookJacket(); String size = coverArt.getChildText("Size", coverArt.getNamespace()); String target = coverArt.getChildText("Target", coverArt.getNamespace()); bookJacket.setSize(size); bookJacket.setTarget(target); result.getBookJacketList().add(bookJacket); } } } // Get Custom Links Element customLinks = xmlRecord.getChild("CustomLinks", xmlRecord.getNamespace()); if (customLinks != null) { List<Element> customLinksList = customLinks.getChildren(); for (int c = 0; c < customLinksList.size(); c++) { Element cl = (Element) customLinksList.get(c); if (null != cl) { String clurl = cl.getChildText("Url", cl.getNamespace()); String name = cl.getChildText("Name", cl.getNamespace()); String category = cl.getChildText("Category", cl.getNamespace()); String text = cl.getChildText("Text", cl.getNamespace()); String icon = cl.getChildText("Icon", cl.getNamespace()); String mouseOverText = cl.getChildText("MouseOverText", cl.getNamespace()); CustomLink customLink = new CustomLink(); customLink.setUrl(clurl); customLink.setName(name); customLink.setCategory(category); customLink.setText(text); customLink.setIcon(icon); customLink.setMouseOverText(mouseOverText); result.getCustomLinkList().add(customLink); } } } // Get Full Text Info Element fullText = xmlRecord.getChild("FullText", xmlRecord.getNamespace()); result.setHtmlAvailable("0"); result.setPdfAvailable("0"); if (null != fullText) { Element text = fullText.getChild("Text", fullText.getNamespace()); if (null != text) { // 0 - embedded full text is not available // 1 - full text is available // -1 - database not configured to provide full text to // guests String htmlAvailable = text.getChildText("Availability", fullText.getNamespace()); if (null != htmlAvailable && !htmlAvailable.isEmpty() && htmlAvailable.equals("1")) { result.setHtmlAvailable("1"); String htmlFullTextValue = text.getChildText("Value", fullText.getNamespace()); if (null != htmlFullTextValue && !htmlFullTextValue.isEmpty()) { if (parse) htmlFullTextValue = Jsoup.parse(htmlFullTextValue).text().toString(); // translate data to valid HTML tags htmlFullTextValue = TransDataToHTML.transDataToHTML(htmlFullTextValue); } result.setHtmlFullText(htmlFullTextValue); } result.setHtmlAvailable(htmlAvailable); } // determine whether or not there are full text links Element linkElement = fullText.getChild("Links", fullText.getNamespace()); if (null != linkElement) { List<Element> links = linkElement.getChildren(); if (null != links && 0 < links.size()) { ArrayList<Link> otherLinks = new ArrayList<Link>(); for (int j = 0; j < links.size(); j++) { Element link = (Element) links.get(j); String type = link.getChildText("Type", link.getNamespace()); String url = link.getChildText("Url", link.getNamespace()); if (null != type && type.equals("pdflink")) { result.setPdfAvailable("1"); result.setPdfLink(url); } else if (null != type && !type.isEmpty()) { Link otherFTLink = new Link(); otherFTLink.setType(type); otherFTLink.setUrl(url); otherLinks.add(otherFTLink); } } if (!otherLinks.isEmpty()) result.setOtherFullTextLinks(otherLinks); } } } // Process Items Element items = xmlRecord.getChild("Items", xmlRecord.getNamespace()); if (null != items) { List<Element> itemList = items.getChildren(); for (int j = 0; j < itemList.size(); j++) { Element itemElement = (Element) itemList.get(j); Item item = new Item(); String label = itemElement.getChildText("Label", itemElement.getNamespace()); String group = itemElement.getChildText("Group", itemElement.getNamespace()); String itemData = itemElement.getChildText("Data", itemElement.getNamespace()); if (parse) itemData = Jsoup.parse(itemData).text().toString(); // translate data to valid HTML tags itemData = TransDataToHTML.transDataToHTML(itemData); item.setLabel(label); item.setGroup(group); item.setData(itemData); result.getItemList().add(item); } } return result; }
From source file:com.eds.Response.XMLProcessor.java
License:Apache License
/** * Constructs a result list in response to an EDS API Search Request *///from w w w.j ava2 s . c o 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.eds.Response.XMLProcessor.java
License:Apache License
private Record constructRecord(Element xmlRecord, Boolean parse) { Record record = new Record(); // Get Record Id String resultId = xmlRecord.getChildText("ResultId", xmlRecord.getNamespace()); record.setResultId(resultId);/*w w w.ja va 2 s.c o m*/ // Get Header Info Element header = xmlRecord.getChild("Header", xmlRecord.getNamespace()); if (null != header) { String dbId = header.getChildText("DbId", header.getNamespace()); String dbLabel = header.getChildText("DbLabel", header.getNamespace()); String an = header.getChildText("An", header.getNamespace()); String pubType = header.getChildText("PubType", header.getNamespace()); String pubTypeId = header.getChildText("PubTypeId", header.getNamespace()); record.setDbId(dbId); record.setDbLabel(dbLabel); record.setPubTypeId(pubTypeId); record.setAn(an); record.setPubType(pubType); } // Get PLink String pLink = xmlRecord.getChildText("PLink", xmlRecord.getNamespace()); record.setpLink(pLink); // Get ImageInfo Element imageInfo = xmlRecord.getChild("ImageInfo", xmlRecord.getNamespace()); if (imageInfo != null) { List<Element> coverArts = imageInfo.getChildren(); for (int b = 0; b < coverArts.size(); b++) { Element coverArt = (Element) coverArts.get(b); if (null != coverArt) { BookJacket bookJacket = new BookJacket(); String size = coverArt.getChildText("Size", coverArt.getNamespace()); String target = coverArt.getChildText("Target", coverArt.getNamespace()); bookJacket.setSize(size); bookJacket.setTarget(target); record.getBookJacketList().add(bookJacket); } } } // Get Custom Links Element customLinks = xmlRecord.getChild("CustomLinks", xmlRecord.getNamespace()); if (customLinks != null) { List<Element> customLinksList = customLinks.getChildren(); for (int c = 0; c < customLinksList.size(); c++) { Element cl = (Element) customLinksList.get(c); if (null != cl) { String clurl = cl.getChildText("Url", cl.getNamespace()); String name = cl.getChildText("Name", cl.getNamespace()); String category = cl.getChildText("Category", cl.getNamespace()); String text = cl.getChildText("Text", cl.getNamespace()); String icon = cl.getChildText("Icon", cl.getNamespace()); String mouseOverText = cl.getChildText("MouseOverText", cl.getNamespace()); CustomLink customLink = new CustomLink(); customLink.setUrl(clurl); customLink.setName(name); customLink.setCategory(category); customLink.setText(text); customLink.setIcon(icon); customLink.setMouseOverText(mouseOverText); record.getCustomLinkList().add(customLink); } } } // Get Full Text Info Element fullText = xmlRecord.getChild("FullText", xmlRecord.getNamespace()); if (null != fullText) { Element htmlFullText = fullText.getChild("Text", fullText.getNamespace()); if (null != htmlFullText) { String availability = htmlFullText.getChildText("Availability", fullText.getNamespace()); record.setHtml(availability); } } // Process Items Element items = xmlRecord.getChild("Items", xmlRecord.getNamespace()); if (null != items) { List<Element> itemList = items.getChildren(); for (int j = 0; j < itemList.size(); j++) { Element itemElement = (Element) itemList.get(j); Item item = new Item(); String label = itemElement.getChildText("Label", itemElement.getNamespace()); String group = itemElement.getChildText("Group", itemElement.getNamespace()); String itemData = itemElement.getChildText("Data", itemElement.getNamespace()); if (parse) itemData = Jsoup.parse(itemData).text().toString(); // translate data to valid HTML tags itemData = TransDataToHTML.transDataToHTML(itemData); item.setLabel(label); item.setGroup(group); item.setData(itemData); record.getItemList().add(item); } } return record; }
From source file:com.forum.action.eder.PerfilACT.java
public String execute() throws Exception { int c0 = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0, c9 = 0, c10 = 0; Model modelo = ModelFactory.createDefaultModel(); FileManager.get().readModel(modelo,//ww w .ja v a2 s . c om ServletActionContext.getServletContext().getRealPath("/") + "/usuarios.rdf"); Resource perfil = modelo.getResource("http://comunipn.multiaportes.com/rdf/" + nick); NodeIterator amigos = modelo.listObjectsOfProperty( modelo.getResource("http://comunipn.multiaportes.com/rdf/" + solicitante), FOAF.knows); while (amigos.hasNext()) { RDFNode amigo = amigos.next(); Resource amigo1 = (Resource) amigo; // Resource es clase hija de RDFNode if (amigo1.getProperty(FOAF.nick).getObject().toString().equals(nick)) es_conocido = "1"; else es_conocido = "0"; } ServletContext context = ServletActionContext.getServletContext(); String url = context.getRealPath("/"); Document document = getDocument(url + "/database.xml"); Element root = document.getRootElement(); Element temas = root.getChild("respuestas"); List<Element> child = temas.getChildren(); for (Element tema : child) { for (Element respuesta : tema.getChildren()) { if (respuesta.getAttributeValue("usuario").equals(nick)) { switch (Integer.parseInt(respuesta.getAttributeValue("calificacion"))) { case 0: c0++; break; case 1: c1++; break; case 2: c2++; break; case 3: c3++; break; case 4: c4++; break; case 5: c5++; break; case 6: c6++; break; case 7: c7++; break; case 8: c8++; break; case 9: c9++; break; case 10: c10++; break; } } } } detalles = new Perfil(perfil.getProperty(FOAF.givenname).getObject().toString(), perfil.getProperty(FOAF.family_name).getObject().toString(), "Alumno", perfil.getProperty(FOAF.schoolHomepage).getObject().toString()); calificaciones = new EstadisticasIndiv(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10); return SUCCESS; }
From source file:com.forum.action.eder.TemaACT.java
private Hilo tema(int id, String url) { String megacadena = ""; Hilo h = new Hilo(); Document document = getDocument(url); Element root = document.getRootElement(); Element temas = root.getChild("temas"); List<Element> child = temas.getChildren(); for (Element e : child) { try {/*from w w w . j a v a2s .c om*/ if (e.getAttribute("id").getIntValue() == id) { h.setTitulo(e.getChildText("titulo")); h.setDetalles(e.getChildText("detalles")); List<Element> e2 = e.getChildren("tags"); for (int i = 0; i < e2.size(); i++) { megacadena += e2.get(i).getValue() + ","; } h.setEtiquetas(megacadena); break; } } catch (DataConversionException ex) { } } return h; }