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:es.ehu.si.ixa.pipe.convert.Convert.java

/**
 * Process the ancora constituent XML annotation into Penn Treebank bracketing
 * style.//from   w  w  w. j  a v a  2  s.c  om
 * 
 * @param inXML
 *          the ancora xml constituent document
 * @return the ancora trees in penn treebank one line format
 * @throws IOException
 *           if io exception
 */
public String ancora2treebank(File inXML) throws IOException {
    String filteredTrees = null;
    if (inXML.isFile()) {

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            AncoraTreebank ancoraParser = new AncoraTreebank();
            saxParser.parse(inXML, ancoraParser);
            String trees = ancoraParser.getTrees();
            // remove empty trees created by "missing" and "elliptic" attributes
            filteredTrees = trees.replaceAll("\\(\\SN\\)", "");
            // format correctly closing brackets
            filteredTrees = filteredTrees.replace(") )", "))");
            // remove double spaces
            filteredTrees = filteredTrees.replaceAll("  ", " ");
            // remove empty sentences created by <sentence title="yes"> elements
            filteredTrees = filteredTrees.replaceAll("\\(SENTENCE \\)\n", "");
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        System.out.println("Please choose a valid file as input");
    }
    return filteredTrees;
}

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

@Override
public void getAppList(final AppListListener listener) {
    ResponseListener<Object> responseListener = new ResponseListener<Object>() {

        @Override//from  w  ww .  j  av  a2  s .  c  om
        public void onSuccess(Object response) {
            String msg = (String) response;

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

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

                List<AppInfo> appList = parser.getApplicationList();

                Util.postSuccess(listener, appList);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } 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);
        }
    };

    String action = "query";
    String param = "apps";

    String uri = requestURL(action, param);

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

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 va  2 s . c o m
        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.eleybourn.bookcatalogue.utils.Utils.java

static public void parseUrlOutput(String path, SAXParserFactory factory, DefaultHandler handler) {
    SAXParser parser;//  www.  j  ava2s  .  co m
    URL url;

    try {
        url = new URL(path);
        parser = factory.newSAXParser();
        parser.parse(Utils.getInputStream(url), handler);
        // Dont bother catching general exceptions, they will be caught by the caller.
    } catch (MalformedURLException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (ParserConfigurationException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (SAXException e) {
        String s = e.getMessage(); // "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (java.io.IOException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    }
}

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

/**
 * /*from  www. ja v  a 2 s. c o  m*/
 * @param queueType
 * @param maxResults
 * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions
 */
public int getHomeTitles() {
    URL QueueUrl = null;
    int result = NF_ERROR_BAD_DEFAULT;

    String expanders = "?expand=synopsis,formats";
    InputStream xml = null;
    try {

        if (!NetFlix.homeQueue.isEmpty())
            return 200;
        QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/at_home" + expanders);
        HomeQueueHandler myHandler = new HomeQueueHandler();
        Log.d("NetFlix", "" + QueueUrl.toString());

        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();
        result = request.getResponseCode();
        xml = request.getInputStream();

        /*BufferedReader in = new BufferedReader(new
        InputStreamReader(xml)); String linein = null; while ((linein =
        in.readLine()) != null) { Log.d("NetFlixQueue", "" +
        linein); }*/

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
        sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));

    } catch (ParserConfigurationException e) {

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

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

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

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }
    return result;
}

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

/**
 * //w  ww. j  a  va 2  s  .c o m
 * @param queueType
 * @param maxResults
 * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions
 */
public int getRecommendations(int startIndex, String maxResults) {
    times[0] = System.currentTimeMillis();
    URL QueueUrl = null;
    int result = NF_ERROR_BAD_DEFAULT;
    if (maxResults.equals(QueueMan.ALL_TITLES_STRING)) {
        maxResults = "500";
    }

    String expanders = "?expand=synopsis,formats&start_index=" + startIndex + "&max_results=" + maxResults;
    InputStream xml = null;
    try {
        // we're either rotating/task jumping OR we're starting/paging
        /*if (!NetFlix.recomemendedQueue.isEmpty() && startIndex == recomemendedQueue.getStartIndex()){
           return 200;
        }else if(recomemendedQueue.getTotalTitles() < startIndex){
           return NF_ERROR_NO_MORE;
        }else{
           recomemendedQueue.purge();
        }*/

        QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/recommendations" + expanders);
        RecommendationsHandler myHandler = new RecommendationsHandler(this);
        Log.d("NetFlix", "" + QueueUrl.toString());

        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();
        result = request.getResponseCode();
        xml = request.getInputStream();

        /*   BufferedReader in = new BufferedReader(new
               InputStreamReader(xml)); String linein = null; while ((linein =
               in.readLine()) != null) { Log.d("NetFlixQueue", "" +
               linein); }*/

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
        sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));

    } catch (ParserConfigurationException e) {

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

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

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

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }
    times[1] = System.currentTimeMillis();
    return result;
}

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

public boolean getNewETag(int queueType, int discPosition) {
    URL QueueUrl = null;//from   w w  w. jav a 2s  .  c o m
    DefaultHandler myQueueHandler = null;
    boolean result = false;
    //start index is 0 based, so step the true position down one
    String expanders = "?max_results=" + 1 + "&start_index=" + (discPosition - 1);
    InputStream xml = null;
    try {
        switch (queueType) {
        case NetFlixQueue.QUEUE_TYPE_INSTANT:
            QueueUrl = new URL(
                    "http://api.netflix.com/users/" + user.getUserId() + "/queues/instant" + expanders);
            myQueueHandler = new InstantETagHandler();
            break;
        case NetFlixQueue.QUEUE_TYPE_DISC:
            QueueUrl = new URL(
                    "http://api.netflix.com/users/" + user.getUserId() + "/queues/disc/available" + expanders);

            myQueueHandler = new DiscETagHandler();
            break;
        }
        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();

        if (request.getResponseCode() == 200) {
            xml = request.getInputStream();

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;
            sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            xr.setContentHandler(myQueueHandler);
            //our custom handler will throw an exception when he gets what he want, interupting the full parse
            ErrorProcessor errors = new ErrorProcessor();
            xr.setErrorHandler(errors);
            xr.parse(new InputSource(xml));
            result = true;
        }

    } catch (ParserConfigurationException e) {

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

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

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

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }
    return result;
}

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

public NetFlixQueue getSearchResults(String searchTerm) {
    searchQueue = new NetFlixQueue(NetFlixQueue.QUEUE_TYPE_SEARCH);
    setSignPost(user.getAccessToken(), user.getAccessTokenSecret());

    InputStream xml = null;/*from   ww  w.j  av a2s .co m*/
    try {
        String encSearchTerm = URLEncoder.encode(searchTerm);
        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        String expanders = "&expand=synopsis,formats";
        URL QueueUrl = null;

        QueueUrl = new URL("http://api.netflix.com/catalog/titles?term=" + encSearchTerm + expanders);
        // Log.d("NetFlix",""+QueueUrl.toString())
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();

        if (request.getResponseCode() == 200) {
            // Log.d("NetFlix", request.getContentType())
            // //Log.d("NetFlix",request.getInputStream().toString())
            // return xml xmldoc
            xml = request.getInputStream();

            /*BufferedReader in = new BufferedReader(new InputStreamReader(
                  xml));
            String linein = null;
            while ((linein = in.readLine()) != null) {
               Log.d("NetFlix", "SearchMovie: " + linein);
            }*/
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;

            sp = spf.newSAXParser();

            XMLReader xr = sp.getXMLReader();
            // SearchResultsHandler myHandler = new
            // SearchResultsHandler(this);
            SearchQueueHandler myHandler = new SearchQueueHandler();
            xr.setContentHandler(myHandler);
            xr.parse(new InputSource(xml));
        }

    } catch (ParserConfigurationException e) {

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

        reportError(e, lastResponseMessage);
    } 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);
    }

    return searchQueue;
}

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

/**
 * Returns the users first name, watch instant rights and preferred formats
 * requires user already set with auth tokens
 * @return//from   w  w  w . j  a  va 2  s.c  o m
 */
public boolean getUserDetails() {
    Log.d("NetFlix", "getUserDetails()>>>");
    URL QueueUrl = null;
    UserHandler myHandler = new UserHandler(user);
    boolean result = false;
    InputStream xml = null;
    try {

        QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId());

        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);

        Log.d("NetFlix", "getUserDetails() | signed");
        request.connect();

        Log.d("NetFlix", "getUserDetails() | response");
        //if succesful, populate remaing user details from netflix
        if (request.getResponseCode() == 200) {

            xml = request.getInputStream();

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;
            sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            xr.setContentHandler(myHandler);
            Log.d("NetFlix", "getUserDetails() | ready to parse");
            xr.parse(new InputSource(xml));

            Log.d("NetFlix", "getUserDetails() | parse complete");
            Log.d("NetFlix", "User Name: " + user.getFirstName());
            Log.d("NetFlix", "Formats: " + user.getPreferredFormats().toArray().toString());
            Log.d("NetFlix", "User Instant?: " + user.isCanWatchInstant());

        } else {

            BufferedReader in = new BufferedReader(new InputStreamReader(xml));
            String linein = null;
            while ((linein = in.readLine()) != null) {
                Log.d("NetFlix", "UserDetails: " + linein);
            }
        }

    } catch (ParserConfigurationException e) {

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

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

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

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }

    Log.d("NetFlix", "getUserDetails()>>>");
    return result;
}

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

public int deleteFromQueue(Disc disc, int queueType) {
    int result = NF_ERROR_BAD_DEFAULT;
    OAuthConsumer postConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET,
            SignatureMethod.HMAC_SHA1);
    postConsumer.setTokenWithSecret(user.getAccessToken(), user.getAccessTokenSecret());

    // postProvider.setOAuth10a(false);

    HttpClient httpclient = new DefaultHttpClient();

    URL QueueUrl;/*from  w  ww  . j  a  va  2  s . com*/
    InputStream xml = null;

    try {
        QueueUrl = new URL(disc.getId());
        HttpDelete httpAction = new HttpDelete(QueueUrl.toString());
        postConsumer.sign(httpAction);

        HttpResponse response = httpclient.execute(httpAction);

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

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

        XMLReader xr = sp.getXMLReader();
        QueueHandler myHandler = new QueueHandler();
        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));
        // result=response.getStatusLine().getStatusCode();
        result = myHandler.getSubCode(result);
        lastResponseMessage = "HTTP:" + response.getStatusLine().getStatusCode() + ", "
                + response.getStatusLine().getReasonPhrase();

        if (myHandler.getMessage() != null) {
            //we may have an error from netflix, check it
            lastResponseMessage += "  NF: " + result + ", " + myHandler.getMessage();
        }

    } catch (OAuthMessageSignerException e) {
        reportError(e, lastResponseMessage);
    } catch (OAuthExpectationFailedException e) {
        reportError(e, lastResponseMessage);
    } catch (ClientProtocolException e) {
        reportError(e, lastResponseMessage);
    } catch (IOException e) {
        reportError(e, lastResponseMessage);
    } catch (SAXException e) {
        reportError(e, lastResponseMessage);
    } catch (ParserConfigurationException e) {
        reportError(e, lastResponseMessage);
    }

    /*
     * On a successful; DELETE we remove our local recordss too
     */
    if (result == 200) {

        switch (queueType) {
        case NetFlixQueue.QUEUE_TYPE_DISC:
            NetFlix.discQueue.delete(disc);
            break;
        case NetFlixQueue.QUEUE_TYPE_INSTANT:
            NetFlix.instantQueue.delete(disc);
            break;
        }
        getNewETag(queueType);
    }
    return result;
}