Example usage for javax.xml.parsers SAXParserFactory newInstance

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

Introduction

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

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:com.aurel.track.exchange.docx.importer.HTMLParser.java

private void parse(String fileName, Locale locale) {
    //get a factory
    localizedHeading = "berschrift";//LocalizeUtil.getLocalizedTextFromApplicationResources(HEADING_KEY, locale);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//w ww  . ja va 2 s  .  co m
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();
        //spf.setValidating(true);
        XMLReader xmlReader = sp.getXMLReader();
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        xmlReader.setContentHandler(this);
        //parse the file and also register this class for call backs
        //InputSource is=new InputSource(new StringReader(xml));
        xmlReader.parse(convertToFileURL(fileName));
    } catch (SAXException se) {
        LOGGER.error("Parsing the file " + fileName + " failed with " + se.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(se));
    } catch (ParserConfigurationException pce) {
        LOGGER.error("Parsing the file " + fileName + " failed with " + pce.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.error(ExceptionUtils.getStackTrace(pce));
        }
    } catch (IOException ie) {
        LOGGER.error("Reading the file " + fileName + " failed with " + ie.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }

}

From source file:Validate.java

void parse(String dir, String filename)
        throws FileNotFoundException, IOException, ParserConfigurationException, SAXException {
    try {//from w  ww. j  a v  a2  s  .  c o m
        File f = new File(dir, filename);
        StringBuffer errorBuff = new StringBuffer();
        InputSource input = new InputSource(new FileInputStream(f));
        // Set systemID so parser can find the dtd with a relative URL in the source document.
        input.setSystemId(f.toString());
        SAXParserFactory spfact = SAXParserFactory.newInstance();

        spfact.setValidating(true);
        spfact.setNamespaceAware(true);

        SAXParser parser = spfact.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        //Instantiate inner-class error and lexical handler.
        Handler handler = new Handler(filename, errorBuff);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
        parser.parse(input, handler);

        if (handler.containsDTD && !handler.errorOrWarning) // valid
        {
            buff.append("VALID " + filename + "\n");
            numValidFiles++;
        } else if (handler.containsDTD) // not valid
        {
            buff.append("NOT VALID " + filename + "\n");
            buff.append(errorBuff.toString());
            numInvalidFiles++;
        } else // no DOCTYPE to use for validation
        {
            buff.append("NO DOCTYPE DECLARATION " + filename + "\n");
            numFilesMissingDoctype++;
        }
    } catch (Exception e) // Serious problem!
    {
        buff.append("NOT WELL-FORMED " + filename + ". " + e.getMessage() + "\n");
        numMalformedFiles++;
    } finally {
        numXMLFiles++;
    }
}

From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java

/**
 * Handle the given archive's content by sending each entry to the given handler.
 * /*  w  w  w . ja  v a  2s  .  c o  m*/
 * @param archive
 * @param handler
 * @throws Exception
 */
public void handleArchive(final Archive archive, final ArchiveResultHandler handler) throws Exception {
    // Create a validating SAX parser

    final SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);

    // Create a common transformer per thread

    Transformer transformer = null;

    try {
        transformer = transformerCache.getTransformer(archive.getId(), "archive",
                archive.getModificationDate());

        if (transformer == null)
            transformer = transformerCache.putContent(archive.getId(), "archive", archive.getModificationDate(),
                    archive.getTransformerContent());
    } catch (TransformerConfigurationException e) {
        logger.error("Unable to generate a (cached) transformer from the given content", e);

        return;
    } catch (TransformerFactoryConfigurationError e) {
        logger.error("Unable to generate a (cached) transformer from the given content", e);

        return;
    }

    // Store and process the files

    try {
        Map<File, String> storedResults = storeAndDecompressFiles(archive);

        List<String> deletedLinks = new ArrayList<String>();

        // Only process deletes when a deletion expression has been provided

        if (StringUtils.hasText(archive.getDeletionExpression())) {
            // Process all entries beforehand, so to exclude deletes from the final result

            for (Map.Entry<File, String> storedResult : storedResults.entrySet()) {
                File storedResultsFolder = storedResult.getKey();

                for (File entryLocation : storedResultsFolder.listFiles())
                    if (entryLocation.getName().matches(archive.getDeletionExpression())) {
                        String deleteLink = entryLocation.getName().replaceAll(archive.getDeletionExpression(),
                                archive.getInternalLink());

                        deletedLinks.add(deleteLink);

                        // Delete the actual link

                        cacheService
                                .addDeleted(new CacheService.DeletedEntry(archive.getCollection(), deleteLink));
                    }
            }
        }

        // Now process the stored results themselves

        for (Map.Entry<File, String> storedResult : storedResults.entrySet()) {
            File storedResultsFolder = storedResult.getKey();

            // Create the descriptions folder if it doesn't already exist

            File descriptionsFolderLocation = new File(storedResultsFolder, "descriptions");

            if (!descriptionsFolderLocation.exists())
                descriptionsFolderLocation.mkdirs();

            for (File entryLocation : storedResultsFolder.listFiles()) {
                if (entryLocation.isDirectory()) {
                    if (!entryLocation.getName().equals("descriptions"))
                        logger.warn("Unknown folder '" + entryLocation.getName()
                                + "'found in decompressed archive folder '"
                                + storedResultsFolder.getAbsolutePath() + "'");

                    continue;
                } else if (StringUtils.hasText(archive.getDeletionExpression())
                        && entryLocation.getName().matches(archive.getDeletionExpression()))
                    continue;

                InputStream transformationInputStream = null;

                try {
                    transformationInputStream = new BufferedInputStream(new FileInputStream(entryLocation));

                    // Now determine the content type and create a reader in case of structured content

                    MediaType entryMediaType = autoDetectParser.getDetector().detect(transformationInputStream,
                            new Metadata());

                    if (!(entryMediaType.getSubtype().equals("xml")
                            || entryMediaType.getSubtype().endsWith("+xml"))) {
                        logger.warn("Archive entry " + entryLocation.getAbsolutePath() + " contains "
                                + entryMediaType + " data which is unstructured, ignoring");

                        continue;
                    }
                } catch (IOException e) {
                    logger.error("Could not close input stream during archive processing", e);

                    if (transformationInputStream != null)
                        transformationInputStream.close();

                    continue;
                }

                // Process it as (semi-)structured content

                XmlReader transformationReader = new XmlReader(transformationInputStream, true);
                StringWriter transformationWriter = new StringWriter();

                try {
                    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");

                    // Use a SAX reader for entity resolution

                    XMLReader xmlReader = parserFactory.newSAXParser().getXMLReader();
                    InputSource inputSource = new InputSource(transformationReader);

                    xmlReader.setEntityResolver(transformerCache.getEntityResolver());
                    inputSource.setSystemId("file://" + transformerCache.getDtdImportPath() + "/template.xsl");

                    // Perform the actual transformation

                    transformer.setParameter("substituteUrl", archive.getInternalLink());
                    transformer.transform(new SAXSource(xmlReader, inputSource),
                            new StreamResult(transformationWriter));
                } catch (TransformerException e) {
                    logger.error("Unable to perform content transformation for entry "
                            + entryLocation.getAbsolutePath());

                    continue;
                } catch (SAXException e) {
                    logger.error("Unable to perform content transformation for entry "
                            + entryLocation.getAbsolutePath());

                    continue;
                } catch (ParserConfigurationException e) {
                    logger.error("Unable to perform content transformation for entry "
                            + entryLocation.getAbsolutePath());

                    continue;
                } finally {
                    transformationInputStream.close();
                    transformationReader.close();
                }

                // Create a syndication feed from the given result

                String resultContent = transformationWriter.toString();

                SyndFeed resultFeed = null;

                try {
                    SyndFeedInput feedInput = new SyndFeedInput();

                    resultFeed = feedInput.build(new StringReader(resultContent));
                } catch (FeedException e) {
                    logger.error("Could not parse the feed resulting from the archive entry transformation");

                    continue;
                } finally {
                    transformationWriter.close();
                }

                // Write the <description> content to a separate file and add it as an <enclosure>

                if (resultFeed.getEntries().size() > 0) {
                    Integer entryNumber = 0;

                    for (SyndEntry feedEntry : (Collection<SyndEntry>) resultFeed.getEntries()) {
                        if (!deletedLinks.contains(feedEntry.getLink())) {
                            String description = feedEntry.getDescription().getValue().trim();

                            File descriptionLocation = new File(descriptionsFolderLocation,
                                    stripExtension(entryLocation.getName()) + "-" + entryNumber++
                                            + (feedEntry.getDescription().getType().equals("text/html")
                                                    ? ".html"
                                                    : ".xml"));

                            Writer descriptionWriter = new OutputStreamWriter(
                                    new FileOutputStream(descriptionLocation), "UTF-8");

                            if (!description.endsWith("</html>"))
                                descriptionWriter.write("<html>\n<head>\n\t<title>" + feedEntry.getTitle()
                                        + "</title>\n</head>\n<body>\n");
                            descriptionWriter.write(description);
                            if (!description.endsWith("</html>"))
                                descriptionWriter.write("\n</body>\n</html>");

                            descriptionWriter.flush();
                            descriptionWriter.close();

                            // Remove the link from the processed cache should it already be in there, taking care of updates

                            cacheService.deleteElement(feedEntry.getLink());

                            // Then offer it up to the handler

                            if (logger.isDebugEnabled())
                                logger.debug("Adding result content (" + entryNumber
                                        + ") for archive entry with path " + entryLocation.getAbsolutePath());

                            try {
                                // NOTE: The encoding of 'UTF-8' is implied for archive-related files

                                handler.process(new URI(feedEntry.getLink()), archive.getHostname(), feedEntry,
                                        resultFeed);
                            } catch (FeedException e) {
                                logger.error(String.format(
                                        "Could not offer feed entry with link '%s' - invalid entry",
                                        feedEntry.getLink()), e);
                            } catch (URISyntaxException e) {
                                logger.error(String.format(
                                        "Could not offer feed entry with link '%s' - invalid link",
                                        feedEntry.getLink()), e);
                            }
                        } else
                            logger.info("Skipping over feed entry with link '" + feedEntry.getLink()
                                    + "' - marked for deletion");
                    }
                } else if (logger.isDebugEnabled())
                    logger.debug("No entries were found in archive entry with path "
                            + entryLocation.getAbsolutePath());
            }

            logger.info("Finished processing archive with name " + storedResult.getValue());

            // Now archive the entry in the cache

            cacheService.addArchived(storedResult.getValue());
        }

        logger.info("Finishing archive populator thread");
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }
}

From source file:MockFedoraIT.java

private void parseIrodsFile(IrodsIFileSystem module, String testPath) throws LowlevelStorageException {
    InputStream is = module.read(new File(testPath));
    // initialize sax for this parse
    try {/*from  w ww. jav  a 2 s .c o  m*/
        SAXParserFactory spf = SAXParserFactory.newInstance();
        // spf.setValidating(false);
        // spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        parser.parse(is, new DefaultHandler());
    } catch (Exception e) {
        throw new RuntimeException("Error with SAX parser", e);
    }
}

From source file:nz.co.wholemeal.christchurchmetro.Stop.java

public ArrayList getArrivals() throws Exception {
    arrivals.clear();/*from  w w w.j a v a 2 s. co m*/

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        URL source = new URL(arrivalURL + platformTag);
        EtaHandler handler = new EtaHandler();
        xr.setContentHandler(handler);
        xr.parse(new InputSource(source.openStream()));
        lastArrivalFetch = System.currentTimeMillis();
    } catch (Exception e) {
        throw e;
    }

    Collections.sort(arrivals, new ComparatorByEta());
    return arrivals;
}

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.  j a  va2  s.co  m*/
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:jp.gr.java_conf.petit_lycee.subsonico.MethodConstants.java

SubsonicResponse parseResponseXML(InputStream is)
        throws SubsonicException, IOException, SAXException, ParserConfigurationException {

    SubsonicXMLHandler handler = new SubsonicXMLHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();

    SAXParser parser = factory.newSAXParser();
    parser.parse(is, handler);/*  www.j  a v  a  2  s. co m*/
    if (handler.isError()) {
        throw handler.getException();
    }
    return handler.getResponse();
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulator.java

public static void main(String[] args) {
    boolean isTTY = (System.console() != null);
    long startTime = System.currentTimeMillis();

    try {/*from   ww w.  j ava  2s.  c o m*/
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        SAXParser theParser = parserFactory.newSAXParser();
        TNT4JSimulatorParserHandler xmlHandler = new TNT4JSimulatorParserHandler();

        processArgs(xmlHandler, args);

        TrackerConfig simConfig = DefaultConfigFactory.getInstance().getConfig(TNT4JSimulator.class.getName());
        logger = TrackingLogger.getInstance(simConfig.build());
        if (logger.isSet(OpLevel.TRACE))
            traceLevel = OpLevel.TRACE;
        else if (logger.isSet(OpLevel.DEBUG))
            traceLevel = OpLevel.DEBUG;

        if (runType == SimulatorRunType.RUN_SIM) {
            if (StringUtils.isEmpty(simFileName)) {
                simFileName = "tnt4j-sim.xml";
                String fileName = readFromConsole("Simulation file [" + simFileName + "]: ");

                if (!StringUtils.isEmpty(fileName))
                    simFileName = fileName;
            }

            StringBuffer simDef = new StringBuffer();
            BufferedReader simLoader = new BufferedReader(new FileReader(simFileName));
            String line;
            while ((line = simLoader.readLine()) != null)
                simDef.append(line).append("\n");
            simLoader.close();

            info("jKool Activity Simulator Run starting: file=" + simFileName + ", iterations=" + numIterations
                    + ", ttl.sec=" + ttl);
            startTime = System.currentTimeMillis();

            if (isTTY && numIterations > 1)
                System.out.print("Iteration: ");
            int itTrcWidth = 0;
            for (iteration = 1; iteration <= numIterations; iteration++) {
                itTrcWidth = printProgress("Executing Iteration", iteration, itTrcWidth);

                theParser.parse(new InputSource(new StringReader(simDef.toString())), xmlHandler);

                if (!Utils.isEmpty(jkFileName)) {
                    PrintWriter gwFile = new PrintWriter(new FileOutputStream(jkFileName, true));
                    gwFile.println("");
                    gwFile.close();
                }
            }
            if (numIterations > 1)
                System.out.println("");

            info("jKool Activity Simulator Run finished, elapsed time = "
                    + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - startTime));
            printMetrics(xmlHandler.getSinkStats(), "Total Sink Statistics");
        } else if (runType == SimulatorRunType.REPLAY_SIM) {
            info("jKool Activity Simulator Replay starting: file=" + jkFileName + ", iterations="
                    + numIterations);
            connect();
            startTime = System.currentTimeMillis();

            // Determine number of lines in file
            BufferedReader gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            for (numIterations = 0; gwFile.readLine() != null; numIterations++)
                ;
            gwFile.close();

            // Reopen the file and
            gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            if (isTTY && numIterations > 1)
                System.out.print("Processing Line: ");
            int itTrcWidth = 0;
            String gwMsg;
            iteration = 0;
            while ((gwMsg = gwFile.readLine()) != null) {
                iteration++;
                if (isTTY)
                    itTrcWidth = printProgress("Processing Line", iteration, itTrcWidth);
                gwConn.write(gwMsg);
            }
            if (isTTY && numIterations > 1)
                System.out.println("");
            long endTime = System.currentTimeMillis();

            info("jKool Activity Simulator Replay finished, elasped.time = "
                    + DurationFormatUtils.formatDurationHMS(endTime - startTime));
        }
    } catch (Exception e) {
        if (e instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e;
            error("Error at line: " + spe.getLineNumber() + ", column: " + spe.getColumnNumber(), e);
        } else {
            error("Error running simulator", e);
        }
    } finally {
        try {
            Thread.sleep(1000L);
        } catch (Exception e) {
        }
        TNT4JSimulator.disconnect();
    }

    System.exit(0);
}

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  a  va  2 s . 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:com.wadpam.ricotta.web.IndexController.java

protected void importXML(InputStream in, String projName, String branchName)
        throws ParserConfigurationException, SAXException, IOException {
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    final UserService userService = UserServiceFactory.getUserService();
    final User user = userService.getCurrentUser();
    final String updatedBy = null != user ? user.getEmail() : "[ANONYMOUS]";

    DefaultHandler dh = new TokensImportHandler(uberDao, projName, branchName, updatedBy);
    parser.parse(in, dh);/*from w  w  w. j a  v  a2  s. c o m*/
}