Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:com.bernard.beaconportal.activities.mail.store.WebDavStore.java

private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers,
        boolean needsParsing) throws MessagingException {
    DataSet dataset = new DataSet();
    if (K9.DEBUG && K9.DEBUG_PROTOCOL_WEBDAV) {
        Log.v(K9.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '"
                + messageBody + "'");
    }//w  w  w  .  j  a  v a2  s. c o  m

    if (url == null || method == null) {
        return dataset;
    }

    getHttpClient();

    try {
        StringEntity messageEntity = null;
        if (messageBody != null) {
            messageEntity = new StringEntity(messageBody);
            messageEntity.setContentType("text/xml");
        }
        InputStream istream = sendRequest(url, method, messageEntity, headers, true);
        if (istream != null && needsParsing) {
            try {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                WebDavHandler myHandler = new WebDavHandler();

                xr.setContentHandler(myHandler);

                xr.parse(new InputSource(istream));

                dataset = myHandler.getDataSet();
            } catch (SAXException se) {
                Log.e(K9.LOG_TAG,
                        "SAXException in processRequest() " + se + "\nTrace: " + processException(se));
                throw new MessagingException("SAXException in processRequest() ", se);
            } catch (ParserConfigurationException pce) {
                Log.e(K9.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: "
                        + processException(pce));
                throw new MessagingException("ParserConfigurationException in processRequest() ", pce);
            }

            istream.close();
        }
    } catch (UnsupportedEncodingException uee) {
        Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee));
        throw new MessagingException("UnsupportedEncodingException in processRequest() ", uee);
    } catch (IOException ioe) {
        Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe));
        throw new MessagingException("IOException in processRequest() ", ioe);
    }

    return dataset;
}

From source file:com.connectsdk.service.NetcastTVService.java

private JSONObject parseVolumeXmlToJSON(String data) {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {//  w ww  .  j a  v  a2  s.  c  o m
        InputStream stream = new ByteArrayInputStream(data.getBytes("UTF-8"));

        SAXParser saxParser = saxParserFactory.newSAXParser();
        NetcastVolumeParser handler = new NetcastVolumeParser();
        saxParser.parse(stream, handler);

        return handler.getVolumeStatus();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.connectsdk.service.NetcastTVService.java

private int parseAppNumberXmlToJSON(String data) {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {/*from  w  w w. j a  v a2s. c  om*/
        InputStream stream = new ByteArrayInputStream(data.getBytes("UTF-8"));

        SAXParser saxParser = saxParserFactory.newSAXParser();
        NetcastAppNumberParser handler = new NetcastAppNumberParser();
        saxParser.parse(stream, handler);

        return handler.getApplicationNumber();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}

From source file:com.connectsdk.service.NetcastTVService.java

private JSONArray parseApplicationsXmlToJSON(String data) {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {//from  w w  w.java2  s.c  o m
        InputStream stream = new ByteArrayInputStream(data.getBytes("UTF-8"));

        SAXParser saxParser = saxParserFactory.newSAXParser();
        NetcastApplicationsParser handler = new NetcastApplicationsParser();
        saxParser.parse(stream, handler);

        return handler.getApplications();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.connectsdk.service.NetcastTVService.java

@Override
public void getCurrentChannel(final ChannelListener listener) {
    String requestURL = getUDAPRequestURL(UDAP_PATH_DATA, TARGET_CURRENT_CHANNEL);

    ResponseListener<Object> responseListener = new ResponseListener<Object>() {

        @Override/*from  w w w  . j a v a  2 s. c o m*/
        public void onSuccess(Object response) {
            String strObj = (String) response;

            try {
                SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
                InputStream stream = new ByteArrayInputStream(strObj.getBytes("UTF-8"));
                SAXParser saxParser = saxParserFactory.newSAXParser();

                NetcastChannelParser parser = new NetcastChannelParser();
                saxParser.parse(stream, parser);

                JSONArray channelArray = parser.getJSONChannelArray();

                if (channelArray.length() > 0) {
                    JSONObject rawData = (JSONObject) channelArray.get(0);

                    ChannelInfo channel = NetcastChannelParser.parseRawChannelData(rawData);

                    Util.postSuccess(listener, channel);
                }
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    };

    ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(this,
            requestURL, null, responseListener);
    request.send();
}

From source file:com.connectsdk.service.NetcastTVService.java

@Override
public void getChannelList(final ChannelListListener listener) {
    String requestURL = getUDAPRequestURL(UDAP_PATH_DATA, TARGET_CHANNEL_LIST);

    ResponseListener<Object> responseListener = new ResponseListener<Object>() {

        @Override/*  ww w  . ja  v  a 2s .c  o  m*/
        public void onSuccess(Object response) {
            String strObj = (String) response;

            try {
                SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
                InputStream stream = new ByteArrayInputStream(strObj.getBytes("UTF-8"));
                SAXParser saxParser = saxParserFactory.newSAXParser();

                NetcastChannelParser parser = new NetcastChannelParser();
                saxParser.parse(stream, parser);

                JSONArray channelArray = parser.getJSONChannelArray();
                ArrayList<ChannelInfo> channelList = new ArrayList<ChannelInfo>();

                for (int i = 0; i < channelArray.length(); i++) {
                    JSONObject rawData;
                    try {
                        rawData = (JSONObject) channelArray.get(i);

                        ChannelInfo channel = NetcastChannelParser.parseRawChannelData(rawData);
                        channelList.add(channel);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                Util.postSuccess(listener, channelList);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    };

    ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(this,
            requestURL, null, responseListener);
    request.setHttpMethod(ServiceCommand.TYPE_GET);
    request.send();
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in a DigiDoc file/*from   w w w.  j av  a2 s.co m*/
 * @param digiSigStream opened stream with Signature data
 * The user must open and close it.
 * @return signed document object if successfully parsed
 */
public Signature readSignature(InputStream digiSigStream) throws DigiDocException {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(digiSigStream, this);
    } catch (SAXDigiDocException ex) {
        throw ex.getDigiDocException();
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_PARSE_XML);
    }
    if (m_sig == null)
        throw new DigiDocException(DigiDocException.ERR_DIGIDOC_FORMAT,
                "This document is not in signature format", null);
    return m_sig;
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in a DigiDoc file.This method reads only data in digidoc format. Not BDOC!
 * @param digiDocStream opened stream with DigiDoc data
 * The user must open and close it./*from   w w w .j a  v  a 2s. c om*/
 * @return signed document object if successfully parsed
 */
public SignedDoc readDigiDocFromStream(InputStream digiDocStream) throws DigiDocException {
    DigiDocVerifyFactory.initProvider();
    if (m_logger.isDebugEnabled())
        m_logger.debug("Start reading ddoc/bdoc");
    try {
        if (m_logger.isDebugEnabled())
            m_logger.debug("Reading ddoc");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(digiDocStream, this);
    } catch (SAXDigiDocException ex) {
        throw ex.getDigiDocException();
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_PARSE_XML);
    }
    if (m_doc == null)
        throw new DigiDocException(DigiDocException.ERR_DIGIDOC_FORMAT, "This document is not in digidoc",
                null);
    return m_doc;
}

From source file:com.agilejava.docbkx.maven.AbstractTransformerMojo.java

/**
 * Builds the actual output document.//from  w ww .j  av  a  2s  . c  om
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().info("Skipping plugin execution");
        return;
    }

    // userland (ant tasks) pre process
    preProcess();

    final File targetDirectory = getTargetDirectory();
    final File sourceDirectory = getSourceDirectory();
    if (!sourceDirectory.exists()) {
        return; // No sources, so there is nothing to render.
    }
    if (!targetDirectory.exists()) {
        org.codehaus.plexus.util.FileUtils.mkdir(targetDirectory.getAbsolutePath());
    }

    final String[] included = scanIncludedFiles();

    // configure a resolver for catalog files
    final CatalogManager catalogManager = createCatalogManager();
    final CatalogResolver catalogResolver = new CatalogResolver(catalogManager);
    // configure a resolver for urn:dockbx:stylesheet
    final URIResolver uriResolver = createStyleSheetResolver(catalogResolver);
    // configure a resolver for xml entities
    final InjectingEntityResolver injectingResolver = createEntityResolver(catalogResolver);

    EntityResolver resolver = catalogResolver;
    if (injectingResolver != null) {
        resolver = injectingResolver;
    }

    // configure the builder for XSL Transforms
    final TransformerBuilder builder = createTransformerBuilder(uriResolver);
    // configure the XML parser
    SAXParserFactory factory = createParserFactory();

    // iterate over included source files
    for (int i = included.length - 1; i >= 0; i--) {
        try {
            if (injectingResolver != null) {
                injectingResolver.forceInjection();
            }
            final String inputFilename = included[i];
            // targetFilename is inputFilename - ".xml" + targetFile extension
            String baseTargetFile = inputFilename.substring(0, inputFilename.length() - 4);
            final String targetFilename = baseTargetFile + "." + getTargetFileExtension();
            final File sourceFile = new File(sourceDirectory, inputFilename);
            getLog().debug("SourceFile: " + sourceFile.toString());

            // creating targetFile
            File targetFile = null;
            if (isUseStandardOutput()) {
                targetFile = new File(targetDirectory, targetFilename);
                getLog().debug("TargetFile: " + targetFile.toString());
            } else {
                String name = new File(baseTargetFile).getName();
                String dir = new File(baseTargetFile).getParent();
                if (dir == null) { // file is located on root of targetDirectory
                    targetFile = targetDirectory;
                } else { // else append the relative directory to targetDirectory
                    targetFile = new File(targetDirectory, dir);
                }
                targetFile = new File(targetFile, name + "." + getTargetFileExtension());
                getLog().debug("TargetDirectory: " + targetDirectory.getAbsolutePath());
            }

            if (!targetFile.exists() || (targetFile.exists() && FileUtils.isFileNewer(sourceFile, targetFile))
                    || (targetFile.exists() && getXIncludeSupported())) {
                getLog().info("Processing input file: " + inputFilename);

                final XMLReader reader = factory.newSAXParser().getXMLReader();
                // configure XML reader
                reader.setEntityResolver(resolver);
                // eval PI
                final PreprocessingFilter filter = createPIHandler(resolver, reader);
                // configure SAXSource for XInclude
                final Source xmlSource = createSource(inputFilename, sourceFile, filter);

                configureXref(targetFile);

                // XSL Transformation setup
                final Transformer transformer = builder.build();
                adjustTransformer(transformer, sourceFile.getAbsolutePath(), targetFile);

                // configure the output file
                Result result = null;
                if (!shouldProcessResult()) {
                    // if the output is not the main result of the transformation, ie xref database
                    if (getLog().isDebugEnabled()) {
                        result = new StreamResult(System.out);
                    } else {
                        result = new StreamResult(new NullOutputStream());
                    }
                } else if (isUseStandardOutput()) {
                    // if the output of the main result is the standard output
                    result = new StreamResult(targetFile.getAbsolutePath());
                } else {
                    // if the output of the main result is not the standard output
                    if (getLog().isDebugEnabled()) {
                        result = new StreamResult(System.out);
                    } else {
                        result = new StreamResult(new NullOutputStream());
                    }
                }

                transformer.transform(xmlSource, result);

                if (shouldProcessResult()) {
                    // if the transformation has produce the expected main results, we can continue
                    // the chain of processing in the output mojos which can override postProcessResult
                    postProcessResult(targetFile);

                    if (isUseStandardOutput()) {
                        getLog().info(targetFile + " has been generated.");
                    } else {
                        getLog().info("See " + targetFile.getParentFile().getAbsolutePath()
                                + " for generated file(s)");
                    }
                } else {
                    // if the output is not the main result
                    getLog().info("See " + targetFile.getParentFile().getAbsolutePath()
                            + " for generated secondary file(s)");
                }

            } else {
                getLog().info(targetFile + " is up to date.");
            }
        } catch (SAXException saxe) {
            throw new MojoExecutionException("Failed to parse " + included[i] + ".", saxe);
        } catch (TransformerException te) {
            throw new MojoExecutionException("Failed to transform " + included[i] + ".", te);
        } catch (ParserConfigurationException pce) {
            throw new MojoExecutionException("Failed to construct parser.", pce);
        }
    }

    // userland (ant tasks) post process
    postProcess();
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in only one <Signature>//from w ww .ja va2 s .c o  m
 * @param sdoc SignedDoc to add this signature to
 * @param sigStream opened stream with Signature data
 * The user must open and close it.
 * @return signed document object if successfully parsed
 */
public Signature readSignature(SignedDoc sdoc, InputStream sigStream) throws DigiDocException {
    m_doc = sdoc;
    m_nCollectMode = 0;
    try {
        // prepare validator to receive signature from xml file as root element
        if (sdoc != null && sdoc.getFormat() != null) {
            XmlElemInfo e = null;
            // for BDOC
            if (SignedDoc.FORMAT_BDOC.equals(sdoc.getFormat())) {
                e = new XmlElemInfo("XAdESSignatures", null, null);
            } else if (SignedDoc.FORMAT_DIGIDOC_XML.equals(sdoc.getFormat())) {
                e = new XmlElemInfo("SignedDoc", null, null);
            }
            if (e != null)
                m_elemRoot = m_elemCurrent = e;
        }
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(sigStream, this);
    } catch (SAXDigiDocException ex) {
        throw ex.getDigiDocException();
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_PARSE_XML);
    }
    if (m_doc.getLastSignature() == null)
        throw new DigiDocException(DigiDocException.ERR_DIGIDOC_FORMAT,
                "This document is not in Signature format", null);
    return m_doc.getLastSignature();
}