Example usage for org.jdom2 Element getNamespace

List of usage examples for org.jdom2 Element getNamespace

Introduction

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

Prototype

public Namespace getNamespace() 

Source Link

Document

Returns the element's Namespace .

Usage

From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationEcolumnModuleImpl.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.e.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.e.siard.metadata.xml.schema.name"),
                validationContext.getXmlNamespace());
        // Iterating over all <schema> elements
        for (Element siardSchemaElement : siardSchemaElements) {
            String schemaFolderName = siardSchemaElement
                    .getChild(properties.getProperty("module.e.siard.metadata.xml.schema.folder.name"),
                            validationContext.getXmlNamespace())
                    .getValue();// w w w  . j  a va2 s.  c  o m
            Element siardTablesElement = siardSchemaElement.getChild(
                    properties.getProperty("module.e.siard.metadata.xml.tables.name"),
                    validationContext.getXmlNamespace());
            List<Element> siardTableElements = siardTablesElement.getChildren(
                    properties.getProperty("module.e.siard.metadata.xml.table.name"),
                    validationContext.getXmlNamespace());
            // Iterating over all containing table elements
            for (Element siardTableElement : siardTableElements) {
                Element siardColumnsElement = siardTableElement.getChild(
                        properties.getProperty("module.e.siard.metadata.xml.columns.name"),
                        validationContext.getXmlNamespace());
                List<Element> siardColumnElements = siardColumnsElement.getChildren(
                        properties.getProperty("module.e.siard.metadata.xml.column.name"),
                        validationContext.getXmlNamespace());
                String tableName = siardTableElement
                        .getChild(properties.getProperty("module.e.siard.metadata.xml.table.folder.name"),
                                validationContext.getXmlNamespace())
                        .getValue();
                SiardTable siardTable = new SiardTable();
                siardTable.setMetadataXMLElements(siardColumnElements);
                siardTable.setTableName(tableName);
                String siardTableFolderName = siardTableElement
                        .getChild(properties.getProperty("module.e.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.e.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.e.siard.table.xsd.file.extension"));
                // Retrieve the according XML schema
                File tableSchema = validationContext.getSiardFiles().get(pathToTableSchema.toString());
                SAXBuilder builder = new SAXBuilder();
                Document tableSchemaDocument = builder.build(tableSchema);
                Element tableSchemaRootElement = tableSchemaDocument.getRootElement();
                Namespace namespace = tableSchemaRootElement.getNamespace();
                // Getting the tags from XML schema to be validated
                Element tableSchemaComplexType = tableSchemaRootElement
                        .getChild(properties.getProperty("module.e.siard.table.xsd.complexType"), namespace);
                Element tableSchemaComplexTypeSequence = tableSchemaComplexType
                        .getChild(properties.getProperty("module.e.siard.table.xsd.sequence"), namespace);
                List<Element> tableSchemaComplexTypeElements = tableSchemaComplexTypeSequence
                        .getChildren(properties.getProperty("module.e.siard.table.xsd.element"), namespace);
                siardTable.setTableXSDElements(tableSchemaComplexTypeElements);
                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.ValidationFrowModuleImpl.java

License:Open Source License

private boolean validateTableXSDFiles(ValidationContext validationContext) throws Exception {
    boolean validTableXSDFiles = true;
    StringBuilder namesOfInvalidTables = new StringBuilder();
    Properties properties = validationContext.getValidationProperties();
    List<SiardTable> siardTables = validationContext.getSiardTables();

    for (SiardTable siardTable : siardTables) {

        Element tableRootElement = siardTable.getTableRootElement();
        Element tableRowsElement = tableRootElement.getChild(
                properties.getProperty("module.f.siard.table.xml.rows.element.name"),
                validationContext.getXmlNamespace());
        Integer rowNumber = new Integer(tableRowsElement.getValue());
        Long extendedRowNumber = rowNumber.longValue();

        Element tableXSDRootElement = siardTable.getTableXSDRootElement();
        Element tableElement = tableXSDRootElement.getChild(
                properties.getProperty("module.f.siard.table.xsd.element"), tableXSDRootElement.getNamespace());

        Element tableComplexType = tableElement.getChild(
                properties.getProperty("module.f.siard.table.xsd.complexType"),
                tableXSDRootElement.getNamespace());

        Element tableSequence = tableComplexType.getChild(
                properties.getProperty("module.f.siard.table.xsd.sequence"),
                tableXSDRootElement.getNamespace());

        String maxOccurs = tableSequence
                .getChild(properties.getProperty("module.f.siard.table.xsd.element"),
                        tableXSDRootElement.getNamespace())
                .getAttributeValue(properties.getProperty("module.f.siard.table.xsd.attribute.maxOccurs.name"));
        String minOccurs = tableSequence
                .getChild(properties.getProperty("module.f.siard.table.xsd.element"),
                        tableXSDRootElement.getNamespace())
                .getAttributeValue(properties.getProperty("module.f.siard.table.xsd.attribute.minOccurs.name"));

        // Implicite max. bound: the maximal value of Long is used
        if (maxOccurs
                .equalsIgnoreCase(properties.getProperty("module.f.siard.table.xsd.attribute.unbounded"))) {
            if (extendedRowNumber >= 0 && extendedRowNumber <= Long.MAX_VALUE) {
            } else {
                validTableXSDFiles = false;
                namesOfInvalidTables.append((namesOfInvalidTables.length() > 0) ? ", " : "");
                namesOfInvalidTables.append(siardTable.getTableName()
                        + properties.getProperty("module.f.siard.table.xsd.file.extension"));
            }//w  w w .  jav a  2 s  .  co  m
        }

        // Explicite max. bound is used
        if (isLong(maxOccurs) && isLong(minOccurs)) {
            if (new Long(minOccurs) == extendedRowNumber && new Long(maxOccurs) == extendedRowNumber) {
            } else {
                if (new Long(minOccurs) - extendedRowNumber == 0
                        && new Long(maxOccurs) - extendedRowNumber == 0) {
                } else {
                    if (new Long(maxOccurs) > extendedRowNumber) {
                        validTableXSDFiles = false;
                        namesOfInvalidTables.append((namesOfInvalidTables.length() > 0) ? ", " : "");
                        namesOfInvalidTables.append(siardTable.getTableName()
                                + properties.getProperty("module.f.siard.table.xsd.file.extension") + " (+"
                                + (new Long(maxOccurs) - extendedRowNumber) + ") ");

                    } else {
                        validTableXSDFiles = false;
                        namesOfInvalidTables.append((namesOfInvalidTables.length() > 0) ? ", " : "");
                        namesOfInvalidTables.append(siardTable.getTableName()
                                + properties.getProperty("module.f.siard.table.xsd.file.extension") + " ("
                                + (new Long(maxOccurs) - extendedRowNumber) + ") ");
                    }
                }
            }
        }
    }

    this.setIncongruentTableXSDFiles(namesOfInvalidTables);
    return validTableXSDFiles;
}

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  ww  w  . j  ava 2 s.  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:com.bc.ceres.binio.binx.BinX.java

License:Open Source License

private CompoundType parseDocument(URI uri) throws IOException, BinXException {
    SAXBuilder builder = new SAXBuilder();
    Document document;/*from  w  w  w  .  java  2s .  com*/
    try {
        document = builder.build(uri.toURL());
    } catch (JDOMException e) {
        throw new BinXException(MessageFormat.format("Failed to read ''{0}''", uri), e);
    }
    Element binxElement = document.getRootElement();
    this.namespace = binxElement.getNamespace();
    parseParameters(binxElement);
    parseDefinitions(binxElement);
    return parseDataset(binxElement);
}

From source file:com.bc.ceres.nbmgen.NbmGenTool.java

License:Open Source License

@Override
public void process(CeresModuleProject project) throws JDOMException, IOException {

    System.out.println("Project [" + project.projectDir.getName() + "]:");

    File originalPomFile = getFile(project.projectDir, CeresModuleProject.ORIGINAL_POM_XML);
    File pomFile = getFile(project.projectDir, CeresModuleProject.POM_XML);
    File manifestBaseFile = getFile(project.projectDir, "src", "main", "nbm", "manifest.mf");

    Element projectElement = project.pomDocument.getRootElement();
    Namespace ns = projectElement.getNamespace();

    Element moduleElement = project.moduleDocument.getRootElement();
    String moduleName = moduleElement.getChildTextTrim("name");
    String moduleDescription = moduleElement.getChildTextNormalize("description");
    String modulePackaging = moduleElement.getChildTextTrim("packaging");
    String moduleNative = moduleElement.getChildTextTrim("native");
    String moduleActivator = moduleElement.getChildTextTrim("activator");
    String moduleChangelog = moduleElement.getChildTextTrim("changelog");
    String moduleFunding = moduleElement.getChildTextTrim("funding");
    String moduleVendor = moduleElement.getChildTextTrim("vendor");
    String moduleContactAddress = moduleElement.getChildTextTrim("contactAddress");
    String moduleCopyright = moduleElement.getChildTextTrim("copyright");
    String moduleLicenseUrl = moduleElement.getChildTextTrim("licenseUrl");
    // Not used anymore:
    //String moduleUrl = moduleElement.getChildTextTrim("url");
    //String moduleAboutUrl = moduleElement.getChildTextTrim("aboutUrl");

    if (moduleName != null) {
        Element nameElement = getOrAddElement(projectElement, "name", ns);
        nameElement.setText(moduleName);
    }/*from w ww  . j  a  v a2 s.co m*/
    if (moduleDescription != null) {
        int nameIndex = projectElement.indexOf(projectElement.getChild("name"));
        Element descriptionElement = getOrAddElement(projectElement, "description", nameIndex + 1, ns);
        descriptionElement.setText(moduleDescription);
    }
    Element descriptionElement = getOrAddElement(projectElement, "packaging", ns);
    descriptionElement.setText("nbm");

    Element urlElement = getOrAddElement(projectElement, "url", ns);
    urlElement.setText("https://sentinel.esa.int/web/sentinel/toolboxes");

    Element buildElement = getOrAddElement(projectElement, "build", ns);
    Element pluginsElement = getOrAddElement(buildElement, "plugins", ns);

    Map<String, String> nbmConfiguration = new LinkedHashMap<>();
    // moduleType is actually a constant which can be put it into the <pluginManagement-element of the parent
    nbmConfiguration.put("moduleType", "normal");
    // licenseName/File should also be constant
    nbmConfiguration.put("licenseName", "GPL 3");
    nbmConfiguration.put("licenseFile", "../LICENSE.html");

    nbmConfiguration.put("cluster", cluster);
    nbmConfiguration.put("defaultCluster", cluster);
    nbmConfiguration.put("publicPackages", "");
    nbmConfiguration.put("requiresRestart", "true");

    addPluginElement(pluginsElement, "org.codehaus.mojo", "nbm-maven-plugin", nbmConfiguration, ns);

    Map<String, String> jarConfiguration = new LinkedHashMap<>();
    jarConfiguration.put("useDefaultManifestFile", "true");

    addPluginElement(pluginsElement, "org.apache.maven.plugins", "maven-jar-plugin", jarConfiguration, ns);

    StringBuilder longDescription = new StringBuilder();

    longDescription.append(moduleDescription != null ? "<p>" + moduleDescription + "" : "")
            .append(descriptionEntry("Funding", moduleFunding)).append(descriptionEntry("Vendor", moduleVendor))
            .append(descriptionEntry("Contact address", moduleContactAddress))
            .append(descriptionEntry("Copyright", moduleCopyright))
            .append(descriptionEntry("Vendor", moduleVendor))
            .append(descriptionEntry("License", moduleLicenseUrl))
            .append(descriptionEntry("Changelog", moduleChangelog));

    Map<String, String> manifestContent = new LinkedHashMap<>();
    manifestContent.put("Manifest-Version", "1.0");
    manifestContent.put("AutoUpdate-Show-In-Client", "false");
    manifestContent.put("AutoUpdate-Essential-Module", "true");
    manifestContent.put("OpenIDE-Module-Java-Dependencies", "Java > 1.8");
    manifestContent.put("OpenIDE-Module-Display-Category", "SNAP");
    if (longDescription.length() > 0) {
        manifestContent.put("OpenIDE-Module-Long-Description", longDescription.toString());
    }
    if (moduleActivator != null) {
        warnModuleDetail("Activator may be reimplemented for NB: " + moduleActivator + " (--> "
                + "consider using @OnStart, @OnStop, @OnShowing, or a ModuleInstall)");
        manifestContent.put("OpenIDE-Module-Install", moduleActivator);
    }
    if (modulePackaging != null && !"jar".equals(modulePackaging)) {
        warnModuleDetail("Unsupported module packaging: " + modulePackaging + " (--> "
                + "provide a ModuleInstall that does the job on install/uninstall)");
    }
    if (moduleNative != null && "true".equals(moduleNative)) {
        warnModuleDetail("Module contains native code: no auto-conversion possible (--> "
                + "follow NB instructions see http://bits.netbeans.org/dev/javadoc/org-openide-modules/org/openide/modules/doc-files/api.html#how-layer");
    }

    if (!originalPomFile.exists()) {
        if (!dryRun) {
            Files.copy(project.pomFile.toPath(), originalPomFile.toPath());
        }
        infoModuleDetail("Copied " + project.pomFile + " to " + originalPomFile);
    }

    if (!dryRun) {
        writeXml(pomFile, project.pomDocument);
    }
    if (pomFile.equals(project.pomFile)) {
        infoModuleDetail("Updated " + pomFile);
    } else {
        infoModuleDetail("Converted " + project.pomFile + " to " + pomFile);
    }

    //noinspection ResultOfMethodCallIgnored
    if (!dryRun) {
        manifestBaseFile.getParentFile().mkdirs();
        writeManifest(manifestBaseFile, manifestContent);
    }
    infoModuleDetail("Written " + manifestBaseFile);
}

From source file:com.bc.ceres.site.util.ExclusionListBuilder.java

License:Open Source License

static void addPomToExclusionList(File exclusionList, URL pom) throws Exception {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(exclusionList, true))) {
        final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final Document w3cDoc = builder.parse(pom.openStream());
        final DOMBuilder domBuilder = new DOMBuilder();
        final org.jdom2.Document doc = domBuilder.build(w3cDoc);
        final Element root = doc.getRootElement();
        final Namespace namespace = root.getNamespace();
        final List<Element> modules = root.getChildren(MODULES_NODE, namespace);
        if (modules != null) {
            // hard-coded index 0 is ok because xml-schema allows only one <modules>-node
            final Element modulesNode = modules.get(0);
            final List<Element> modulesList = modulesNode.getChildren(MODULE_NAME, namespace);
            for (Element module : modulesList) {
                addModuleToExclusionList(exclusionList, writer, module.getText());
            }//from   w w  w  .java2s  . c o  m
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

protected Optional<Element> createElement(JspElementContext node, JSPElementNodeConverter context) {
    final Element element = new Element(newNameForElement(node));
    element.removeNamespaceDeclaration(element.getNamespace());
    element.setNamespace(newNamespaceForElement(node));
    return Optional.of(element);
}

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