Example usage for javax.xml.parsers SAXParser getXMLReader

List of usage examples for javax.xml.parsers SAXParser getXMLReader

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser getXMLReader.

Prototype


public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;

Source Link

Document

Returns the org.xml.sax.XMLReader that is encapsulated by the implementation of this class.

Usage

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

/**
 * //  w w w  .j av 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

/**
 * //from   w w  w.  j  a  v  a2 s .  com
 * @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   www  .  jav  a2s .  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   w w  w  .  j a  v a2  s .  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 www  .  j a  v  a 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;//  www .  j  a va2s .  co m
    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;
}

From source file:com.silverpeas.importExport.control.ImportExport.java

/**
 * Mthode retournant l'arbre des objets mapps sur le fichier xml pass en paramtre.
 *
 * @param xmlFileName le fichier xml interprt par Castor
 * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML Castor
 * @throws ImportExportException//from   w w w  .java 2  s.  co m
 */
SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException {
    SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
            "root.MSG_GEN_ENTER_METHOD", "xmlFileName = " + xmlFileName);

    try {
        InputSource xmlInputSource = new InputSource(xmlFileName);
        String xsdPublicId = settings.getString("xsdPublicId");
        String xsdSystemId = settings.getString("xsdDefaultSystemId");

        // Load and parse default XML schema for import/export
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema",
                "com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory", null);
        Schema schema = schemaFactory.newSchema(new StreamSource(xsdSystemId));

        // Create an XML parser for loading XML import file
        SAXParserFactory factory = SAXParserFactory
                .newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setSchema(schema);
        SAXParser parser = factory.newSAXParser();

        // First try to determine to load the XML file using the default
        // XML-Schema
        ImportExportErrorHandler errorHandler = new ImportExportErrorHandler();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setErrorHandler(errorHandler);

        try {
            xmlReader.parse(xmlInputSource);

        } catch (SAXException ex) {
            SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                    "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("XML File ")).append(xmlFileName)
                            .append(" is not valid according to default schema").toString());

            // If case the default schema is not the one specified by the
            // XML import file, try to get the right XML-schema and
            // namespace (this is done by parsing without validation)
            ImportExportNamespaceHandler nsHandler = new ImportExportNamespaceHandler();
            factory.setSchema(null);
            parser = factory.newSAXParser();
            xmlReader = parser.getXMLReader();
            xmlReader.setContentHandler(nsHandler);
            xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
            xmlReader.parse(xmlInputSource);

            // If OK, extract the name and location of the schema
            String nsSpec = nsHandler.getNsSpec();
            if (nsSpec == null || xsdPublicId.equals(nsSpec)) {
                throw ex;
            }

            String nsVersion = extractUriNameIndex(nsSpec);
            if (nsVersion.length() == 0) {
                throw ex;
            }

            String altXsdSystemId = settings.getStringWithParam("xsdSystemId", nsVersion);
            if ((altXsdSystemId == null) || (altXsdSystemId.equals(xsdSystemId))) {
                throw ex;
            }

            SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                    "root.MSG_GEN_PARAM_VALUE",
                    (new StringBuilder("Trying again using schema specification located at "))
                            .append(altXsdSystemId).toString());

            // Try again to load, parse and validate the XML import file,
            // using the new schema specification
            schema = schemaFactory.newSchema(new StreamSource(altXsdSystemId));
            factory.setSchema(schema);
            parser = factory.newSAXParser();
            xmlReader = parser.getXMLReader();
            xmlReader.setErrorHandler(errorHandler);
            xmlReader.parse(xmlInputSource);
        }

        SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                "root.MSG_GEN_PARAM_VALUE", "XML Validation complete");

        // Mapping file for Castor
        String mappingDir = settings.getString("mappingDir");
        String mappingFileName = settings.getString("importExportMapping");
        String mappingFile = mappingDir + mappingFileName;
        Mapping mapping = new Mapping();

        // Load mapping and instantiate a Unmarshaller
        mapping.loadMapping(mappingFile);
        Unmarshaller unmar = new Unmarshaller(SilverPeasExchangeType.class);
        unmar.setMapping(mapping);
        unmar.setValidation(false);

        // Unmarshall the process model
        SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmar.unmarshal(xmlInputSource);
        SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                "root.MSG_GEN_PARAM_VALUE", "Unmarshalling complete");
        return silverpeasExchange;

    } catch (MappingException me) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_LOADING_XML_MAPPING_FAILED",
                "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me);
    } catch (MarshalException me) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_UNMARSHALLING_FAILED",
                "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me);
    } catch (ValidationException ve) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve);
    } catch (IOException ioe) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_LOADING_XML_MAPPING_FAILED",
                "XML Filename " + xmlFileName + ": " + ioe.getLocalizedMessage(), ioe);
    } catch (ParserConfigurationException ex) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + ex.getLocalizedMessage(), ex);
    } catch (SAXNotRecognizedException snre) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + snre.getLocalizedMessage(), snre);
    } catch (SAXNotSupportedException snse) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + snse.getLocalizedMessage(), snse);
    } catch (SAXException se) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + se.getLocalizedMessage(), se);
    }
}

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  www .ja  v  a  2s .c om
 * 
 * @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:edwardawebb.queueman.classes.NetFlix.java

/**
 * Post a rating to specificed title/*  ww  w . j a  v  a 2 s. c om*/
 * @param modifiedDisc
 * @return SubCode, httpResponseCode or NF_ERROR_BAD_DEFAULT on exception
 */
public int setRating(Disc modifiedDisc) {

    int result = NF_ERROR_BAD_DEFAULT;
    // 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());

    // postProvider.setOAuth10a(false);
    InputStream xml = null;
    try {

        // Construct data
        /*
         * Log.d("NetFlix", "title_ref=" + URLEncoder.encode(disc.getId(),
         * "UTF-8")); Log.d("NetFlix", "etag=" +
         * URLEncoder.encode(NetFlixQueue.getETag(), "UTF-8"));
         */
        URL url = new URL("https://api.netflix.com/users/" + user.getUserId() + "/ratings/title/actual");

        // Log.d("NetFlix", "@URL: " + url.toString())
        HttpClient httpclient = new DefaultHttpClient();
        // Your URL
        HttpPost httppost = new HttpPost(url.toString());
        postConsumer.setTokenWithSecret(user.getAccessToken(), user.getAccessTokenSecret());

        String rating = (modifiedDisc.getUserRating() == 0) ? NF_RATING_NO_INTEREST
                : String.valueOf(modifiedDisc.getUserRating().intValue());
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        // Your DATA
        nameValuePairs.add(new BasicNameValuePair("title_ref", modifiedDisc.getId()));
        nameValuePairs.add(new BasicNameValuePair("rating", rating));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        postConsumer.sign(httppost);

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

        xml = response.getEntity().getContent();
        lastResponseMessage = response.getStatusLine().getStatusCode() + ": "
                + response.getStatusLine().getReasonPhrase();
        result = response.getStatusLine().getStatusCode();

        /* Log.d("NetFlix", "" +
         response.getEntity().getContentType().toString()); BufferedReader
         in = new BufferedReader(new InputStreamReader(xml)); String
         linein = null; while ((linein = in.readLine()) != null) {
         Log.d("NetFlix", "SetRating: " + linein); }*/

        // Log.i("NetFlix", "Parsing XML Response")
        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));

        if (result == 201 || result == 422) {
            switch (modifiedDisc.getQueueType()) {
            //could be rating froms earch, recommends, instant, discm, or at home
            case NetFlixQueue.QUEUE_TYPE_RECOMMEND:
                ((Disc) recomemendedQueue.getDiscs().get(recomemendedQueue.indexOf(modifiedDisc)))
                        .setUserRating(modifiedDisc.getUserRating());
                break;
            case NetFlixQueue.QUEUE_TYPE_INSTANT:
                ((Disc) instantQueue.getDiscs().get(instantQueue.indexOf(modifiedDisc)))
                        .setUserRating(modifiedDisc.getUserRating());
                break;
            case NetFlixQueue.QUEUE_TYPE_DISC:
                ((Disc) discQueue.getDiscs().get(discQueue.indexOf(modifiedDisc)))
                        .setUserRating(modifiedDisc.getUserRating());
                break;
            }
        }

        lastNFResponseMessage = "NF: " + myHandler.getMessage();
        result = myHandler.getSubCode(result);

    } 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 (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        reportError(e, lastResponseMessage);
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        reportError(e, lastResponseMessage);
    }
    return result;
}

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

/**
 * //  w  w  w. ja  va 2 s.co m
 * @param queueType
 * @param maxResults
 * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions
 */
public int getQueue(int queueType, String maxResults) {
    Log.d("NetFlix", "getQueue()>>>");
    URL QueueUrl = null;
    QueueHandler myQueueHandler = null;
    int result = NF_ERROR_BAD_DEFAULT;
    if (maxResults.equals(QueueMan.ALL_TITLES_STRING)) {
        maxResults = "500";
    }
    // addtional info to return 
    String expanders = "?expand=synopsis,formats&max_results=" + maxResults;
    InputStream xml = null;
    try {
        switch (queueType) {
        case NetFlixQueue.QUEUE_TYPE_INSTANT:
            if (!NetFlix.instantQueue.isEmpty() && instantQueue.isDownloaded())
                return SUCCESS_FROM_CACHE;
            QueueUrl = new URL(
                    "http://api.netflix.com/users/" + user.getUserId() + "/queues/instant" + expanders);
            myQueueHandler = new InstantQueueHandler();
            break;
        case NetFlixQueue.QUEUE_TYPE_DISC:
            if (!NetFlix.discQueue.isEmpty() && discQueue.isDownloaded())
                return SUCCESS_FROM_CACHE;
            QueueUrl = new URL(
                    "http://api.netflix.com/users/" + user.getUserId() + "/queues/disc/available" + expanders);

            myQueueHandler = new DiscQueueHandler();
            break;
        }
        //Log.d("NetFlix", "" + QueueUrl.toString());
        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();
        Log.d("NetFlix", "getQueue() | ready");
        NetFlix.oaconsumer.sign(request);
        Log.d("NetFlix", "getQueue() | signed");
        request.connect();

        Log.d("NetFlix", "getQueue() | response");
        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("NetFlix", "GetQueue: " +
          linein); }*/

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

        xr.setContentHandler(myQueueHandler);

        Log.d("NetFlix", "getQueue() | parse ready");
        xr.parse(new InputSource(xml));

        Log.d("NetFlix", "getQueue() | parse complete");
        result = myQueueHandler.getSubCode(result);

        if (myQueueHandler.getMessage() != null) {
            //we may have an error from netflix, check it
            lastResponseMessage += "  NF:" + result + ", " + myQueueHandler.getMessage();
            lastNFResponseMessage = myQueueHandler.getMessage();
        } else {
            lastNFResponseMessage = "No Message";
        }
        if (result == 200) {
            switch (queueType) {
            case NetFlixQueue.QUEUE_TYPE_INSTANT:
                instantQueue.setDownloaded(true);
                break;
            case NetFlixQueue.QUEUE_TYPE_DISC:
                discQueue.setDownloaded(true);
                break;
            }
        } else 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("NF Message:", "" + myQueueHandler.getMessage());
            FlurryAgent.onEvent("getQueue502", parameters);
        }

    } 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", "getQueue()<<<");
    return result;
}