List of usage examples for org.jdom2 Element getChild
public Element getChild(final String cname, final Namespace ns)
From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationFrowModuleImpl.java
License:Open Source License
private boolean prepareValidationData(ValidationContext validationContext) throws JDOMException, IOException, Exception { boolean successfullyCommitted = false; Properties properties = validationContext.getValidationProperties(); // Gets the tables to be validated List<SiardTable> siardTables = new ArrayList<SiardTable>(); Document document = validationContext.getMetadataXMLDocument(); Element rootElement = document.getRootElement(); String workingDirectory = validationContext.getConfigurationService().getPathToWorkDir(); String siardSchemasElementsName = properties.getProperty("module.f.siard.metadata.xml.schemas.name"); // Gets the list of <schemas> elements from metadata.xml List<Element> siardSchemasElements = rootElement.getChildren(siardSchemasElementsName, validationContext.getXmlNamespace()); for (Element siardSchemasElement : siardSchemasElements) { // Gets the list of <schema> elements from metadata.xml List<Element> siardSchemaElements = siardSchemasElement.getChildren( properties.getProperty("module.f.siard.metadata.xml.schema.name"), validationContext.getXmlNamespace()); // Iterating over all <schema> elements for (Element siardSchemaElement : siardSchemaElements) { String schemaFolderName = siardSchemaElement .getChild(properties.getProperty("module.f.siard.metadata.xml.schema.folder.name"), validationContext.getXmlNamespace()) .getValue();/*from w ww .j ava 2s .c o m*/ Element siardTablesElement = siardSchemaElement.getChild( properties.getProperty("module.f.siard.metadata.xml.tables.name"), validationContext.getXmlNamespace()); List<Element> siardTableElements = siardTablesElement.getChildren( properties.getProperty("module.f.siard.metadata.xml.table.name"), validationContext.getXmlNamespace()); // Iterating over all containing table elements for (Element siardTableElement : siardTableElements) { Element siardColumnsElement = siardTableElement.getChild( properties.getProperty("module.f.siard.metadata.xml.columns.name"), validationContext.getXmlNamespace()); List<Element> siardColumnElements = siardColumnsElement.getChildren( properties.getProperty("module.f.siard.metadata.xml.column.name"), validationContext.getXmlNamespace()); String tableName = siardTableElement .getChild(properties.getProperty("module.f.siard.metadata.xml.table.folder.name"), validationContext.getXmlNamespace()) .getValue(); SiardTable siardTable = new SiardTable(); // Add Table Root Element siardTable.setTableRootElement(siardTableElement); siardTable.setMetadataXMLElements(siardColumnElements); siardTable.setTableName(tableName); String siardTableFolderName = siardTableElement .getChild(properties.getProperty("module.f.siard.metadata.xml.table.folder.name"), validationContext.getXmlNamespace()) .getValue(); StringBuilder pathToTableSchema = new StringBuilder(); // Preparing access to the according XML schema file pathToTableSchema.append(workingDirectory); pathToTableSchema.append(File.separator); pathToTableSchema.append(properties.getProperty("module.f.siard.path.to.content")); pathToTableSchema.append(File.separator); pathToTableSchema.append(schemaFolderName.replaceAll(" ", "")); pathToTableSchema.append(File.separator); pathToTableSchema.append(siardTableFolderName.replaceAll(" ", "")); pathToTableSchema.append(File.separator); pathToTableSchema.append(siardTableFolderName.replaceAll(" ", "")); pathToTableSchema.append(properties.getProperty("module.f.siard.table.xsd.file.extension")); // Retrieve the according XML schema File tableSchema = validationContext.getSiardFiles().get(pathToTableSchema.toString()); // --> Hier StringBuilder pathToTableXML = new StringBuilder(); pathToTableXML.append(workingDirectory); pathToTableXML.append(File.separator); pathToTableXML.append(properties.getProperty("module.f.siard.path.to.content")); pathToTableXML.append(File.separator); pathToTableXML.append(schemaFolderName.replaceAll(" ", "")); pathToTableXML.append(File.separator); pathToTableXML.append(siardTableFolderName.replaceAll(" ", "")); pathToTableXML.append(File.separator); pathToTableXML.append(siardTableFolderName.replaceAll(" ", "")); pathToTableXML.append(properties.getProperty("module.f.siard.table.xml.file.extension")); File tableXML = validationContext.getSiardFiles().get(pathToTableXML.toString()); SAXBuilder schemaBuilder = new SAXBuilder(); Document tableSchemaDocument = schemaBuilder.build(tableSchema); Element tableSchemaRootElement = tableSchemaDocument.getRootElement(); // Getting the tags from XML schema to be validated siardTable.setTableXSDRootElement(tableSchemaRootElement); SAXBuilder xmlBuilder = new SAXBuilder(); Document tableXMLDocument = xmlBuilder.build(tableXML); Element tableXMLRootElement = tableXMLDocument.getRootElement(); Namespace xMLNamespace = tableXMLRootElement.getNamespace(); List<Element> tableXMLElements = tableXMLRootElement.getChildren( properties.getProperty("module.f.siard.table.xml.row.element.name"), xMLNamespace); siardTable.setTableXMLElements(tableXMLElements); siardTables.add(siardTable); // Writing back the List off all SIARD tables to the // validation context validationContext.setSiardTables(siardTables); } } } if (validationContext.getSiardTables().size() > 0) { this.setValidationContext(validationContext); successfullyCommitted = true; } else { this.setValidationContext(null); successfullyCommitted = false; throw new Exception(); } return successfullyCommitted; }
From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationGtableModuleImpl.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/*from w ww. j a va 2 s. co m*/ public boolean validate(File siardDatei) throws ValidationGtableException { boolean valid = true; try { /* * Extract the metadata.xml from the temporare work folder and build * a jdom document */ String pathToWorkDir = getConfigurationService().getPathToWorkDir(); /* * Nicht vergessen in * "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property * name="configurationService" ref="configurationService" /> */ File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header") .append(File.separator).append("metadata.xml").toString()); InputStream fin = new FileInputStream(metadataXml); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(fin); fin.close(); // declare ArrayLists List listSchemas = new ArrayList(); List listTables = new ArrayList(); List listColumns = new ArrayList(); /* * read the document and for each schema and table entry verify * existence in temporary extracted structure */ Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd"); // select schema elements and loop List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns); for (Element schema : schemas) { String schemaName = schema.getChild("name", ns).getText(); String lsSch = (new StringBuilder().append(schemaName).toString()); // select table elements and loop List<Element> tables = schema.getChild("tables", ns).getChildren("table", ns); for (Element table : tables) { String tableName = table.getChild("name", ns).getText(); // Concatenate schema and table String lsTab = (new StringBuilder().append(schemaName).append(" / ").append(tableName) .toString()); // select column elements and loop List<Element> columns = table.getChild("columns", ns).getChildren("column", ns); for (Element column : columns) { String columnName = column.getChild("name", ns).getText(); // Concatenate schema, table and column String lsCol = (new StringBuilder().append(schemaName).append(" / ").append(tableName) .append(" / ").append(columnName).toString()); listColumns.add(lsCol); // concatenating Strings } listTables.add(lsTab); // concatenating Strings (table // names) } listSchemas.add(lsSch); // concatenating Strings (schema // names) } HashSet hashSchemas = new HashSet(); // check for duplicate schemas for (Object value : listSchemas) if (!hashSchemas.add(value)) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G) + getTextResourceService().getText(MESSAGE_DASHES) + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_SCHEMA, value)); } HashSet hashTables = new HashSet(); // check for duplicate tables for (Object value : listTables) if (!hashTables.add(value)) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G) + getTextResourceService().getText(MESSAGE_DASHES) + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_TABLE, value)); } HashSet hashColumns = new HashSet(); // check for duplicate columns for (Object value : listColumns) if (!hashColumns.add(value)) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G) + getTextResourceService().getText(MESSAGE_DASHES) + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_COLUMN, value)); } } catch (java.io.IOException ioe) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G) + getTextResourceService().getText(MESSAGE_DASHES) + "IOException " + ioe.getMessage()); } catch (JDOMException e) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G) + getTextResourceService().getText(MESSAGE_DASHES) + "JDOMException " + e.getMessage()); return valid; } return valid; }
From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationHcontentModuleImpl.java
License:Open Source License
@Override public boolean validate(File siardDatei) throws ValidationHcontentException { boolean valid = true; try {//from w w w .ja v a2s. c o m /* * Extract the metadata.xml from the temporary work folder and build * a jdom document */ String pathToWorkDir = getConfigurationService().getPathToWorkDir(); File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header") .append(File.separator).append("metadata.xml").toString()); InputStream fin = new FileInputStream(metadataXml); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(fin); fin.close(); /* * read the document and for each schema and table entry verify * existence in temporary extracted structure */ Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd"); // select schema elements and loop List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns); for (Element schema : schemas) { Element schemaFolder = schema.getChild("folder", ns); File schemaPath = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("content") .append(File.separator).append(schemaFolder.getText()).toString()); if (schemaPath.isDirectory()) { Element[] tables = schema.getChild("tables", ns).getChildren("table", ns) .toArray(new Element[0]); for (Element table : tables) { Element tableFolder = table.getChild("folder", ns); File tablePath = new File(new StringBuilder(schemaPath.getAbsolutePath()) .append(File.separator).append(tableFolder.getText()).toString()); if (tablePath.isDirectory()) { File tableXml = new File(new StringBuilder(tablePath.getAbsolutePath()) .append(File.separator).append(tableFolder.getText() + ".xml").toString()); File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath()) .append(File.separator).append(tableFolder.getText() + ".xsd").toString()); if (verifyRowCount(tableXml, tableXsd)) { valid = validate(tableXml, tableXsd) && valid; } } } } } } catch (java.io.IOException ioe) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_H) + getTextResourceService().getText(MESSAGE_DASHES) + "IOException " + ioe.getMessage()); } catch (JDOMException e) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_H) + getTextResourceService().getText(MESSAGE_DASHES) + "JDOMException " + e.getMessage()); } catch (SAXException e) { valid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_H) + getTextResourceService().getText(MESSAGE_DASHES) + "SAXException " + e.getMessage()); } return valid; }
From source file:com.bc.ceres.binio.binx.BinX.java
License:Open Source License
private Element getChild(Element element, String name, boolean require) throws BinXException { final Element child = element.getChild(name, namespace); if (require && child == null) { throw new BinXException( MessageFormat.format("Element ''{0}}': child ''{1}'' not found.", element.getName(), name)); }//from www. ja v a 2 s .com return child; }
From source file:com.bc.ceres.nbmgen.NbmGenTool.java
License:Open Source License
private static Element getOrAddElement(Element parent, String name, int index, Namespace ns) { Element child = parent.getChild(name, ns); if (child == null) { child = new Element(name, ns); if (index >= 0) { parent.addContent(index, child); } else {// w w w . j ava 2 s .c o m parent.addContent(child); } } return child; }
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 . ja va 2 s . com * * @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.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 ww . j a v a 2 s .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 RetrieveResponse ProcessRetrieveResponse(ServiceResponse serviceResponse) { RetrieveResponse retrieveResponse = new RetrieveResponse(); BufferedReader reader = serviceResponse.getReader(); if (!serviceResponse.getErrorStream().equals("")) { ApiErrorMessage errorMessage = ProcessError(serviceResponse.getErrorNumber(), serviceResponse.getErrorStream()); retrieveResponse.setApiErrorMessage(errorMessage); } else {/*from w ww . j av a 2 s. c om*/ String RecordXML = ""; try { String line = ""; while ((line = reader.readLine()) != null) { RecordXML += line; } } catch (IOException e1) { ApiErrorMessage errorMessage = new ApiErrorMessage(); errorMessage.setErrorDescription("Error processing retrieve response"); errorMessage.setDetailedErrorDescription(e1.getMessage()); retrieveResponse.setApiErrorMessage(errorMessage); return retrieveResponse; } try { StringReader stringReader = new StringReader(RecordXML); InputSource inputSource = new InputSource(stringReader); Document doc = (new SAXBuilder()).build(inputSource); // root element (level 1) Element retrieveResponseMessage = doc.getRootElement(); // level 2 elements Element xmlRecord = retrieveResponseMessage.getChild("Record", retrieveResponseMessage.getNamespace()); Result result = this.constructRecord(xmlRecord, true); retrieveResponse.setRecord(result); } catch (Exception e) { ApiErrorMessage errorMessage = new ApiErrorMessage(); errorMessage.setErrorDescription("Error processing retrieve response"); errorMessage.setDetailedErrorDescription(e.getMessage()); retrieveResponse.setApiErrorMessage(errorMessage); } } return retrieveResponse; }
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 {/* ww w .j av 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
private Result constructRecord(Element xmlRecord, Boolean parse) { Result result = new Result(); // Get Record Id String resultId = xmlRecord.getChildText("ResultId", xmlRecord.getNamespace()); result.setResultId(resultId);/*from ww 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()); 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; }