Example usage for javax.xml.parsers SAXParserFactory newInstance

List of usage examples for javax.xml.parsers SAXParserFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newInstance.

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:com.wart.magister.SelectSchoolActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select_school);
    // Display the Actionbar arrow
    getActionBar().setDisplayHomeAsUpEnabled(false);

    ((EditText) findViewById(R.id.select_school_edittext)).addTextChangedListener(new TextWatcher() {
        @Override/* w ww  .ja  v  a  2  s .co m*/
        public void afterTextChanged(Editable e) {
            if (e.length() > 0) {
                showProgress(true);
                if (mRetrieveSchoolsRequest != null && !mRetrieveSchoolsRequest.isFinished())
                    mRetrieveSchoolsRequest.cancel(true);
                mRetrieveSchoolsRequest = Global.AsyncHttpClient.get(
                        "http://app.schoolmaster.nl/schoolLicentieService.asmx/Search?term="
                                + e.toString().replace(" ", "%20").toLowerCase().trim(),
                        new TextHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, String responseBody) {
                                try {
                                    SAXParserFactory factory = SAXParserFactory.newInstance();
                                    SAXParser saxParser = factory.newSAXParser();

                                    mRetrievedSchools.clear();
                                    DefaultHandler handler = new DefaultHandler() {
                                        private String currentValue;
                                        private School currentSchool;

                                        @Override
                                        public void characters(char ch[], int start, int length)
                                                throws SAXException {
                                            currentValue = new String(ch, start, length);
                                        }

                                        @Override
                                        public void endElement(String uri, String localName, String qName)
                                                throws SAXException {
                                            if (qName.equalsIgnoreCase("medius"))
                                                currentSchool.URL = currentValue;
                                            else if (qName.equalsIgnoreCase("licentie"))
                                                currentSchool.License = currentValue;
                                        }

                                        @Override
                                        public void startElement(String uri, String localName, String qName,
                                                Attributes attributes) throws SAXException {
                                            if (qName.equalsIgnoreCase("school")) {
                                                currentSchool = new School();
                                                mRetrievedSchools.add(currentSchool);
                                            }
                                        }
                                    };
                                    saxParser.parse(new InputSource(new StringReader(responseBody)), handler);

                                    String[] names = new String[mRetrievedSchools.size()];
                                    for (int i = 0; i < mRetrievedSchools.size(); i++)
                                        names[i] = mRetrievedSchools.get(i).License;

                                    mSchoolsList.setAdapter(new ArrayAdapter<String>(SelectSchoolActivity.this,
                                            android.R.layout.simple_list_item_1, names));
                                } catch (Exception e) {
                                    Log.e(TAG, "Error in onSuccess", e);
                                }
                            }

                            @Override
                            public void onFailure(String responseBody, Throwable error) {
                                mSchoolsList.setAdapter(null);
                                Log.e(TAG, "Retrieving schools failed", error);
                            }

                            @Override
                            public void onFinish() {
                                showProgress(false);
                            }
                        });
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    mSchoolsList = (ListView) findViewById(R.id.select_school_listview);
    mSchoolsList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mTestMediusRequest != null && !mTestMediusRequest.isFinished())
                mTestMediusRequest.cancel(true);
            ((TextView) findViewById(R.id.select_school_status_message)).setText("Testing school...");
            showProgress(true);

            Data.set(Data.MEDIUSURL, Data.buildMediusUrl(mRetrievedSchools.get(position).URL));
            Log.v(TAG, "posting to " + Data.getString(Data.MEDIUSURL));
            byte[] request = new byte[54];
            request[0] = 0x52;
            request[1] = 0x4f;
            request[2] = 49;
            request[3] = 48;
            request[4] = 55;
            request[12] = 95;
            request[13] = -38;
            request[14] = -109;
            request[15] = 13;
            request[16] = -14;
            request[17] = 92;
            request[18] = 7;
            request[19] = 86;
            request[20] = -77;
            request[21] = -23;
            request[22] = 9;
            request[23] = 22;
            request[24] = 71;
            request[25] = -53;
            request[26] = -81;
            request[27] = 45;
            request[28] = 5;
            request[32] = 76;
            request[33] = 111;
            request[34] = 103;
            request[35] = 105;
            request[36] = 110;
            request[37] = 13;
            request[41] = 71;
            request[42] = 101;
            request[43] = 116;
            request[44] = 83;
            request[45] = 99;
            request[46] = 104;
            request[47] = 111;
            request[48] = 111;
            request[49] = 108;
            request[50] = 78;
            request[51] = 97;
            request[52] = 109;
            request[53] = 101;

            Log.i(TAG, "Testing the url...");
            mTestMediusRequest = Global.AsyncHttpClient.post(SelectSchoolActivity.this,
                    Data.getString(Data.MEDIUSURL), new ByteArrayEntity(request), "text/html",
                    new BinaryHttpResponseHandler(new String[] { "text/html" }) {
                        @Override
                        public void onSuccess(byte[] binaryData) {

                            if (binaryData != null) {
                                Log.i(TAG, "Received " + binaryData.length + " bytes of data");
                                Serializer s = new Serializer(binaryData);
                                try {
                                    if (s.readROHeader(null, "login", "getschoolname")) {
                                        Data.set(Data.LICENSE, s.readString());
                                        MediusCall.setLicense(Data.getString(Data.LICENSE));
                                    } else
                                        Log.e(TAG, "Geblokkeerd door webserver");
                                } catch (Exception e) {
                                    Log.e(TAG, "Error in TestMedius.onSuccess", e);
                                }
                                Log.i(TAG, "Succesfully tested the medius");
                                SelectSchoolActivity.this.startActivity(
                                        new Intent(SelectSchoolActivity.this, LoginActivity.class));
                            } else
                                Log.e(TAG, "TestMedius timed out");
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] binaryData,
                                Throwable error) {
                            Log.e(TAG, "Error in TestMedius.onFaillure", error);
                        }

                        @Override
                        public void onFinish() {
                            showProgress(false);
                        }
                    });
        }
    });
    mSearchLayout = (LinearLayout) findViewById(R.id.select_school_status_layout);
}

From source file:org.gots.weather.provider.google.GoogleWeatherTask.java

@Override
protected WeatherConditionInterface doInBackground(Object... arg0) {
    if (force || ws == null) {

        try {//from  w w w  .  ja va  2  s .  c o  m

            // android.os.Debug.waitForDebugger();
            /*************/

            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url.toURI());

            // create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responseBody = httpclient.execute(httpget, responseHandler);
            // Log.d(DEBUG_TAG, "response from httpclient:n "+responseBody);

            ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());

            /* Get a SAXParser from the SAXPArserFactory. */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

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

            /* Create a new ContentHandler and apply it to the XML-Reader */
            GoogleWeatherHandler gwh = new GoogleWeatherHandler();
            xr.setContentHandler(gwh);

            // InputSource is = new InputSource(url.openStream());
            /* Parse the xml-data our URL-call returned. */
            xr.parse(new InputSource(is));

            /* Our Handler now provides the parsed weather-data to us. */
            ws = gwh.getWeatherSet();
        } catch (Exception e) {
            Log.e("WeatherManager", "WeatherQueryError", e);

        }
        force = false;
    }
    Calendar requestCalendar = Calendar.getInstance();
    requestCalendar.setTime(requestedDay);
    if (ws == null)
        return new WeatherCondition(requestedDay);
    else if (requestCalendar.get(Calendar.DAY_OF_YEAR) == Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
        return ws.getWeatherCurrentCondition();
    else if (requestCalendar.get(Calendar.DAY_OF_YEAR) > Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
        return ws.getWeatherForecastConditions().get(
                requestCalendar.get(Calendar.DAY_OF_YEAR) - Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
    return new WeatherCondition(requestedDay);

}

From source file:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {//from w  ww  .  j av a2s .  com
        ZipInputStream zipIn = new ZipInputStream(template);
        ZipOutputStream zipOut = new ZipOutputStream(out);

        ZipEntry entry;

        Map<String, byte[]> sheets = new HashMap<String, byte[]>();

        while ((entry = zipIn.getNextEntry()) != null) {

            String name = entry.getName();

            if (name.startsWith("xl/sharedStrings.xml")) {

                byte[] bytes = IOUtils.toByteArray(zipIn);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(bytes);

                sharedStrings = processSharedStrings(bytes);

            } else if (name.startsWith("xl/worksheets/sheet")) {
                byte[] bytes = IOUtils.toByteArray(zipIn);
                sheets.put(name, bytes);
            } else if (name.equals("xl/calcChain.xml")) {
                // skip this file, let excel recreate it
            } else if (name.equals("xl/workbook.xml")) {
                zipOut.putNextEntry(new ZipEntry(name));

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Writer writer = new OutputStreamWriter(zipOut, "UTF-8");

                byte[] bytes = IOUtils.toByteArray(zipIn);
                saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer));

                writer.flush();
            } else {
                zipOut.putNextEntry(new ZipEntry(name));
                IOUtils.copy(zipIn, zipOut);
            }

        }

        for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) {
            String name = sheetEntry.getKey();

            byte[] bytes = sheetEntry.getValue();
            zipOut.putNextEntry(new ZipEntry(name));
            processSheet(bytes, zipOut, visitor);
        }

        zipIn.close();
        template.close();

        zipOut.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:edu.psu.citeseerx.updates.external.metadata.ACMMetadataUpdater.java

public void updateACM() {
    try {/*from w w w . j  a v  a 2  s .c om*/
        // Get the SAX factory.
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // Neither we want validation nor namespaces.
        factory.setNamespaceAware(false);
        factory.setValidating(true);

        SAXParser parser = factory.newSAXParser();

        /*xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", 
            false);*/

        parser.parse(ACMDataFile, acmHandler);
    } catch (ParserConfigurationException e) {
        logger.error("The underlaying parser doesn't support the " + "requested feature", e);
    } catch (SAXException e) {
        logger.error("Error", e);
    } catch (IOException e) {
        logger.error("A parsing error has occurred: " + ACMDataFile, e);
    }
}

From source file:Main.java

/**
 * Creates a SAX parser./*from  www .  ja va2  s  . com*/
 *
 * <p>
 * See {@link #parse} for hints on setting an entity resolver.
 *
 * @param validate       if true, a validating parser is returned
 * @param namespaceAware if true, a namespace aware parser is returned
 *
 * @throws FactoryConfigurationError Application developers should never
 *                                   need to directly catch errors of this
 *                                   type.
 * @throws SAXException              if a parser fulfilling given parameters
 *                                   can not be created
 *
 * @return XMLReader configured according to passed parameters
 */
public static synchronized XMLReader createXMLReader(boolean validate, boolean namespaceAware)
        throws SAXException {
    SAXParserFactory factory = saxes[validate ? 0 : 1][namespaceAware ? 0 : 1];
    if (factory == null) {
        try {
            factory = SAXParserFactory.newInstance();
        } catch (FactoryConfigurationError err) {
            throw err;
        }
        factory.setValidating(validate);
        factory.setNamespaceAware(namespaceAware);
        saxes[validate ? 0 : 1][namespaceAware ? 0 : 1] = factory;
    }

    try {
        return factory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException("Cannot create parser satisfying configuration parameters", ex); // NOI18N
    }
}

From source file:com.cloudera.recordbreaker.analyzer.XMLSchemaDescriptor.java

void computeSchema() throws IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = null;/*  w  w  w . ja  v a  2s  .  c o  m*/
    // Unfortunately, validation is often not possible
    factory.setValidating(false);

    try {
        // The XMLProcessor builds up a tree of tags
        XMLProcessor xp = new XMLProcessor();
        parser = factory.newSAXParser();
        parser.parse(dd.getRawBytes(), xp);

        // Grab the root tag
        this.rootTag = xp.getRoot();

        // Once the tree is built, we:
        // a) Find the correct repetition node (and throws out 'bad' repeats)
        // b) Flatten hierarchies of subfields into a single layer, so it's suitable
        //    for relational-style handling
        // c) Build an overall schema object that can summarize every expected
        //    object, even if the objects' individual schemas differ somewhat
        this.rootTag.completeTree();
    } catch (SAXException saxe) {
        throw new IOException(saxe.toString());
    } catch (ParserConfigurationException pcee) {
        throw new IOException(pcee.toString());
    }
}

From source file:com.inferiorhumanorgans.WayToGo.Agency.BART.Prediction.XMLTask.java

@Override
protected Void doInBackground(BARTAgency... someAgencies) {
    super.doInBackground(someAgencies);
    theListener.startPredictionFetch();// w  ww. j  a  va  2 s  . c  o m
    Log.d(LOG_NAME, "Trying to get Predictions.");

    InputStream content = null;
    ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient hc = new DefaultHttpClient(connman, params);

    String theURL = BART_URL + BARTAgency.API_KEY + "&orig=" + theStationTag;

    Log.i(LOG_NAME, "Fetching from: " + theURL);
    HttpGet getRequest = new HttpGet(theURL);
    try {
        content = hc.execute(getRequest).getEntity().getContent();
    } catch (ClientProtocolException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    }
    Log.d(LOG_NAME, "Put the BART predictions in the background.");

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

        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(dataHandler);

        xr.parse(new InputSource(content));

    } catch (ParserConfigurationException pce) {
        Log.e(LOG_NAME + " SAX XML", "sax parse error", pce);
    } catch (AbortXMLParsingException abrt) {
        Log.d(LOG_NAME + " AsyncXML", "Cancelled!!!!!");
    } catch (SAXException se) {
        Log.e(LOG_NAME + " SAX XML", "sax error", se);
    } catch (IOException ioe) {
        Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe);
    }
    Log.d(LOG_NAME + " SAX XML", "Done parsing BART station XML");
    return null;
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * @param service//from   w  w w  .  j a  va 2s .c  o  m
 *          Service-ID
 * @return Data of specific service
 */
private TreeMap<String, String> getServiceDataBouquets(String service) {
    if (!mConfig.hasValidAddress()) {
        return null;
    }
    try {
        InputStream stream = openStreamForLocalUrl("/web/getservices?bRef=" + service);
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxHandler handler = new DreamboxHandler();
        saxParser.parse(stream, handler);
        return handler.getData();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.vionto.vithesaurus.wikipedia.CommonsAudioDumper.java

private void run(InputStream is) throws IOException, SAXException, ParserConfigurationException {
    CommonsPageHandler handler = new CommonsPageHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.getXMLReader().setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
            false);//from www . ja va 2  s. c om
    System.out.println("SET NAMES utf8;");
    saxParser.parse(is, handler);
    System.err.println("Exported: " + handler.exported);
    System.err.println("Skipped: " + handler.skipped);
    System.err.println("Skipped " + handler.noLicense + " because of missing/undetected license");
}

From source file:eionet.cr.util.xml.XmlAnalysis.java

/**
 *
 * @param inputStream//from w  w  w.  j  a  v a 2s  . c o  m
 * @return
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws GDEMException
 * @throws SAXException
 * @throws IOException
 */
public void parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {

    // set up the parser and reader
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    // turn off validation against schema or dtd (we only need the document to be well-formed XML)
    parserFactory.setValidating(false);
    reader.setFeature("http://xml.org/sax/features/validation", false);
    reader.setFeature("http://apache.org/xml/features/validation/schema", false);
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    reader.setFeature("http://xml.org/sax/features/namespaces", true);

    // turn on dtd handling
    doctypeReader = new SAXDoctypeReader();
    try {
        parser.setProperty("http://xml.org/sax/properties/lexical-handler", doctypeReader);
    } catch (SAXNotRecognizedException e) {
        logger.warn("Installed XML parser does not provide lexical events", e);
    } catch (SAXNotSupportedException e) {
        logger.warn("Cannot turn on comment processing here", e);
    }

    // set the handler and do the parsing
    handler = new Handler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(inputStream));
    } catch (SAXException e) {
        Exception ee = e.getException();
        if (ee == null || !(ee instanceof CRException))
            throw e;
    }
}