Example usage for org.xml.sax XMLReader setContentHandler

List of usage examples for org.xml.sax XMLReader setContentHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setContentHandler.

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:org.xwiki.gadgets.internal.GoogleGadgetService.java

/**
 * {@inheritDoc}//from   w  w  w .  j av a2 s . c o  m
 * 
 * @see GadgetService#parseUserPrefs(String)
 */
public List<UserPref> parseUserPrefs(String gadgetUri) {
    try {
        XMLReader xr = xmlReaderFactory.createXMLReader();
        UserPrefsHandler upHandler = new UserPrefsHandler();
        xr.setContentHandler(upHandler);
        xr.parse(new InputSource(gadgetUri));

        return upHandler.getResult();
    } catch (Exception e) {
        LOG.error(String.format("Exception while parsing User Preferences from gadget XML at location %s.",
                gadgetUri), e);
        return null;
    }
}

From source file:org.xwiki.gadgets.internal.GoogleGadgetService.java

/**
 * {@inheritDoc}//from w w w .j a v a2 s. c o m
 * 
 * @see GadgetService#parseModulePrefs(String)
 */
public ModulePrefs parseModulePrefs(String gadgetUri) {
    try {
        XMLReader xr = xmlReaderFactory.createXMLReader();
        ModulePrefsHandler mpHandler = new ModulePrefsHandler();
        xr.setContentHandler(mpHandler);
        xr.parse(new InputSource(gadgetUri));

        return mpHandler.getResult();
    } catch (Exception e) {
        LOG.error(String.format("Exception while parsing Module Preferences from gadget XML at location %s.",
                gadgetUri), e);
        return null;
    }
}

From source file:org.yawlfoundation.yawl.unmarshal.YawlXMLSpecificationValidator.java

/**
 * Sets the checker up for a run.//from   w ww  .  j  a v  a2s .co  m
 * @param version the version of the schema
 * @return a reader configured to do the checking.
 * @throws SAXException
 */
private XMLReader setUpChecker(String version) throws SAXException {
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    if (YSpecification.isValidVersion(version)) {
        parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                getSchemaLocation(version));
    } else {
        throw new RuntimeException("Version [" + version + "] is not valid version.");
    }
    parser.setContentHandler(this);
    parser.setErrorHandler(this);
    parser.setFeature("http://xml.org/sax/features/validation", true);
    parser.setFeature("http://apache.org/xml/features/validation/schema", true);
    parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    return parser;
}

From source file:org.zuinnote.hadoop.office.format.common.parser.msexcel.MSExcelLowFootprintParser.java

/**
 * Processes a OPCPackage (new Excel format, .xlsx) in Streaming Mode
 * /*from ww w  .j av  a2  s  .  com*/
 * @param pkg
 * @throws OpenXML4JException 
 * @throws IOException 
 */
private void processOPCPackage(OPCPackage pkg) throws FormatNotUnderstoodException {
    LOG.debug("Processing OPCPackage in low footprint mode");
    // check if signature should be verified
    if (this.hocr.getVerifySignature()) {
        LOG.info("Verifying signature of document");
        SignatureConfig sic = new SignatureConfig();
        sic.setOpcPackage(pkg);
        SignatureInfo si = new SignatureInfo();
        si.setSignatureConfig(sic);
        if (!si.verifySignature()) {
            throw new FormatNotUnderstoodException(
                    "Cannot verify signature of OOXML (.xlsx) file: " + this.hocr.getFileName());
        } else {
            LOG.info("Successfully verifed first part signature of OXXML (.xlsx) file: "
                    + this.hocr.getFileName());
        }
        Iterator<SignaturePart> spIter = si.getSignatureParts().iterator();
        while (spIter.hasNext()) {
            SignaturePart currentSP = spIter.next();
            if (!(currentSP.validate())) {
                throw new FormatNotUnderstoodException(
                        "Could not validate all signature parts for file: " + this.hocr.getFileName());
            } else {
                X509Certificate currentCertificate = currentSP.getSigner();
                try {
                    if ((this.hocr.getX509CertificateChain().size() > 0) && (!CertificateChainVerificationUtil
                            .verifyCertificateChain(currentCertificate, this.hocr.getX509CertificateChain()))) {
                        throw new FormatNotUnderstoodException(
                                "Could not validate signature part for principal \""
                                        + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                                        + this.hocr.getFileName());
                    }
                } catch (CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                        | InvalidAlgorithmParameterException e) {
                    LOG.error("Could not validate signature part for principal \""
                            + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                            + this.hocr.getFileName(), e);
                    throw new FormatNotUnderstoodException("Could not validate signature part for principal \""
                            + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                            + this.hocr.getFileName());

                }
            }
        }
        LOG.info("Successfully verifed all signatures of OXXML (.xlsx) file: " + this.hocr.getFileName());
    }
    // continue in lowfootprint mode
    XSSFReader r;
    try {
        r = new XSSFReader(pkg);
    } catch (IOException | OpenXML4JException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
    }
    try {
        // read date format
        InputStream workbookDataXML = r.getWorkbookData();
        WorkbookDocument wd = WorkbookDocument.Factory.parse(workbookDataXML);
        this.isDate1904 = wd.getWorkbook().getWorkbookPr().getDate1904();

        // read shared string tables
        if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX
                .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
            this.pushSST = new ReadOnlySharedStringsTable(pkg);
        } else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX
                .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
            List<PackagePart> pkgParts = pkg
                    .getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType());
            if (pkgParts.size() > 0) {
                this.pullSST = new EncryptedCachedDiskStringsTable(pkgParts.get(0), this.hocr.getSstCacheSize(),
                        this.hocr.getCompressSST(), this.ca, this.cm);
            }
        }
        this.styles = r.getStylesTable();
        XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) r.getSheetsData();
        int sheetNumber = 0;
        while (iter.hasNext()) {

            // check if we need to parse this sheet?
            boolean parse = false;
            if (this.sheets != null) {
                for (int i = 0; i < this.sheets.length; i++) {
                    if (iter.getSheetName().equals(this.sheets[i])) {
                        parse = true;
                        break;
                    }
                }
            } else {
                parse = true;
            }
            // sheet is supposed to be parsed
            if (parse) {

                InputStream rawSheetInputStream = iter.next();
                this.sheetNameList.add(iter.getSheetName());
                InputSource rawSheetInputSource = new InputSource(rawSheetInputStream);
                if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX
                        .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
                    this.event = true;
                    LOG.info("Using SAX parser for low footprint Excel parsing");
                    XMLReader sheetParser = SAXHelper.newXMLReader();
                    XSSFEventParser xssfp = new XSSFEventParser(sheetNumber, iter.getSheetName(),
                            this.spreadSheetCellDAOCache);

                    ContentHandler handler = new XSSFSheetXMLHandler(this.styles, iter.getSheetComments(),
                            this.pushSST, xssfp, this.useDataFormatter, false);
                    sheetParser.setContentHandler(handler);
                    sheetParser.parse(rawSheetInputSource);
                    sheetNumber++;
                } else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX
                        .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
                    LOG.info("Using STAX parser for low footprint Excel parsing");
                    this.event = false;
                    this.pullSheetInputList.add(rawSheetInputStream);
                    this.pullSheetNameList.add(iter.getSheetName());
                    // make shared string table available

                    // everything else is in the getNext method
                } else {
                    LOG.error("Unknown XML parser configured for low footprint mode: \""
                            + this.hocr.getLowFootprintParser() + "\"");
                    throw new FormatNotUnderstoodException(
                            "Unknown XML parser configured for low footprint mode: \""
                                    + this.hocr.getLowFootprintParser() + "\"");
                }

            }
        }
    } catch (InvalidFormatException | IOException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
    } catch (SAXException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException(
                "Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
    } catch (ParserConfigurationException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException(
                "Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
    } catch (XmlException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException(
                "Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
    }
    // check skipping of additional lines
    for (int i = 0; i < this.hocr.getSkipLines(); i++) {
        this.getNext();
    }
    // check header
    if (this.hocr.getReadHeader()) {

        LOG.debug("Reading header...");
        Object[] firstRow = this.getNext();
        if (firstRow != null) {
            this.header = new String[firstRow.length];
            for (int i = 0; i < firstRow.length; i++) {
                if ((firstRow[i] != null)
                        && (!"".equals(((SpreadSheetCellDAO) firstRow[i]).getFormattedValue()))) {
                    this.header[i] = ((SpreadSheetCellDAO) firstRow[i]).getFormattedValue();
                }
            }
            this.header = MSExcelParser.sanitizeHeaders(this.header, this.hocr.getColumnNameRegex(),
                    this.hocr.getColumnNameReplace());
        } else {
            this.header = new String[0];
        }
    }
    this.headerParsed = true;

}

From source file:pl.otros.vfs.browser.auth.AuthStoreUtils.java

public void load(AuthStore authStore, InputStream in) throws IOException {
    try {// ww  w  .j  av  a2s.  c o m
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setContentHandler(new AuthStoreHandler(authStore));
        xmlReader.parse(new InputSource(in));
    } catch (SAXException e) {
        throw new IOException(e);
    }
}

From source file:self.philbrown.droidQuery.AjaxTask.java

@Override
protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled())
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {/*from  www.  j  a va2  s  . c  o  m*/
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(AjaxTask.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(AjaxTask.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.headers = null;
        return s;

    }

    if (request == null) {
        String type = options.type();
        if (type == null)
            type = "GET";
        if (type.equalsIgnoreCase("DELETE")) {
            request = new HttpDelete(options.url());
        } else if (type.equalsIgnoreCase("GET")) {
            request = new HttpGet(options.url());
        } else if (type.equalsIgnoreCase("HEAD")) {
            request = new HttpHead(options.url());
        } else if (type.equalsIgnoreCase("OPTIONS")) {
            request = new HttpOptions(options.url());
        } else if (type.equalsIgnoreCase("POST")) {
            request = new HttpPost(options.url());
        } else if (type.equalsIgnoreCase("PUT")) {
            request = new HttpPut(options.url());
        } else if (type.equalsIgnoreCase("TRACE")) {
            request = new HttpTrace(options.url());
        } else if (type.equalsIgnoreCase("CUSTOM")) {
            try {
                request = options.customRequest();
            } catch (Exception e) {
                request = null;
            }

            if (request == null) {
                Log.w("droidQuery.ajax",
                        "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                request = new HttpGet();
            }

        } else {
            //default to GET
            request = new HttpGet();
        }
    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", request);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class });
            if (options.processData() == null) {
                setEntity.invoke(request, new StringEntity(options.data().toString()));
            } else {
                Class<?> dataProcessor = Class.forName(options.processData());
                Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class });
                setEntity.invoke(request, constructor.newInstance(options.data()));
            }
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    HttpParams params = new BasicHttpParams();

    if (options.timeout() != 0) {
        HttpConnectionParams.setConnectionTimeout(params, options.timeout());
        HttpConnectionParams.setSoTimeout(params, options.timeout());
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (options.trustAllSSLCertificates()) {
        X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier(hostnameVerifier);
        schemeRegistry.register(new Scheme("https", socketFactory, 443));
        Log.w("Ajax", "Warning: All SSL Certificates have been trusted!");
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry);
    HttpClient client = new DefaultHttpClient(mgr, params);

    HttpResponse response = null;
    try {

        if (options.cookies() != null) {
            CookieStore cookies = new BasicCookieStore();
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
            }
            HttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
            response = client.execute(request, httpContext);
        } else {
            response = client.execute(request);
        }

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), response, options.dataType());
            else
                options.dataFilter().invoke(null, response, options.dataType());
        }

        final StatusLine statusLine = response.getStatusLine();

        final Function function = options.statusCode().get(statusLine.getStatusCode());
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusLine.getStatusCode(), options.clone());
                    else
                        function.invoke(null, statusLine.getStatusCode(), options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                parsedResponse = parseText(response);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    InputStream is = response.getEntity().getContent();
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(is, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(is, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    InputStream is = response.getEntity().getContent();

                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(is));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(response);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(response);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(response);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                parsedResponse = parseImage(response);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(response);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        }

        if (statusLine.getStatusCode() >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.headers = response.getAllHeaders();
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            Header[] lastModifiedHeaders = response.getHeaders("last-modified");
            if (lastModifiedHeaders.length >= 1) {
                try {
                    Header h = lastModifiedHeaders[0];
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h.getValue());
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.request = request;
                            error.options = options;
                            e.status = statusLine.getStatusCode();
                            e.reason = statusLine.getReasonPhrase();
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.headers = response.getAllHeaders();
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = statusLine.getReasonPhrase();
            s.headers = response.getAllHeaders();
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:stroom.xml.util.TestXMLWriter.java

private void processXML(final File inputFile, final File outputDir) {
    LOGGER.info("Processing file: " + inputFile.getAbsolutePath());
    FileUtil.mkdirs(outputDir);/*from   w w  w  . ja  v  a 2s. c  o  m*/

    // First create SAXON formatted output.
    final File saxonOutput = new File(outputDir,
            inputFile.getName().substring(0, inputFile.getName().lastIndexOf('.')) + ".saxon.xml");
    try {
        // Pretty print with SAXON.
        XMLUtil.prettyPrintXML(new BufferedInputStream(new FileInputStream(inputFile)),
                new BufferedOutputStream(new FileOutputStream(saxonOutput)));

        try {
            // Pretty print with XMLWriter.
            final File xwOutput = new File(outputDir,
                    inputFile.getName().substring(0, inputFile.getName().lastIndexOf('.')) + ".xw.xml");
            final FileWriter fw = new FileWriter(xwOutput);
            final BufferedWriter bw = new BufferedWriter(fw);
            final XMLWriter xmlWriter = new XMLWriter(bw);
            xmlWriter.setOutputXMLDecl(true);
            xmlWriter.setIndentation(3);

            final SAXParser saxParser = PARSER_FACTORY.newSAXParser();
            final XMLReader xmlReader = saxParser.getXMLReader();
            xmlReader.setContentHandler(xmlWriter);
            xmlReader.parse(new InputSource(new BufferedReader(new FileReader(inputFile))));

            bw.close();

        } catch (final Throwable t) {
            Assert.fail(t.getMessage());
        }
    } catch (final Throwable t) {
        // Ignore...
    }
}

From source file:tds.student.sbacossmerge.data.TestResponseReaderSax.java

public static TestResponseReader parseSax(InputStream xml, TestOpportunity testOpp) throws Exception {
    TestResponseReaderSax saxReader = new TestResponseReaderSax();
    saxReader._testOpp = testOpp;/*from   w  w  w .java  2  s. co  m*/

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();

    saxReader._xmlReader = xmlReader;
    ContentHandler defaultHandler = saxReader._parseHandlers.peek();
    xmlReader.setContentHandler(defaultHandler);

    xmlReader.parse(new InputSource(xml));

    return saxReader;
}

From source file:tv.acfun.video.player.resolver.SinaResolver.java

@Override
public void resolve(Context context) throws ResolveException {
    // TODO Auto-generated method stub
    try {//from w  w  w. ja v  a  2 s .  c  om
        if (mResolutionMode < RESOLUTION_HD2) {
            vid = getSinaMp4Vid(vid);
            Log.i(TAG, "sina mp4 mode");
        }
        String url = getContentUrl(vid);
        Log.i(TAG, "sina video url = " + url);
        InputStream stream = getResponseAsStream(url);
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        ContentHandler contentHandler = new UrlContentHandler();
        xmlReader.setContentHandler(contentHandler);
        xmlReader.parse(new InputSource(stream));
    } catch (Exception e) {
        throw new ResolveException(e);
    }
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.XSLTEntityHandler.java

public void parseToSAX(final String toRender, final ContentHandler ch) throws IOException, SAXException {
    /**//from  ww  w .j  av  a  2 s. co  m
     * create a proxy for the stream, filtering out the start element and
     * end element events
     */
    ContentHandler proxy = new ContentHandler() {
        public void setDocumentLocator(Locator arg0) {
            ch.setDocumentLocator(arg0);
        }

        public void startDocument() throws SAXException {
            // ignore
        }

        public void endDocument() throws SAXException {
            // ignore
        }

        public void startPrefixMapping(String arg0, String arg1) throws SAXException {
            ch.startPrefixMapping(arg0, arg1);
        }

        public void endPrefixMapping(String arg0) throws SAXException {
            ch.endPrefixMapping(arg0);
        }

        public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
            ch.startElement(arg0, arg1, arg2, arg3);
        }

        public void endElement(String arg0, String arg1, String arg2) throws SAXException {
            ch.endElement(arg0, arg1, arg2);
        }

        public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
            ch.characters(arg0, arg1, arg2);
        }

        public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException {
            ch.ignorableWhitespace(arg0, arg1, arg2);
        }

        public void processingInstruction(String arg0, String arg1) throws SAXException {
            ch.processingInstruction(arg0, arg1);
        }

        public void skippedEntity(String arg0) throws SAXException {
            ch.skippedEntity(arg0);
        }

    };
    InputSource ins = new InputSource(new StringReader(toRender));
    XMLReader xmlReader;
    try {
        SAXParser saxParser = saxParserFactory.newSAXParser();

        xmlReader = saxParser.getXMLReader();
    }

    catch (Exception e) {
        log.error("SAXException when creating XMLReader", e); //$NON-NLS-1$
        // rethrow!!
        throw new SAXException(e);
    }
    xmlReader.setContentHandler(proxy);
    xmlReader.parse(ins);
}