Example usage for org.xml.sax XMLReader setContentHandler

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

Introduction

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

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

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

/**
 * Post a rating to specificed title/*from www .  j av a2  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

/**
 * moveInQueue This will post to netflix with the new ddesired position.
 * Disc q only 1 based index/*from  w w w  .j av  a 2 s . co m*/
 * 
 * @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

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

    InputStream xml = null;// w  ww .ja  va 2s  . c o 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:net.sf.joost.stx.Processor.java

/**
 * Assigns a parent to this filter instance. Attempts to register itself
 * as a lexical handler on this parent.//from ww  w .  j a v  a2  s.  com
 */
public void setParent(XMLReader parent) {
    super.setParent(parent);
    parent.setContentHandler(this); // necessary??

    try {
        parent.setProperty("http://xml.org/sax/properties/lexical-handler", this);
    } catch (SAXException ex) {
        if (log != null)
            log.warn("Accessing " + parent + ": " + ex);
        else
            System.err.println("Warning - Accessing " + parent + ": " + ex);
    }
}

From source file:Writer.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();/*from w  w  w. j  av  a  2  s  .c o  m*/
        System.exit(1);
    }

    // variables
    Writer writer = null;
    XMLReader parser = null;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
    boolean canonical = DEFAULT_CANONICAL;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                    }
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("np")) {
                namespacePrefixes = option.equals("np");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("xd")) {
                externalDTD = option.equals("xd");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equalsIgnoreCase("c")) {
                canonical = option.equals("c");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                e.printStackTrace(System.err);
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // setup writer
        if (writer == null) {
            writer = new Writer();
            try {
                writer.setOutput(System.out, "UTF8");
            } catch (UnsupportedEncodingException e) {
                System.err.println("error: Unable to set output. Exiting.");
                System.exit(1);
            }
        }

        // set parser
        parser.setContentHandler(writer);
        parser.setErrorHandler(writer);
        try {
            parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer);
        } catch (SAXException e) {
            // ignore
        }

        // parse file
        writer.setCanonical(canonical);
        try {
            parser.parse(arg);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            if (e instanceof SAXException) {
                Exception nested = ((SAXException) e).getException();
                if (nested != null) {
                    e = nested;
                }
            }
            e.printStackTrace(System.err);
        }
    }

}

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

/**
 * //  w  ww . j  av a  2s .  c  o  m
 * @param disc
 * @param queueType
 * @return SubCode, httpResponseCode or NF_ERROR_BAD_DEFAULT on exception
 */
public int addToQueue(Disc disc, int queueType) {
    lastResponseMessage = "";
    lastNFResponseMessage = "";
    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());
    OAuthProvider postProvider = new DefaultOAuthProvider(postConsumer, REQUEST_TOKEN_ENDPOINT_URL,
            ACCESS_TOKEN_ENDPOINT_URL, AUTHORIZE_WEBSITE_URL);
    String expanders = "?expand=synopsis,formats";
    InputStream xml = null;
    NetFlixQueue queue = null;
    URL QueueUrl = null;
    String eTag = null;
    URL url = null;
    try {

        // Construct data
        int queueSize = 0;
        switch (queueType) {
        case NetFlixQueue.QUEUE_TYPE_DISC:
            queueSize = NetFlix.discQueue.getTotalTitles();
            if (queueSize == 0)
                getNewETag(queueType);
            // @ TODO This is for issue 41
            if (disc.getPosition() > NetFlix.discQueue.getTotalTitles()) {
                disc.setPosition(NetFlix.discQueue.getTotalTitles());
            }
            // @ TODO   Move this to instnat once it works

            eTag = NetFlix.discQueue.getETag();
            url = new URL("https://api.netflix.com/users/" + user.getUserId() + "/queues/disc" + expanders);

            break;
        case NetFlixQueue.QUEUE_TYPE_INSTANT:
            eTag = NetFlix.instantQueue.getETag();
            url = new URL("https://api.netflix.com/users/" + user.getUserId() + "/queues/instant" + expanders);
            break;
        }

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

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        // Your DATA
        nameValuePairs.add(new BasicNameValuePair("title_ref", disc.getId()));
        nameValuePairs.add(new BasicNameValuePair("position", "" + disc.getPosition()));
        nameValuePairs.add(new BasicNameValuePair("etag", eTag));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        postConsumer.sign(httppost);

        HttpResponse response;
        response = httpclient.execute(httppost);
        result = response.getStatusLine().getStatusCode();

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

        /*  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", "AddMovie: " + linein); }
         if(true) return 200;
         //^ avoids the parser since we consumed xml for debug
         */

        // Log.i("NetFlix", "Parsing XML Response")
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;

        sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();
        QueueHandler myHandler = null;
        switch (queueType) {
        case NetFlixQueue.QUEUE_TYPE_DISC:
            myHandler = (AddDiscQueueHandler) new AddDiscQueueHandler();
            break;
        case NetFlixQueue.QUEUE_TYPE_INSTANT:
            myHandler = (AddInstantQueueHandler) new AddInstantQueueHandler();
            break;
        }
        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));

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

        //extra code to catch 502

    } 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) {

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

        reportError(e, lastResponseMessage);
    } finally {
        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("Position:", "" + disc.getPosition());
            parameters.put("Availability:", "" + disc.isAvailable() + ", " + disc.getAvailibilityText());
            parameters.put("URL:", "" + url);
            FlurryAgent.onEvent("AddToQueue502", parameters);

        }
    }
    return result;
}

From source file:net.sf.joost.stx.Processor.java

/**
 * Constructs a new <code>Processor</code> instance by parsing an
 * STX transformation sheet./*w w  w.j  a v a 2 s  . c o  m*/
 * @param reader the parser that is used for reading the transformation
 *               sheet
 * @param src the source for the STX transformation sheet
 * @param pContext a parse context
 * @throws IOException if <code>src</code> couldn't be retrieved
 * @throws SAXException if a SAX parser couldn't be created
 */
public Processor(XMLReader reader, InputSource src, ParseContext pContext) throws IOException, SAXException {
    if (reader == null)
        reader = createXMLReader();

    // create a Parser for parsing the STX transformation sheet
    Parser stxParser = new Parser(pContext);
    reader.setContentHandler(stxParser);
    reader.setErrorHandler(pContext.getErrorHandler());

    // parse the transformation sheet
    reader.parse(src);

    init(stxParser.getTransformNode());

    // re-use this XMLReader for processing
    setParent(reader);
}

From source file:nl.b3p.wms.capabilities.WMSCapabilitiesReader.java

public ServiceProvider getProvider(ByteArrayInputStream in) {

    //Nu kan het service provider object gemaakt en gevuld worden
    serviceProvider = new ServiceProvider();
    XMLReader reader = null;
    try {//from w w  w  .  j  a  v  a  2 s .c  om
        reader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
    } catch (SAXException ex) {

    }

    IgnoreEntityResolver r = new IgnoreEntityResolver();
    reader.setEntityResolver(r);

    reader.setContentHandler(s);
    InputSource is = new InputSource(in);
    is.setEncoding(KBConfiguration.CHARSET);

    try {
        reader.parse(is);
    } catch (Exception ex) {
    }

    return serviceProvider;
}

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 .j av a  2 s .c  o 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);
    }
}