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:org.energyos.espi.common.service.impl.ImportServiceImpl.java

@Override
public void importData(InputStream stream, Long retailCustomerId)
        throws IOException, SAXException, ParserConfigurationException {

    // setup the parser
    JAXBContext context = marshaller.getJaxbContext();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*w w  w .  j a  v  a 2 s.c o m*/
    XMLReader reader = factory.newSAXParser().getXMLReader();

    // EntryProcessor processor = new EntryProcessor(resourceLinker, new
    // ResourceConverter(), resourceService);
    ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService);
    reader.setContentHandler(atomContentHandler);

    // do the parse/import

    try {
        reader.parse(new InputSource(stream));

    } catch (SAXException e) {
        System.out.printf(
                "\nImportServiceImpl -- importData: SAXException\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        throw new SAXException(e.getMessage(), e);

    } catch (Exception e) {
        System.out.printf("\nImportServiceImpl -- importData:\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        e.printStackTrace();

    }
    // context of the import used for linking things up
    // and establishing notifications
    //

    entries = atomContentHandler.getEntries();
    minUpdated = atomContentHandler.getMinUpdated();
    maxUpdated = atomContentHandler.getMaxUpdated();

    // cleanup/end processing
    // 1 - associate to usage points to the right retail customer
    // 2 - make sure authorization/subscriptions have the right URIs
    // 3 - place the imported usagePoints in to the subscriptions
    //
    List<UsagePoint> usagePointList = new ArrayList<UsagePoint>();

    // now perform any associations (to RetailCustomer) and stage the
    // Notifications (if any)

    RetailCustomer retailCustomer = null;

    if (retailCustomerId != null) {
        retailCustomer = retailCustomerService.findById(retailCustomerId);
    }

    Iterator<EntryType> its = entries.iterator();

    while (its.hasNext()) {
        EntryType entry = its.next();
        UsagePoint usagePoint = entry.getContent().getUsagePoint();
        if (usagePoint != null) {

            // see if we already have a retail customer association

            RetailCustomer tempRc = usagePoint.getRetailCustomer();
            if (tempRc != null) {
                // hook it to the retailCustomer
                if (!(tempRc.equals(retailCustomer))) {
                    // we have a conflict in association meaning to Retail
                    // Customers
                    // TODO: resolve how to handle the conflict mentioned
                    // above.
                    // TODO: Only works for a single customer and not
                    // multiple customers
                    retailCustomer = tempRc;
                }
            } else {
                // associate the usagePoint with the Retail Customer
                if (retailCustomer != null) {
                    usagePointService.associateByUUID(retailCustomer, usagePoint.getUUID());
                }
            }
            usagePointList.add(usagePoint);
        }
    }

    // now if we have a retail customer, check for any subscriptions that
    // need associated
    if (retailCustomer != null) {

        Subscription subscription = null;

        // find and iterate across all relevant authorizations
        //
        List<Authorization> authorizationList = authorizationService
                .findAllByRetailCustomerId(retailCustomer.getId());
        for (Authorization authorization : authorizationList) {

            try {
                subscription = subscriptionService.findByAuthorizationId(authorization.getId());
            } catch (Exception e) {
                // an Authorization w/o an associated subscription breaks
                // the propagation chain
                System.out.printf("**** End of Notification Propagation Chain\n");
            }
            if (subscription != null) {
                String resourceUri = authorization.getResourceURI();
                // this is the first time this authorization has been in
                // effect. We must set up the appropriate resource links
                if (resourceUri == null) {
                    ApplicationInformation applicationInformation = authorization.getApplicationInformation();
                    resourceUri = applicationInformation.getDataCustodianResourceEndpoint();
                    resourceUri = resourceUri + "/Batch/Subscription/" + subscription.getId();
                    authorization.setResourceURI(resourceUri);

                    resourceService.merge(authorization);
                }

                // make sure the UsagePoint(s) we just imported are linked
                // up
                // with
                // the Subscription

                for (UsagePoint usagePoint : usagePointList) {
                    boolean addNew = false;
                    for (UsagePoint up : subscription.getUsagePoints()) {
                        if (up.equals(usagePoint))
                            addNew = true;
                    }

                    if (addNew)
                        subscriptionService.addUsagePoint(subscription, usagePoint);

                }
            }
        }
    }
}

From source file:es.rczone.tutoriales.gmaps.MainActivity.java

private void cargarKML(String ruta) {
    try {/*from  w  w  w .ja v  a  2 s.com*/
        InputStream is_kml = getResources().getAssets().open(ruta);

        // create the factory
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // create a parser
        SAXParser parser;
        parser = factory.newSAXParser();

        // create the reader (scanner)
        XMLReader xmlreader = parser.getXMLReader();
        // instantiate our handler
        NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
        // assign our handler
        xmlreader.setContentHandler(navSaxHandler);
        // get our data via the url class
        InputSource is = new InputSource(is_kml);
        // perform the synchronous parse           
        xmlreader.parse(is);

        // get the results - should be a fully populated RSSFeed instance, or null on error
        NavigationDataSet ds = navSaxHandler.getParsedData();

        Placemark place = ds.getPlacemarks().get(0);

        ArrayList<String> lista_coordenadas = place.getCoordinates();

        LatLng locationToCamera = null;

        for (String coordenadas : lista_coordenadas) {
            locationToCamera = draw(coordenadas);
        }

        CameraPosition camPos = new CameraPosition.Builder().target(locationToCamera) //Centramos el mapa en Madrid
                .zoom(9) //Establecemos el zoom en 19
                .build();

        CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);

        map.animateCamera(camUpd3);

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolManager.java

/**
 * Parse a manifest file describing a list of test tool versions.
 *
 * @param file The file to parse.//from   ww  w . j a v  a 2  s  .com
 * @return The parsed list of versions.
 * @throws IOException on error.
 */
private List<TestToolVersion> parseManifest(final File file) throws IOException {

    FileInputStream stream = null;
    try {

        stream = new FileInputStream(file);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));

        ManifestContentHandler handler = new ManifestContentHandler();

        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        reader.parse(new InputSource(buffer));

        return handler.getResult();

    } catch (SAXException exception) {
        throw new IOException("Error parsing DynamoDB Local manifest file", exception);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:com.penbase.dma.Dalyo.HTTPConnection.DmaHttpClient.java

/**
 * Gets the resources of an application/*from  ww  w.  j  a  v a  2s .  c o  m*/
 */
public void getResource(String urlRequest) {
    if (mSendResource) {
        StringBuffer getResources = new StringBuffer("act=getresources");
        getResources.append(urlRequest);
        byte[] bytes = sendPost(getResources.toString());
        SAXParserFactory spFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        try {
            saxParser = spFactory.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            EventsHandler eventsHandler = new EventsHandler(urlRequest);
            xmlReader.setContentHandler(eventsHandler);
            xmlReader.parse(new InputSource(new ByteArrayInputStream(bytes)));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Common.streamToFile(bytes, mResources_XML, false);
    } else {
        SAXParserFactory spFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        try {
            saxParser = spFactory.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            EventsHandler eventsHandler = new EventsHandler(urlRequest);
            xmlReader.setContentHandler(eventsHandler);
            xmlReader.parse(new InputSource(new FileInputStream(new File(mResources_XML))));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.sf.firemox.xml.XmlParser.java

/**
 * @param source//  w w w  .  ja va2 s.co  m
 *          the document source.
 * @return the node of document.
 * @throws IOException
 *           error while opening the stream.
 * @throws SAXException
 *           error while parsing.
 */
public synchronized Node parse(InputSource source) throws IOException, SAXException {
    Handler handler = new Handler();
    XMLReader reader = parser.getXMLReader();
    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);
    reader.setEntityResolver(handler);
    parser.parse(source, handler);
    if (handler.error != null) {
        throw handler.error;
    }
    Node doc = (Node) handler.top.get(0);
    handler.clear();
    return doc;
}

From source file:net.sf.firemox.xml.XmlParser.java

/**
 * Parse InputStream.// www  .j  a va  2 s .  co  m
 * 
 * @param in
 *          the document source.
 * @return the node of document.
 * @throws IOException
 *           error while opening the stream.
 * @throws SAXException
 *           error while parsing.
 */
public synchronized Node parse(InputStream in) throws IOException, SAXException {
    Handler handler = new Handler();
    XMLReader reader = parser.getXMLReader();
    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);
    reader.setEntityResolver(handler);
    parser.parse(new InputSource(in), handler);
    if (handler.error != null) {
        throw handler.error;
    }
    Node doc = (Node) handler.top.get(0);
    handler.clear();
    return doc;
}

From source file:sundroid.code.SundroidActivity.java

/** Called when the activity is first created. ***/
@Override//ww  w.j  av a2  s.com
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius);
    Button cmd_submit = (Button) findViewById(R.id.cmd_submit);

    cmd_submit.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            try {

                ///////////////// Code to get weather conditions for entered place ///////////////////////////////////////////////////
                String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString();
                String queryString = "https://www.google.com/ig/api?weather=" + cityParamString;
                queryString = queryString.replace("#", "");

                /* Parsing the xml file*/
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();

                GoogleWeatherHandler gwh = new GoogleWeatherHandler();
                xr.setContentHandler(gwh);

                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(queryString.replace(" ", "%20"));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httpget, responseHandler);
                ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
                xr.parse(new InputSource(is));
                Log.d("Sundroid", "parse complete");

                WeatherSet ws = gwh.getWeatherSet();

                newupdateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition(),
                        " " + cityParamString, "");

                ///////////////// Code to get weather conditions for entered place ends /////////////////////////////////////////////////// 

                ///////////////// Code to get latitude and longitude using zipcode starts ///////////////////////////////////////////////////

                String latlng_querystring = "http://maps.googleapis.com/maps/api/geocode/xml?address="
                        + cityParamString.replace(" ", "%20") + "&sensor=false";
                URL url_latlng = new URL(latlng_querystring);
                spf = SAXParserFactory.newInstance();
                sp = spf.newSAXParser();

                xr = sp.getXMLReader();
                xmlhandler_latlong xll = new xmlhandler_latlong();
                xr.setContentHandler(xll);
                xr.parse(new InputSource(url_latlng.openStream()));

                Latitude_longitude ll = xll.getLatlng_resultset();
                double selectedLat = ll.getLat_lng_pair().getLat();
                double selectedLng = ll.getLat_lng_pair().getLon();

                ///////////////// Code to get latitude and longitude using zipcode ends ///////////////////////////////////////////////////

                ///////////////// Code to get miles from text box & convert to meters for passing into the api link////////////////////////
                EditText edt = (EditText) findViewById(R.id.edit_miles);
                float miles = Float.valueOf(edt.getText().toString());
                float meters = (float) (miles * 1609.344);

                ///////////////// Code to get miles from text box & convert to meters for passing into the api link ends /////////////////

                ///////////////// Code to pass lat,long and radius and get destinations from places api starts////////// /////////////////
                URL queryString_1 = new URL("https://maps.googleapis.com/maps/api/place/search/xml?location="
                        + Double.toString(selectedLat) + "," + Double.toString(selectedLng) + "&radius="
                        + Float.toString(meters)
                        + "&types=park|types=aquarium|types=point_of_interest|types=establishment|types=museum&sensor=false&key=AIzaSyDmP0SB1SDMkAJ1ebxowsOjpAyeyiwHKQU");
                spf = SAXParserFactory.newInstance();
                sp = spf.newSAXParser();
                xr = sp.getXMLReader();
                xmlhandler_places xhp = new xmlhandler_places();
                xr.setContentHandler(xhp);
                xr.parse(new InputSource(queryString_1.openStream()));
                int arraysize = xhp.getVicinity_List().size();
                String[] place = new String[25];
                String[] place_name = new String[25];
                Double[] lat_pt = new Double[25];
                Double[] lng_pt = new Double[25];
                int i;
                //Getting name and vicinity tags from the xml file//
                for (i = 0; i < arraysize; i++) {
                    place[i] = xhp.getVicinity_List().get(i);
                    place_name[i] = xhp.getPlacename_List().get(i);
                    lat_pt[i] = xhp.getLatlist().get(i);
                    lng_pt[i] = xhp.getLonglist().get(i);
                    System.out.println("long -" + lng_pt[i]);
                    place[i] = place[i].replace("#", "");

                }

                ///////////////// Code to pass lat,long and radius and get destinations from places api ends////////// /////////////////

                //////////////////////while loop for getting top 5 from the array////////////////////////////////////////////////

                int count = 0;
                int while_ctr = 0;
                String str_weathercondition;
                str_weathercondition = "";
                WeatherCurrentCondition reftemp;
                //Places to visit if none of places in the given radius are sunny/clear/partly cloudy
                String[] rainy_place = { "Indoor Mall", "Watch a Movie", "Go to a Restaurant", "Shopping!" };
                double theDistance = 0;
                String str_dist = "";
                while (count < 5) {
                    //Checking if xml vicinity value is empty
                    while (place[while_ctr] == null || place[while_ctr].length() < 2) {
                        while_ctr = while_ctr + 1;
                    }
                    //First search for places that are sunny or clear 
                    if (while_ctr < i - 1) {
                        queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr];
                        System.out.println("In while loop - " + queryString);
                        theDistance = (Math.sin(Math.toRadians(selectedLat))
                                * Math.sin(Math.toRadians(lat_pt[while_ctr]))
                                + Math.cos(Math.toRadians(selectedLat))
                                        * Math.cos(Math.toRadians(lat_pt[while_ctr]))
                                        * Math.cos(Math.toRadians(selectedLng - lng_pt[while_ctr])));
                        str_dist = new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09).intValue()
                                + " miles";
                        System.out.println(str_dist);
                        spf = SAXParserFactory.newInstance();
                        sp = spf.newSAXParser();

                        xr = sp.getXMLReader();

                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);
                        httpclient = new DefaultHttpClient();
                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        if (gwh.isIn_error_information()) {
                            System.out.println("Error Info flag set");
                        } else {
                            ws = gwh.getWeatherSet();

                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            //         Check if the condition is sunny or partly cloudy
                            if (str_weathercondition.equals("Sunny")
                                    || str_weathercondition.equals("Mostly Sunny")
                                    || str_weathercondition.equals("Clear")) {
                                System.out.println("Sunny Loop");

                                //  Increment the count 
                                ++count;

                                //   Disply the place on the widget 
                                if (count == 1) {
                                    newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 2) {
                                    newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 3) {
                                    newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 4) {
                                    newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 5) {
                                    newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else {
                                }
                            }
                        }
                    }

                    //  If Five sunny places not found then search for partly cloudy places 

                    else if (while_ctr >= i && while_ctr < i * 2) {
                        queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr - i];
                        queryString = queryString.replace("  ", " ");

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

                        // Get the XMLReader of the SAXParser we created. 
                        xr = sp.getXMLReader();

                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);

                        // Use HTTPClient to deal with the URL  
                        httpclient = new DefaultHttpClient();
                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        Log.d(DEBUG_TAG, "parse complete");

                        if (gwh.isIn_error_information()) {
                        } else {
                            ws = gwh.getWeatherSet();
                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            //    Check if the condition is sunny or partly cloudy
                            if (str_weathercondition.equals("Partly Cloudy")) {

                                count = count + 1;

                                //  Display the place 
                                if (count == 1) {
                                    newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 2) {
                                    newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 3) {
                                    newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 4) {
                                    newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 5) {
                                    newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else {
                                }
                            }
                        }
                    }
                    ////////////////////////////////  Give suggestions for a rainy day 
                    else {
                        queryString = "https://www.google.com/ig/api?weather=" + cityParamString;
                        queryString = queryString.replace("#", "");

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

                        // Get the XMLReader of the SAXParser we created. 
                        xr = sp.getXMLReader();
                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);

                        httpclient = new DefaultHttpClient();

                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        // create a response handler 
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        if (gwh.isIn_error_information()) {
                        }

                        else {
                            ws = gwh.getWeatherSet();

                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            if (count == 0) {
                                newupdateWeatherInfoView(R.id.weather_1, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], "");
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 1) {
                                newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], "");
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[0], "");
                            } else if (count == 2) {
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 3) {
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 4) {
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else {
                            }
                            count = 5;
                        }
                        count = 5;
                    }
                    while_ctr++;
                }

                /////////////Closing the soft keypad////////////////
                InputMethodManager iMethodMgr = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                iMethodMgr.hideSoftInputFromWindow(edt.getWindowToken(), 0);

            } catch (Exception e) {
                resetWeatherInfoViews();
                Log.e(DEBUG_TAG, "WeatherQueryError", e);
            }
        }
    });
}

From source file:SAXTreeValidator.java

/**
 * <p>This handles building the Swing UI tree.</p>
 *
 * @param treeModel Swing component to build upon.
 * @param base tree node to build on./*  w w  w  . j  av  a2 s . c o m*/
 * @param xmlURI URI to build XML document from.
 * @throws <code>IOException</code> - when reading the XML URI fails.
 * @throws <code>SAXException</code> - when errors in parsing occur.
 */
public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode base, String xmlURI)
        throws IOException, SAXException {

    // Create instances needed for parsing
    XMLReader reader = XMLReaderFactory.createXMLReader(vendorParserClass);
    ContentHandler jTreeContentHandler = new JValidatorContentHandler(treeModel, base);
    ErrorHandler jTreeErrorHandler = new JValidatorErrorHandler();

    // Register content handler
    reader.setContentHandler(jTreeContentHandler);

    // Register error handler
    reader.setErrorHandler(jTreeErrorHandler);

    // Turn on validation
    reader.setFeature("http://xml.org/sax/features/validation", true);
    reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    // Parse
    InputSource inputSource = new InputSource(xmlURI);
    reader.parse(inputSource);
}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {/*from  w ww .  j  a v  a 2s  . c  o  m*/
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}