Example usage for javax.xml.xpath XPathConstants NODESET

List of usage examples for javax.xml.xpath XPathConstants NODESET

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODESET.

Prototype

QName NODESET

To view the source code for javax.xml.xpath XPathConstants NODESET.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfParser.java

/**
 * Queries for a list nodes matching the xpath expression.
 *
 * @param root/*from  w w  w  .jav  a  2  s . co  m*/
 * @param xpathExpr
 * @return
 */
private NodeList nodes(Node root, String xpathExpr) {
    try {
        return (NodeList) xpath().evaluate(xpathExpr, root, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testRecordLimit() throws Exception {

    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);/*from   w w  w  .j  a  v a  2s  . c om*/
    assertNotNull(entityContainerNode);

    Node entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(
            String.valueOf(Integer.MAX_VALUE));

    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    int inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    String recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(6 + "");

    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(null);

    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode("not an int");

    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(2 + "");

    Document attributeParametersDocument = entityResolutionMessageHandler.getAttributeParametersDocument();
    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode,
            attributeParametersDocument.getDocumentElement(), entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(6, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("true", recordLimitExceeded);

    // LOG.info(new XmlConverter().toString(resultDocument));
    NodeList statNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality",
            resultDocument, XPathConstants.NODESET);
    assertEquals(6, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics/merge-result-ext:AttributeXPath",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics/merge-result-ext:StringDistanceMeanInRecord",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics/merge-result-ext:StringDistanceStandardDeviationInRecord",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
}

From source file:aurelienribon.gdxsetupui.ProjectUpdate.java

private void writeGwtDefinition(File gwtDefitionFile, List<GwtModule> modules) {
    try {/* w  w  w  .j  a v  a  2 s .co  m*/
        Document doc = XmlUtils.createParser().parse(gwtDefitionFile);
        Node root = (Node) XmlUtils.xpath("module", doc, XPathConstants.NODE);
        NodeList nodes = (NodeList) XmlUtils.xpath("module/inherits", doc, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            root.removeChild(nodes.item(i));
        }

        for (GwtModule module : modules) {
            Element elem = doc.createElement("inherits");
            root.appendChild(elem);

            elem.setAttribute("name", module.name);
        }

        XmlUtils.clean(doc);
        String str = XmlUtils.transform(doc);
        FileUtils.writeStringToFile(gwtDefitionFile, str);

    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (TransformerException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.ServiceProviderXmlTests.java

@Test
public void serviceProviderHasAtMostOnePublisher() throws XPathExpressionException {
    //Get the listed ServiceProvider elements
    NodeList providerChildren = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_v2:ServiceProvider/*", doc,
            XPathConstants.NODESET);
    int numPublishers = 0;
    for (int i = 0; i < providerChildren.getLength(); i++) {
        Node child = providerChildren.item(i);
        if (child.getLocalName() != null && child.getNamespaceURI().equals(OSLCConstants.DC)
                && child.getLocalName().equals("publisher")) {
            numPublishers++;//w w  w.j a v a2 s .c  o  m
        }
    }
    assert (numPublishers <= 1);
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java

@Test
public void changeRequestHasAtMostOneCreatedDate() throws XPathExpressionException {
    NodeList createdDates = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest/dc:created",
            doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), createdDates.getLength() <= 1);
    //If there is a created date, verify the format.
    if (createdDates.getLength() > 0) {
        try {/*from  ww w  . j a  v a 2  s .c  o m*/
            DatatypeConverter.parseDateTime(createdDates.item(0).getTextContent());
        } catch (Exception e) {
            fail("Created date not in valid XSD format");
        }
    }
}

From source file:com.amalto.core.query.DataRecordCreationTest.java

public void __testDateTypeInKey() throws Exception {
    MetadataRepository repository = new MetadataRepository();
    repository.load(DataRecordCreationTest.class.getResourceAsStream("metadata16.xsd"));

    Storage storage = new HibernateStorage("H2-Default"); //$NON-NLS-1$
    storage.init(ServerContext.INSTANCE.get().getDefinition("H2-Default", "MDM")); //$NON-NLS-1$//$NON-NLS-2$
    storage.prepare(repository, true);//from  w w w .  j  a  v  a2s  .  c om
    DataRecordReader<String> factory = new XmlStringDataRecordReader();

    List<DataRecord> records = new LinkedList<DataRecord>();
    records.add(factory.read(repository, repository.getComplexType("DateInKey"),
            "<DateInKey><id>22</id><name>22</name><date1>2014-04-17</date1></DateInKey>"));
    records.add(factory.read(repository, repository.getComplexType("DateTimeInKey"),
            "<DateTimeInKey><code>22</code><db1>2014-04-17T12:00:00</db1><aaa>aaa</aaa></DateTimeInKey>"));
    storage.begin();
    storage.update(records);
    storage.commit();

    // Query saved data
    storage.begin();
    ComplexTypeMetadata dateInKey = repository.getComplexType("DateInKey"); //$NON-NLS-1$
    UserQueryBuilder qb = from(dateInKey);
    qb.start(0);
    qb.limit(1);
    StorageResults results = storage.fetch(qb.getSelect());
    assertEquals(1, results.getCount());
    DataRecord result = results.iterator().next();
    assertEquals("2014-04-17",
            StorageMetadataUtils.toString(result.get("date1"), result.getType().getField("date1")));

    DataRecordWriter writer = new ItemPKCriteriaResultsWriter(dateInKey.getName(), dateInKey);
    ResettableStringWriter stringWriter = new ResettableStringWriter();
    try {
        writer.write(result, stringWriter);
    } catch (IOException e) {
        throw new XmlServerException(e);
    }
    String recordStringValue = stringWriter.toString();
    XPath xpath = XPathFactory.newInstance().newXPath();
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Element r = documentBuilder.parse(new InputSource(new StringReader(recordStringValue)))
            .getDocumentElement();
    NodeList idsList = (NodeList) xpath.evaluate("./ids/i", r, XPathConstants.NODESET); //$NON-NLS-1$
    List<String> keyStrValues = new ArrayList<String>();
    for (int j = 0; j < idsList.getLength(); j++) {
        keyStrValues.add(
                idsList.item(j).getFirstChild() == null ? "" : idsList.item(j).getFirstChild().getNodeValue()); //$NON-NLS-1$
    }
    assertTrue(keyStrValues.contains("2014-04-17"));
    assertTrue(keyStrValues.contains("22"));
    stringWriter.reset();

    dateInKey = repository.getComplexType("DateTimeInKey"); //$NON-NLS-1$
    qb = from(dateInKey);
    qb.start(0);
    qb.limit(1);
    results = storage.fetch(qb.getSelect());
    assertEquals(1, results.getCount());
    result = results.iterator().next();
    assertEquals("2014-04-17T12:00:00",
            StorageMetadataUtils.toString(result.get("db1"), result.getType().getField("db1")));
    writer = new ItemPKCriteriaResultsWriter(dateInKey.getName(), dateInKey);
    try {
        writer.write(result, stringWriter);
    } catch (IOException e) {
        throw new XmlServerException(e);
    }
    recordStringValue = stringWriter.toString();
    r = documentBuilder.parse(new InputSource(new StringReader(recordStringValue))).getDocumentElement();
    idsList = (NodeList) xpath.evaluate("./ids/i", r, XPathConstants.NODESET); //$NON-NLS-1$
    keyStrValues.clear();
    for (int j = 0; j < idsList.getLength(); j++) {
        keyStrValues.add(
                idsList.item(j).getFirstChild() == null ? "" : idsList.item(j).getFirstChild().getNodeValue()); //$NON-NLS-1$
    }
    assertTrue(keyStrValues.contains("2014-04-17T12:00:00"));
    assertTrue(keyStrValues.contains("22"));
    stringWriter.reset();
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderXPath.java

/**
 * Read in next file and store the nodes which satisfy the given XPath expression in the queue
 * for further process.//  www  .  ja v  a 2 s  . c om
 */
private void processNextFile() {
    if (fileIterator.hasNext()) {
        currentFileResource = fileIterator.next();
        File currentFile = currentFileResource.getFile();

        FileInputStream inputStream = null;
        NodeList nodeList = null;
        try {
            inputStream = new FileInputStream(currentFile);
            InputSource inputSource = new InputSource(inputStream);
            nodeList = (NodeList) compiledRootXPath.evaluate(inputSource, XPathConstants.NODESET);
        } catch (FileNotFoundException e) {
            // Should not happen
            new RuntimeException(e);
        } catch (XPathExpressionException e) {
            new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }

        // Add nodes to the queue
        if (nodeList != null) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                nodes.add(nodeList.item(i));
            }
        }
    }
}

From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java

/**
 * Returns the query result as a <code>NodeList</code> or <code>null</code> if
 * the xpath expression doesn't yield a result set.
 * //from  w  w  w.  j  a  v a 2 s . c o  m
 * @param node
 *          the context node
 * @param xpathExpression
 *          the xpath expression
 * @param processor
 *          the xpath processor
 * @return the selected node
 */
public static NodeList selectList(Node node, String xpathExpression, XPath processor) {
    if (node == null || processor == null) {
        return null;
    }
    try {
        NodeList result = (NodeList) processor.evaluate(xpathExpression, node, XPathConstants.NODESET);

        // If we are running in test mode, we may neglect namespaces
        if (result == null || result.getLength() == 0) {
            NamespaceContext ctx = processor.getNamespaceContext();
            if (ctx instanceof XPathNamespaceContext && ((XPathNamespaceContext) ctx).isTest()) {
                if (xpathExpression.matches("(.*)[a-zA-Z0-9]+\\:[a-zA-Z0-9]+(.*)")) {
                    String xpNs = xpathExpression.replaceAll("[a-zA-Z0-9]+\\:", "");
                    result = (NodeList) processor.evaluate(xpNs, node, XPathConstants.NODESET);
                }
            }
        }
        return result;

    } catch (XPathExpressionException e) {
        logger.warn("Error when selecting '{}' from {}", new Object[] { xpathExpression, node, e });
        return null;
    }
}

From source file:InlineSchemaValidator.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();// w  w w.java 2 s.  com
        System.exit(1);
    }

    // variables
    Vector schemas = null;
    Vector instances = null;
    HashMap prefixMappings = null;
    HashMap uriMappings = null;
    String docURI = argv[argv.length - 1];
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    int repetition = DEFAULT_REPETITION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;

    // process arguments
    for (int i = 0; i < argv.length - 1; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: xpath expressions for schemas
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: xpath expressions for instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-nm")) {
                String prefix;
                String uri;
                while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-")
                        && !(uri = argv[i + 2]).startsWith("-")) {
                    if (prefixMappings == null) {
                        prefixMappings = new HashMap();
                        uriMappings = new HashMap();
                    }
                    prefixMappings.put(prefix, uri);
                    HashSet prefixes = (HashSet) uriMappings.get(uri);
                    if (prefixes == null) {
                        prefixes = new HashSet();
                        uriMappings.put(uri, prefixes);
                    }
                    prefixes.add(prefix);
                    i += 2;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("m")) {
                memoryUsage = option.equals("m");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    try {
        // Create new instance of inline schema validator.
        InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings);

        // Parse document containing schemas and validation roots
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(inlineSchemaValidator);
        Document doc = db.parse(docURI);

        // Create XPath factory for selecting schema and validation roots
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        xpath.setNamespaceContext(inlineSchemaValidator);

        // Select schema roots from the DOM
        NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0];
        for (int i = 0; i < schemaNodes.length; ++i) {
            XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i));
            schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET);
        }

        // Select validation roots from the DOM
        NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0];
        for (int i = 0; i < instanceNodes.length; ++i) {
            XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i));
            instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET);
        }

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(inlineSchemaValidator);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        {
            DOMSource[] sources;
            int size = 0;
            for (int i = 0; i < schemaNodes.length; ++i) {
                size += schemaNodes[i].getLength();
            }
            sources = new DOMSource[size];
            if (size == 0) {
                schema = factory.newSchema();
            } else {
                int count = 0;
                for (int i = 0; i < schemaNodes.length; ++i) {
                    NodeList nodeList = schemaNodes[i];
                    int nodeListLength = nodeList.getLength();
                    for (int j = 0; j < nodeListLength; ++j) {
                        sources[count++] = new DOMSource(nodeList.item(j));
                    }
                }
                schema = factory.newSchema(sources);
            }
        }

        // Setup validator and input source.
        Validator validator = schema.newValidator();
        validator.setErrorHandler(inlineSchemaValidator);

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents
        for (int i = 0; i < instanceNodes.length; ++i) {
            NodeList nodeList = instanceNodes[i];
            int nodeListLength = nodeList.getLength();
            for (int j = 0; j < nodeListLength; ++j) {
                DOMSource source = new DOMSource(nodeList.item(j));
                source.setSystemId(docURI);
                inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage);
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.FetchResourceTests.java

@Test
public void getValidResourceUsingCOMPACT()
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    String body = getValidResourceUsingContentType(OSLCConstants.CT_COMPACT);

    Document doc = OSLCUtils.createXMLDocFromResponseBody(body);

    Node compactNode = (Node) OSLCUtils.getXPath().evaluate("/*/oslc_v2:Compact", doc, XPathConstants.NODE);
    assertNotNull(compactNode);//  w  ww .java2s  . c  o m

    // Everything is optional in the oslc:Compact representation.

    NodeList nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./dc:title", compactNode,
            XPathConstants.NODESET);
    int numNodes = nodeList.getLength();
    assertTrue("Expected number of dcterms:titles to be <=1 but was: " + numNodes, numNodes <= 1);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:shortTitle", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:shortTitles to be <=1 but was: " + numNodes, numNodes <= 1);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:icon", compactNode, XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:icon to be <=1 but was: " + numNodes, numNodes <= 1);

    String iconUrl = null;
    if (numNodes == 1) {
        Node rdfAbout = nodeList.item(0).getAttributes().getNamedItemNS(OSLCConstants.RDF, "resource");
        assertNotNull("oslc:icon in oslc:Compact missing rdf:about attribute", rdfAbout);
        iconUrl = rdfAbout.getTextContent();

        HttpResponse response = OSLCUtils.getResponseFromUrl(iconUrl, iconUrl, creds, "*/*", headers);
        int statusCode = response.getStatusLine().getStatusCode();
        EntityUtils.consume(response.getEntity());
        assertTrue(
                "Fetching icon from " + iconUrl + " did not respond with expected code, received " + statusCode,
                200 <= statusCode && statusCode < 400);
    }

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:smallPreview", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:smallPreview is 0 or 1 but was: " + numNodes, numNodes <= 1);
    if (numNodes == 1)
        validateCompactPreview(nodeList);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:largePreview", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:largePreview is 0 or 1 but was: " + numNodes, numNodes <= 1);
    if (numNodes == 1)
        validateCompactPreview(nodeList);
}