Example usage for javax.xml.parsers SAXParserFactory setNamespaceAware

List of usage examples for javax.xml.parsers SAXParserFactory setNamespaceAware

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory setNamespaceAware.

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:importer.handler.post.stages.SAXSplitter.java

/**
 * Split a TEI-XML file into versions of XML
 * @param tei the TEI content containing versions
 * @return an analysis of the variant markup in a file
 * @throws ImportException if something went wrong
 *//*from  w  w  w .  ja  va2s.  c o m*/
public JSONArray scan(String tei) throws ImporterException {
    this.layers = new HashMap<String, Integer>();
    this.lineNo = 1;
    this.splits = new HashSet<String>();
    this.attributes = new HashMap<String, String>();
    this.siblings = new HashMap<String, String>();
    this.states = new Stack<Integer>();
    this.states.push(0);
    this.siblingCount = 0;
    this.path = new StringBuilder();
    // hard-wire config for now
    attributes.put("add", "n");
    attributes.put("rdg", "wit");
    attributes.put("lem", "wit");
    siblings.put("add", "del");
    siblings.put("del", "add");
    siblings.put("lem", "rdg");
    siblings.put("rdg", "lem");
    splits.add("add");
    splits.add("del");
    splits.add("sic");
    splits.add("corr");
    splits.add("abbrev");
    splits.add("expan");
    splits.add("rdg");
    splits.add("lem");
    splits.add("app");
    splits.add("mod");
    splits.add("choice");
    splits.add("subst");
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        parser = spf.newSAXParser();
        xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(this);
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        CharArrayReader car = new CharArrayReader(tei.toCharArray());
        xmlReader.parse(new InputSource(car));
        return layersToJson();
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:com.ibm.jaql.lang.expr.xml.XmlToJsonFn.java

@Override
public JsonValue eval(Context context) throws Exception {
    if (parser == null) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        parser = factory.newSAXParser().getXMLReader();
        handler = new XmlToJsonHandler2();
        parser.setContentHandler(handler);
    }//from   ww w .  j  a v a  2  s . co m

    JsonString s = (JsonString) exprs[0].eval(context);
    if (s == null) {
        return null;
    }
    parser.parse(new InputSource(new StringReader(s.toString())));
    return handler.result;
}

From source file:net.sbbi.upnp.messages.StateVariableMessage.java

/**
 * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a state variable response object containing the variable value
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *///w  ww. ja va2 s.  c om
public StateVariableResponse service() throws IOException, UPNPResponseException {
    StateVariableResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">");
    body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>");
    body.append("</u:QueryStateVariable>");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\"");
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignoring
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getStateVariableResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:com.esri.gpt.server.csw.client.CswCatalog.java

/**
 * Execute GetCapabilities using SAX objects. Send GetCapabilities request,
 * receive the response from a service, and parse the response to get URLs for
 * "GetRecords" and "GetRecordsById".// ww w  . j ava 2  s. co  m
 * 
 * @return the csw catalog capabilities
 * @throws SAXException the sAX exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParserConfigurationException the parser configuration exception
 * @return Csw Capabilities object
 */
private CswCatalogCapabilities executeGetCapabilitiesWithSAX()
        throws SAXException, IOException, ParserConfigurationException {
    CswCatalogCapabilities capabilities = new CswCatalogCapabilities();

    CswClient client = new CswClient();
    client.setConnectTimeout(this.getConnectionTimeoutMs());
    client.setReadTimeout(this.getResponseTimeoutMs());
    client.setBatchHttpClient(getBatchHttpClient());
    // Execute submission and parsing into response element
    InputStream responseStream = client.submitHttpRequest("GET", url, "");

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    CapabilitiesParse cParse = new CapabilitiesParse(capabilities);
    factory.newSAXParser().parse(new InputSource(responseStream), cParse);

    this.capabilities = capabilities;
    Utils.close(responseStream);
    return capabilities;
}

From source file:eu.scape_project.planning.xml.PlanMigrator.java

/**
 * Detect the version of the given XML representation of plans. If the
 * version of the XML representation is not up to date, necessary
 * transformations are applied.//from  ww w.java  2s  .co m
 * 
 * @param importData
 * @return null if the transformation fails, otherwise an up to date XML
 *         representation
 * @throws IOException
 *             if parsing the XML representation fails
 * @throws SAXException
 *             if parsing the XML representation fails
 */
public String getCurrentVersionData(final InputStream in, final String tempPath,
        final List<String> appliedTransformations) throws PlatoException {
    String originalFile = tempPath + "_original.xml";
    try {
        FileUtils.writeToFile(in, new FileOutputStream(originalFile));

        /** check for the version of the file **/

        // The version of the read xml file is unknown, so it is not possible to
        // validate it
        // moreover, in old plans the version attribute was on different
        // nodes(project, projects),
        // with a different name (fileVersion)
        // to be backwards compatible we create rules for all these attributes
        fileVersion = "xxx";
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(false);
        Digester d = new Digester(factory.newSAXParser());

        d.setValidating(false);
        // StrictErrorHandler errorHandler = new StrictErrorHandler();
        // d.setErrorHandler(errorHandler);
        d.push(this);
        // to read the version we have to support all versions:
        d.addSetProperties("*/projects", "version", "fileVersion");
        // manually migrated projects may have the file version in the node
        // projects/project
        d.addSetProperties("*/projects/project", "version", "fileVersion");
        // pre V1.3 version info was stored in the project node
        d.addSetProperties("*/project", "version", "fileVersion");
        // since V1.9 the root node is plans:
        d.addSetProperties("plans", "version", "fileVersion");

        InputStream inV = new FileInputStream(originalFile);
        d.parse(inV);
        inV.close();
        /** this could be more sophisticated, but for now this is enough **/
        String version = "1.0";
        if (fileVersion != null) {
            version = fileVersion;
        }

        String fileTo = originalFile;
        String fileFrom = originalFile;

        boolean success = true;
        if ("xxx".equals(version)) {
            fileFrom = fileTo;
            fileTo = fileFrom + "_V1.3.xml";
            /** this is an old export file, transform it to the 1.3 schema **/
            success = transformXmlData(fileFrom, fileTo, "data/xslt/Vxxx-to-V1.3.xsl");
            appliedTransformations.add("Vxxx-to-V1.3.xsl");
            version = "1.3";
        }
        if (success && "1.3".equals(version)) {
            fileFrom = fileTo;
            fileTo = fileFrom + "_V1.9.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V1.3-to-V1.9.xsl");
            appliedTransformations.add("V1.3-to-V1.9.xsl");
            version = "1.9";
        }
        // with release of Plato 2.0 and its schema ProjectExporter creates
        // documents with version 2.0
        if (success && "1.9".equals(version)) {
            version = "2.0";
        }
        if (success && "2.0".equals(version)) {
            // transform the document to version 2.1
            fileFrom = fileTo;
            fileTo = fileFrom + "_V2.1.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V2.0-to-V2.1.xsl");
            appliedTransformations.add("V2.0-to-V2.1.xsl");
            version = "2.1";
        }
        if (success && "2.1".equals(version)) {
            // transform the document to version 2.1.2
            fileFrom = fileTo;
            fileTo = fileFrom + "_V2.1.2.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V2.1-to-V2.1.2.xsl");
            appliedTransformations.add("V2.1-to-V2.1.2.xsl");
            version = "2.1.2";
        }
        if (success && "2.1.1".equals(version)) {
            // transform the document to version 2.1.2
            fileFrom = fileTo;
            fileTo = fileFrom + "_V2.1.2.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V2.1.1-to-V2.1.2.xsl");
            appliedTransformations.add("V2.1.1-to-V2.1.2.xsl");
            version = "2.1.2";
        }

        if (success && "2.1.2".equals(version)) {
            // transform the document to version 3.0.0
            fileFrom = fileTo;
            fileTo = fileFrom + "_V3.0.0.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V2.1.2-to-V3.0.0.xsl");
            appliedTransformations.add("V2.1.2-to-V3.0.0.xsl");
            version = "3.0.0";
        }
        if (success && "3.0.0".equals(version)) {
            // transform the document to version 3.0.1
            fileFrom = fileTo;
            fileTo = fileFrom + "_V3.0.1.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V3.0.0-to-V3.0.1.xsl");
            appliedTransformations.add("V3.0.0-to-V3.0.1.xsl");
            version = "3.0.1";
        }
        if (success && "3.0.1".equals(version)) {
            // transform the document to version 3.9.0
            fileFrom = fileTo;
            fileTo = fileFrom + "_V3.9.0.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V3.0.1-to-V3.9.0.xsl");
            appliedTransformations.add("V3.0.1-to-V3.9.0.xsl");
            version = "3.9.0";
        }
        if (success && "3.9.0".equals(version)) {
            // transform the document to version 3.9.9
            fileFrom = fileTo;
            fileTo = fileFrom + "_V3.9.9.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V3.9.0-to-V3.9.9.xsl");
            appliedTransformations.add("V3.9.0-to-V3.9.9.xsl");
            version = "3.9.9";
        }
        if (success && "3.9.9".equals(version)) {
            // transform the document to version 4.0.0
            fileFrom = fileTo;
            fileTo = fileFrom + "_V4.0.1.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V3.9.9-to-V4.0.1.xsl");
            appliedTransformations.add("V3.9.9-to-V4.0.1.xsl");
            version = "4.0.1";
        }
        if (success && "4.0.1".equals(version)) {
            // transform the document to version 4.0.0
            fileFrom = fileTo;
            fileTo = fileFrom + "_V4.0.2.xml";
            success = transformXmlData(fileFrom, fileTo, "data/xslt/V4.0.1-to-V4.0.2.xsl");
            appliedTransformations.add("V4.0.1-to-V4.0.2.xsl");
            version = "4.0.2";
        }

        if (success) {
            return fileTo;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new PlatoException("Failed to update plan to current version.", e);
    }
}

From source file:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java

protected SAXParserFactory createSAXParserFactory() throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    if (log.isDebugEnabled()) {
        log.debug("Instantiated SAX parser factory of type " + parserFactory.getClass().getName());
    }//  w w w  . ja  v a 2s . c  o  m

    parserFactory.setNamespaceAware(true);

    boolean validating = isValidating();
    parserFactory.setValidating(validating);
    parserFactory.setFeature("http://xml.org/sax/features/validation", validating);
    return parserFactory;
}

From source file:architecture.common.util.L10NUtils.java

private void loadProps(String resource, boolean breakOnError) throws IOException {

    HashSet<URL> hashset = new HashSet<URL>();
    if (log.isDebugEnabled()) {
        log.debug((new StringBuilder()).append("Searching ").append(resource).toString());
    }//from w  ww.  j av  a 2 s . c  o  m
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(resource);
    if (urls != null) {
        URL url;
        for (; urls.hasMoreElements(); hashset.add(url)) {
            url = urls.nextElement();
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Adding ").append(url).toString());
        }
    }

    for (URL url : hashset) {
        if (log.isDebugEnabled())
            log.debug((new StringBuilder()).append("Loading from ").append(url).toString());
        InputStream is = null;
        try {
            is = url.openStream();
            InputSource input = new InputSource(is);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XMLReader xmlreader = factory.newSAXParser().getXMLReader();
            I18nParsingHandler handler = new I18nParsingHandler();
            xmlreader.setContentHandler(handler);
            xmlreader.setDTDHandler(handler);
            xmlreader.setEntityResolver(handler);
            xmlreader.setErrorHandler(handler);
            xmlreader.parse(input);
            localizers.addAll(handler.localizers);
        } catch (IOException e) {
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Skipping ").append(url).toString());
            if (breakOnError)
                throw e;
        } catch (Exception e) {
            log.error(e);
        } finally {
            if (is != null)
                IOUtils.closeQuietly(is);
        }
    }

}

From source file:org.energyos.espi.common.service.impl.ImportServiceImpl.java

@Override
public void importData(InputStream stream, Long retailCustomerId)
        throws IOException, SAXException, ParserConfigurationException {

    // setup the parser
    JAXBContext context = marshaller.getJaxbContext();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XMLReader reader = factory.newSAXParser().getXMLReader();

    // EntryProcessor processor = new EntryProcessor(resourceLinker, new
    // ResourceConverter(), resourceService);
    ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService);
    reader.setContentHandler(atomContentHandler);

    // do the parse/import

    try {//from   w  w w  . j  a  va  2  s.  c  om
        reader.parse(new InputSource(stream));

    } catch (SAXException e) {
        System.out.printf(
                "\nImportServiceImpl -- importData: SAXException\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        throw new SAXException(e.getMessage(), e);

    } catch (Exception e) {
        System.out.printf("\nImportServiceImpl -- importData:\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        e.printStackTrace();

    }
    // context of the import used for linking things up
    // and establishing notifications
    //

    entries = atomContentHandler.getEntries();
    minUpdated = atomContentHandler.getMinUpdated();
    maxUpdated = atomContentHandler.getMaxUpdated();

    // cleanup/end processing
    // 1 - associate to usage points to the right retail customer
    // 2 - make sure authorization/subscriptions have the right URIs
    // 3 - place the imported usagePoints in to the subscriptions
    //
    List<UsagePoint> usagePointList = new ArrayList<UsagePoint>();

    // now perform any associations (to RetailCustomer) and stage the
    // Notifications (if any)

    RetailCustomer retailCustomer = null;

    if (retailCustomerId != null) {
        retailCustomer = retailCustomerService.findById(retailCustomerId);
    }

    Iterator<EntryType> its = entries.iterator();

    while (its.hasNext()) {
        EntryType entry = its.next();
        UsagePoint usagePoint = entry.getContent().getUsagePoint();
        if (usagePoint != null) {

            // see if we already have a retail customer association

            RetailCustomer tempRc = usagePoint.getRetailCustomer();
            if (tempRc != null) {
                // hook it to the retailCustomer
                if (!(tempRc.equals(retailCustomer))) {
                    // we have a conflict in association meaning to Retail
                    // Customers
                    // TODO: resolve how to handle the conflict mentioned
                    // above.
                    // TODO: Only works for a single customer and not
                    // multiple customers
                    retailCustomer = tempRc;
                }
            } else {
                // associate the usagePoint with the Retail Customer
                if (retailCustomer != null) {
                    usagePointService.associateByUUID(retailCustomer, usagePoint.getUUID());
                }
            }
            usagePointList.add(usagePoint);
        }
    }

    // now if we have a retail customer, check for any subscriptions that
    // need associated
    if (retailCustomer != null) {

        Subscription subscription = null;

        // find and iterate across all relevant authorizations
        //
        List<Authorization> authorizationList = authorizationService
                .findAllByRetailCustomerId(retailCustomer.getId());
        for (Authorization authorization : authorizationList) {

            try {
                subscription = subscriptionService.findByAuthorizationId(authorization.getId());
            } catch (Exception e) {
                // an Authorization w/o an associated subscription breaks
                // the propagation chain
                System.out.printf("**** End of Notification Propagation Chain\n");
            }
            if (subscription != null) {
                String resourceUri = authorization.getResourceURI();
                // this is the first time this authorization has been in
                // effect. We must set up the appropriate resource links
                if (resourceUri == null) {
                    ApplicationInformation applicationInformation = authorization.getApplicationInformation();
                    resourceUri = applicationInformation.getDataCustodianResourceEndpoint();
                    resourceUri = resourceUri + "/Batch/Subscription/" + subscription.getId();
                    authorization.setResourceURI(resourceUri);

                    resourceService.merge(authorization);
                }

                // make sure the UsagePoint(s) we just imported are linked
                // up
                // with
                // the Subscription

                for (UsagePoint usagePoint : usagePointList) {
                    boolean addNew = false;
                    for (UsagePoint up : subscription.getUsagePoints()) {
                        if (up.equals(usagePoint))
                            addNew = true;
                    }

                    if (addNew)
                        subscriptionService.addUsagePoint(subscription, usagePoint);

                }
            }
        }
    }
}

From source file:de.betterform.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *///from ww  w  .j av a  2s  .  co  m
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation",
                    schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:edu.psu.citeseerx.updates.external.metadata.DBLPMetadataUpdater.java

public void updateDBLP() {
    try {/*  w ww . ja  va 2s .  co m*/
        // Get the SAX factory.
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // Neither we want validation nor namespaces.
        factory.setNamespaceAware(false);
        factory.setValidating(true);

        SAXParser parser = factory.newSAXParser();
        parser.getXMLReader().setEntityResolver(new DBLPEntityResolver(DBLPDTDFile));

        /*xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", 
            false);*/

        parser.parse(DBLPDataFile, dblpHandler);
    } catch (ParserConfigurationException e) {
        logger.error("The underlaying parser doesn't support the " + "requested feature", e);
    } catch (SAXException e) {
        logger.error("Error", e);
    } catch (IOException e) {
        logger.error("A parsing error has occurred: " + DBLPDataFile, e);
    }

}