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.kdmanalytics.toif.assimilator.Assimilator.java

/**
 * Load the kdm file. parse the input file.
 * //from  w  w  w  .  j av a 2 s.c  o m
 * @param xmlFile
 *          the input file
 * @param out
 *          output stream
 * @return the xml handler for the kdm data.
 * @throws IOException
 * @throws ToifInternalException
 */
public KdmXmlHandler load(File xmlFile, PipedOutputStream out)
        throws IOException, RepositoryException, ToifException {
    RepositoryConnection tempCon = null;
    KdmXmlHandler kdmXmlHandler = null;
    PrintWriter pw = null;
    try {
        File tempFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "KDMRepository");

        deleteDirectory(tempFile);

        tempFile.deleteOnExit();
        Repository tempRepository = new SailRepository(new NativeStore(tempFile));
        tempRepository.initialize();

        tempCon = tempRepository.getConnection();
        /**
         * The factory used to drive the parsing process.
         * 
         */
        SAXParserFactory factory = null;
        // Use the default (non-validating) parser
        factory = SAXParserFactory.newInstance();

        SAXParser saxParser;
        saxParser = factory.newSAXParser();

        // Have to parse the file once to determine the maximum id;
        KdmXmiIdHandler idHandler = new KdmXmiIdHandler();

        // Need to set the stream to UTF-8 ti ensure that we correctly
        // handle
        // characters in Strings
        InputStream inputStream = new FileInputStream(xmlFile);
        InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
        InputSource inputSource = new InputSource(inputReader);
        inputSource.setEncoding("UTF-8");

        saxParser.parse(inputSource, idHandler);

        tempCon.setAutoCommit(false); // Control commit for speed

        pw = new PrintWriter(out);
        kdmXmlHandler = new KdmXmlHandler(pw, repository, idHandler.getMaxId());

        // Parse the input
        saxParser.parse(xmlFile, kdmXmlHandler);

        // Commit postLoad data
        kdmXmlHandler.postLoad();

        tempCon.commit();
        tempCon.clear();
    }

    catch (ParserConfigurationException | SAXException ex) {
        final String msg = "Parser exception encountered:";
        LOG.error(msg, ex);
        throw new ToifException(msg, ex);
    } finally {
        if (pw != null) {
            pw.flush();
            pw.close();
        }
        if (null != tempCon) {
            tempCon.close();
        }

    }
    return kdmXmlHandler;

}

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 om
        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:jp.co.fttx.rakuphotomail.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 (RakuPhotoMail.DEBUG && RakuPhotoMail.DEBUG_PROTOCOL_WEBDAV) {
        Log.v(RakuPhotoMail.LOG_TAG, "processRequest url = '" + url + "', method = '" + method
                + "', messageBody = '" + messageBody + "'");
    }/*from w  w w  .  ja  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(RakuPhotoMail.LOG_TAG,
                        "SAXException in processRequest() " + se + "\nTrace: " + processException(se));
                throw new MessagingException("SAXException in processRequest() ", se);
            } catch (ParserConfigurationException pce) {
                Log.e(RakuPhotoMail.LOG_TAG, "ParserConfigurationException in processRequest() " + pce
                        + "\nTrace: " + processException(pce));
                throw new MessagingException("ParserConfigurationException in processRequest() ", pce);
            }

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

    return dataset;
}

From source file:edwardawebb.queueman.classes.NetFlix.java

/**
 * moveInQueue This will post to netflix with the new ddesired position.
 * Disc q only 1 based index//from   w w  w . j a v a2 s  .  com
 * 
 * @param disc
 * @param oldPosition
 * @param newPosition
 * @param queueType
 * @return subcode, statuscode, or httpresponse code (NF_ERROR_BAD_DEFAULT on exception)
 */
public int moveInQueue(Disc disc, int oldPosition, int newPosition, int queueType) {

    int result = NF_ERROR_BAD_DEFAULT;

    //getNewETag(queueType,newPosition);
    // 2 choirs, send request to netflix, and if successful update local q.

    OAuthConsumer postConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET,
            SignatureMethod.HMAC_SHA1);
    postConsumer.setTokenWithSecret(user.getAccessToken(), user.getAccessTokenSecret());

    InputStream xml = null;
    URL url = null;
    try {

        url = new URL("http://api.netflix.com/users/" + user.getUserId() + "/queues/"
                + NetFlixQueue.queueTypeText[queueType]);
        Log.d("NetFlix", "Moving: " + url.toString());
        HttpClient httpclient = new DefaultHttpClient();
        // Your URL
        HttpPost httppost = new HttpPost(url.toString());

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        // Your DATA
        nameValuePairs.add(new BasicNameValuePair("title_ref", disc.getId()));
        nameValuePairs.add(new BasicNameValuePair("position", String.valueOf(newPosition)));
        nameValuePairs.add(new BasicNameValuePair("etag", NetFlix.discQueue.getETag()));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        postConsumer.sign(httppost);

        HttpResponse response;
        response = httpclient.execute(httppost);

        xml = response.getEntity().getContent();

        result = response.getStatusLine().getStatusCode();

        /*  BufferedReader in = new BufferedReader(new
          InputStreamReader(xml)); String linein = null; while ((linein =
          in.readLine()) != null) { Log.d("NetFlix", "Move Movie: " +
          linein); }*/
        lastResponseMessage = "HTTP:" + response.getStatusLine().getStatusCode() + ", "
                + response.getStatusLine().getReasonPhrase();

        if (result == 502) {
            HashMap<String, String> parameters = new HashMap<String, String>();
            parameters.put("Queue Type:", "" + NetFlixQueue.queueTypeText[queueType]);
            parameters.put("HTTP Result:", "" + lastResponseMessage);
            parameters.put("User ID:", "" + user.getUserId());
            parameters.put("Disc ID:", "" + disc.getId());
            parameters.put("Positions:", "" + disc.getPosition() + " -> " + String.valueOf(newPosition));
            parameters.put("URL:", "" + url);
            FlurryAgent.onEvent("MoveInQueue502", parameters);

            return result;

        }

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
        sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();
        MoveQueueHandler myHandler = new MoveQueueHandler(oldPosition);
        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));
        // result=response.getStatusLine().getStatusCode();
        result = myHandler.getSubCode(result);

        if (myHandler.getMessage() != null) {
            //we may have an error from netflix, check it
            lastResponseMessage += "  NF: " + result + ", " + myHandler.getMessage();
        } else {
            if (queueType == NetFlixQueue.QUEUE_TYPE_DISC
                    && newPosition > (discQueue.getStartIndex() + discQueue.getPerPage())) {
                // a disc queue and we have moved past our current viewing 
                // so we will remove it from viewing to prevnt confusion and removing mishpas (position will be lost)
                discQueue.delete(disc);
                result = MOVED_OUTSIDE_CURRENT_VIEW;
            }
        }
    } catch (IOException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "IO Error connecting to NetFlix queue")
    } catch (OAuthMessageSignerException e) {

        reportError(e, lastResponseMessage);
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
    } catch (SAXException e) {

        reportError(e, lastResponseMessage);
    } catch (ParserConfigurationException e) {

        reportError(e, lastResponseMessage);
    }
    return result;
}

From source file:se.lu.nateko.edca.svc.GeoHelper.java

/**
 * Parses an XML response from a WFS Transaction (Insert) request and
 * reports if the response contains a Service Exception.
 * @param xmlResponse String containing the XML response from a DescribeFeatureType request.
 *//*from w ww. j  a  va  2 s . co m*/
protected boolean parseXMLResponse(InputStream xmlResponse) {
    Log.d(TAG, "parseXMLResponse(InputStream) called.");

    mInsertedIDs = new ArrayList<Long>();

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return false;
    }
    return true;
}

From source file:com.silverwrist.venice.core.impl.ConferencingImporter.java

final List importMessages(InputStream xmlstm) throws DataException {
    try { // create a SAX parser and let it loose on the input data with our listener
        SAXParserFactory fact = SAXParserFactory.newInstance();
        fact.setNamespaceAware(false);// w  ww  .j a v a 2s  . c om
        fact.setValidating(false);
        SAXParser parser = fact.newSAXParser();
        parser.parse(xmlstm, new Listener());

    } // end try
    catch (ParserConfigurationException e) { // configuration error
        throw new DataException("Error configuring XML parser for message import: " + e.getMessage(), e);

    } // end catch
    catch (SAXException e) { // give an error message
        throw new DataException("Error importing messages: " + e.getMessage(), e);

    } // end catch
    catch (IOException e) { // I/O error in parsing!
        throw new DataException("Error importing messages: " + e.getMessage(), e);

    } // end catch

    if (m_events == null)
        return Collections.EMPTY_LIST;
    ArrayList rc = new ArrayList(m_events);
    m_events = null;
    return Collections.unmodifiableList(rc);

}

From source file:com.fsck.k9.mail.store.webdav.WebDavStore.java

private DataSet processRequest(String url, String method, String messageBody, Map<String, String> headers,
        boolean needsParsing) throws MessagingException {
    DataSet dataset = new DataSet();
    if (K9MailLib.isDebug() && DEBUG_PROTOCOL_WEBDAV) {
        Log.v(LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '"
                + messageBody + "'");
    }//from   ww w. j a va2s  .co  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(LOG_TAG, "SAXException in processRequest() " + se + "\nTrace: " + processException(se));
                throw new MessagingException("SAXException in processRequest() ", se);
            } catch (ParserConfigurationException pce) {
                Log.e(LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: "
                        + processException(pce));
                throw new MessagingException("ParserConfigurationException in processRequest() ", pce);
            }

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

    return dataset;
}

From source file:com.g2inc.scap.library.domain.SCAPContentManager.java

public List<File> getOvalFiles(File dir) {
    ArrayList<File> ovalFileList = new ArrayList<File>();
    // get list of all xml files in dir
    File[] xmlFiles = dir.listFiles(new FilenameFilter() {
        @Override/*  w  w w .  j a  va2s .  c  om*/
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".xml");
        }
    });
    if (xmlFiles != null && xmlFiles.length > 0) {
        try {
            SAXParserFactory saxfactory = SAXParserFactory.newInstance();
            saxfactory.setValidating(false);
            saxfactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            saxfactory.setFeature("http://xml.org/sax/features/validation", false);

            for (int i = 0; i < xmlFiles.length; i++) {
                SAXParser saxparser = saxfactory.newSAXParser();
                XMLReader xmlReader = saxparser.getXMLReader();
                OvalParser ovalParser = new OvalParser();
                xmlReader.setContentHandler(ovalParser);
                FileInputStream inStream = new FileInputStream(xmlFiles[i]);
                xmlReader.parse(new InputSource(inStream));
                if (ovalParser.isOval()) {
                    ovalFileList.add(xmlFiles[i]);
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Caught an error trying list oval files in directory " + dir.getAbsolutePath(), e);
        }
    }
    return ovalFileList;
}

From source file:br.pcfl.up.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 (Up.DEBUG && Up.DEBUG_PROTOCOL_WEBDAV) {
        Log.v(Up.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '"
                + messageBody + "'");
    }//from   ww w .j  a v  a2  s.  c om

    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(Up.LOG_TAG,
                        "SAXException in processRequest() " + se + "\nTrace: " + processException(se));
                throw new MessagingException("SAXException in processRequest() ", se);
            } catch (ParserConfigurationException pce) {
                Log.e(Up.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: "
                        + processException(pce));
                throw new MessagingException("ParserConfigurationException in processRequest() ", pce);
            }

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

    return dataset;
}

From source file:cn.mailchat.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 (MailChat.DEBUG && MailChat.DEBUG_PROTOCOL_WEBDAV) {
        Log.v(MailChat.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '"
                + messageBody + "'");
    }/*from  ww  w. j  a  va 2s.  c  om*/

    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(MailChat.LOG_TAG,
                        "SAXException in processRequest() " + se + "\nTrace: " + processException(se));
                throw new MessagingException("SAXException in processRequest() ", se);
            } catch (ParserConfigurationException pce) {
                Log.e(MailChat.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: "
                        + processException(pce));
                throw new MessagingException("ParserConfigurationException in processRequest() ", pce);
            }

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

    return dataset;
}