Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:com.zyz.mobile.book.UserBookData.java

/**
 * open the info xml file. create one if it cannot be found
 *///from ww  w .ja  va 2  s. c  o  m
public boolean parse() {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader reader = sp.getXMLReader();
        reader.setContentHandler(this);
        reader.parse(new InputSource(new FileReader(mInfoFile)));
    } catch (Exception e) {
        // constructor doesn't check for validity of the file
        // catch all exceptions here
        Log.e(TAG, "Failed to parse xml file?");
        return false;
    }
    return true;
}

From source file:eionet.gdem.validation.ValidationService.java

/**
/**/*from  w ww .java 2 s . c  o m*/
 * Validate XML. If schema is null, then read the schema or DTD from the header of XML. If schema or DTD is defined, then ignore
 * the defined schema or DTD.
 *
 * @param srcStream XML file as InputStream to be validated.
 * @param schema XML Schema URL.
 * @return Validation result as HTML snippet.
 * @throws DCMException in case of unknnown system error.
 */
public String validateSchema(InputStream srcStream, String schema) throws DCMException {

    String result = "";
    boolean isDTD = false;
    boolean isBlocker = false;

    if (Utils.isNullStr(schema)) {
        schema = null;
    }

    try {

        SAXParserFactory spfact = SAXParserFactory.newInstance();
        SAXParser parser = spfact.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        reader.setErrorHandler(errHandler);
        XmlconvCatalogResolver catalogResolver = new XmlconvCatalogResolver();
        reader.setEntityResolver(catalogResolver);

        // make parser to validate
        reader.setFeature("http://xml.org/sax/features/validation", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        reader.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);

        InputAnalyser inputAnalyser = new InputAnalyser();
        inputAnalyser.parseXML(uriXml);
        String namespace = inputAnalyser.getSchemaNamespace();

        // if schema is not in the parameter, then sniff it from the header of xml
        if (schema == null) {
            schema = inputAnalyser.getSchemaOrDTD();
            isDTD = inputAnalyser.isDTD();
        } else {
            // if the given schema ends with dtd, then don't do schema validation
            isDTD = schema.endsWith("dtd");
        }

        // schema is already given as a parameter. Read the default namespace from XML file and set external schema.
        if (schema != null) {
            if (!isDTD) {
                if (Utils.isNullStr(namespace)) {
                    // XML file does not have default namespace
                    setNoNamespaceSchemaProperty(reader, schema);
                } else {
                    setNamespaceSchemaProperty(reader, namespace, schema);
                }
            } else {
                // validate against DTD
                setLocalSchemaUrl(schema);
                LocalEntityResolver localResolver = new LocalEntityResolver(schema, getValidatedSchema());
                reader.setEntityResolver(localResolver);
            }
        } else {
            return validationFeedback.formatFeedbackText(
                    "Could not validate XML file. Unable to locate XML Schema reference.",
                    QAFeedbackType.WARNING, isBlocker);
        }
        // if schema is not available, then do not parse the XML and throw error
        if (!Utils.resourceExists(getValidatedSchema())) {
            return validationFeedback.formatFeedbackText(
                    "Failed to read schema document from the following URL: " + getValidatedSchema(),
                    QAFeedbackType.ERROR, isBlocker);
        }
        Schema schemaObj = schemaManager.getSchema(getOriginalSchema());
        if (schemaObj != null) {
            isBlocker = schemaObj.isBlocker();
        }
        validationFeedback.setSchema(getOriginalSchema());
        InputSource is = new InputSource(srcStream);
        reader.parse(is);

    } catch (SAXParseException se) {
        return validationFeedback.formatFeedbackText("Document is not well-formed. Column: "
                + se.getColumnNumber() + "; line:" + se.getLineNumber() + "; " + se.getMessage(),
                QAFeedbackType.ERROR, isBlocker);
    } catch (IOException ioe) {
        return validationFeedback.formatFeedbackText(
                "Due to an IOException, the parser could not check the document. " + ioe.getMessage(),
                QAFeedbackType.ERROR, isBlocker);
    } catch (Exception e) {
        Exception se = e;
        if (e instanceof SAXException) {
            se = ((SAXException) e).getException();
        }
        if (se != null) {
            se.printStackTrace(System.err);
        } else {
            e.printStackTrace(System.err);
        }
        return validationFeedback.formatFeedbackText(
                "The parser could not check the document. " + e.getMessage(), QAFeedbackType.ERROR, isBlocker);
    }

    validationFeedback.setValidationErrors(getErrorList());
    result = validationFeedback.formatFeedbackText(isBlocker);

    // validation post-processor
    QAResultPostProcessor postProcessor = new QAResultPostProcessor();
    result = postProcessor.processQAResult(result, schema);
    warningMessage = postProcessor.getWarningMessage(schema);

    return result;
}

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);//from 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:com.magicmod.mmweather.engine.YahooWeatherProvider.java

@Override
public void refreshData(String id, String localizedCityName, boolean metricUnits) {
    mCityId = id;/*from  w  w w.  j  a  v a2s . co  m*/
    mLocalizedCityName = localizedCityName;
    mMetricUnits = metricUnits;

    String url = String.format(URL_WEATHER, id, metricUnits ? "c" : "f");
    String response = HttpRetriever.retrieve(url);

    if (response == null) {
        mWeatherInfo = null;
        return;
    }

    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        StringReader reader = new StringReader(response);
        WeatherHandler handler = new WeatherHandler();
        parser.parse(new InputSource(reader), handler);

        if (handler.isComplete()) {
            // There are cases where the current condition is unknown, but the forecast
            // is not - using the (inaccurate) forecast is probably better than showing
            // the question mark
            if (handler.conditionCode.equals(3200)) {
                handler.condition = handler.forecasts.get(0).getCondition();
                handler.conditionCode = handler.forecasts.get(0).getConditionCode();
            }
            ArrayList<DayForecast> forecasts = new ArrayList<WeatherInfo.DayForecast>();

            long time = System.currentTimeMillis();
            for (DayForecast forecast : handler.forecasts) {
                if (forecast.getDate().equals(handler.date)) {
                    forecast.setCondition(handler.condition);
                    forecast.setConditionCode(handler.conditionCode);
                    forecast.setHumidity(handler.humidity);
                    forecast.setSunRaise(handler.sunrise);
                    forecast.setSunSet(handler.sunset);
                    forecast.setTemperature(handler.temperature);
                    forecast.setTempUnit(handler.temperatureUnit);
                    forecast.setWindSpeed(handler.windSpeed);
                    forecast.setWindDirection(handler.windDirection);
                    forecast.setWindSpeedUnit(handler.speedUnit);
                }
                if (localizedCityName != null) {
                    forecast.setCity(localizedCityName);
                }
                forecast.setSynctimestamp(String.valueOf(time));
                forecasts.add(forecast);
            }
            mWeatherInfo = new WeatherInfo(forecasts);
            Log.d(TAG, "Weather updated: " + mWeatherInfo);
        } else {
            Log.w(TAG, "Received incomplete weather XML (id=" + id + ")");
            mWeatherInfo = null;
        }
    } catch (ParserConfigurationException e) {
        Log.e(TAG, "Could not create XML parser", e);
        mWeatherInfo = null;
    } catch (SAXException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
        mWeatherInfo = null;
    } catch (IOException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
        mWeatherInfo = null;
    }
    if (mWeatherDataChangedListener != null)
        mWeatherDataChangedListener.onDataChanged();
}

From source file:com.sshtools.daemon.configuration.ServerConfiguration.java

/**
 *
 *
 * @param in// w w w . ja  va 2s . c o  m
 *
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws IOException
 */
public void reload(InputStream in) throws SAXException, ParserConfigurationException, IOException {
    allowedSubsystems.clear();
    serverHostKeys.clear();
    allowedAuthentications.clear();
    requiredAuthentications.clear();
    commandPort = 12222;
    port = 22;
    listenAddress = "0.0.0.0";
    maxConnections = 10;
    maxAuthentications = 5;
    terminalProvider = "";
    authorizationFile = "authorization.xml";
    userConfigDirectory = "%D/.ssh2";
    authenticationBanner = "";
    allowTcpForwarding = true;
    currentElement = null;

    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    saxParser.parse(in, this);
}

From source file:de.betterform.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *//*  www .j a va2  s .c  o  m*/
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation",
                    schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

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/*from w  w  w .  ja v a 2 s  .  com*/
        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.apache.uima.ruta.resource.TreeWordList.java

public void readXML(InputStream stream, String encoding) throws IOException {
    try {/*  w w w .  ja  va  2s . c  o m*/
        InputStream is = new BufferedInputStream(stream); // adds mark/reset support
        boolean isXml = MultiTreeWordListPersistence.isSniffedXmlContentType(is);
        if (!isXml) { // MTWL is encoded
            is = new ZipInputStream(is);
            ((ZipInputStream) is).getNextEntry(); // zip must contain a single entry
        }
        InputStreamReader streamReader = new InputStreamReader(is, encoding);
        this.root = new TextNode();
        XMLEventHandler handler = new XMLEventHandler(root);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        // XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        reader.parse(new InputSource(streamReader));
    } catch (SAXParseException spe) {
        StringBuffer sb = new StringBuffer(spe.toString());
        sb.append("\n  Line number: " + spe.getLineNumber());
        sb.append("\n Column number: " + spe.getColumnNumber());
        sb.append("\n Public ID: " + spe.getPublicId());
        sb.append("\n System ID: " + spe.getSystemId() + "\n");
        System.out.println(sb.toString());
    } catch (SAXException se) {
        System.out.println("loadDOM threw " + se);
        se.printStackTrace(System.out);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:com.wlcg.aroundme.cc.weather.YahooWeatherProvider.java

@Override
public WeatherInfo getWeatherInfo(String id, String localizedCityName, boolean metricUnits) {
    mCityId = id;/*  w  w w .  j  a v  a 2 s. c om*/
    mLocalizedCityName = localizedCityName;
    mMetricUnits = metricUnits;

    String url = String.format(URL_WEATHER, id, metricUnits ? "c" : "f");
    Log.d(TAG, "URL is => " + url);
    String response = HttpRetriever.retrieve(url);

    if (response == null) {
        //mWeatherInfo = null;
        return null;
    }

    WeatherInfo info = null;

    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        StringReader reader = new StringReader(response);
        WeatherHandler handler = new WeatherHandler();
        parser.parse(new InputSource(reader), handler);

        if (handler.isComplete()) {
            // There are cases where the current condition is unknown, but the forecast
            // is not - using the (inaccurate) forecast is probably better than showing
            // the question mark
            if (handler.conditionCode.equals(3200)) {
                handler.condition = handler.forecasts.get(0).getCondition();
                handler.conditionCode = handler.forecasts.get(0).getConditionCode();
            }
            ArrayList<DayForecast> forecasts = new ArrayList<WeatherInfo.DayForecast>();

            String time = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date());
            for (DayForecast forecast : handler.forecasts) {
                if (forecast.getDate().equals(handler.date)) {
                    forecast.setCondition(handler.condition);
                    forecast.setConditionCode(handler.conditionCode);
                    forecast.setHumidity(handler.humidity);
                    forecast.setSunRaise(handler.sunrise);
                    forecast.setSunSet(handler.sunset);
                    forecast.setTemperature(handler.temperature);
                    forecast.setTempUnit(handler.temperatureUnit);
                    forecast.setWindSpeed(handler.windSpeed);
                    forecast.setWindDirection(handler.windDirection);
                    forecast.setWindSpeedUnit(handler.speedUnit);
                }
                if (localizedCityName != null) {
                    forecast.setCity(localizedCityName);
                }
                forecast.setSynctimestamp(time);
                forecasts.add(forecast);

                //Log.d(TAG, "Weather forecast is => " + forecast);
            }
            //mWeatherInfo = new WeatherInfo(forecasts);
            info = new WeatherInfo(forecasts);
            Log.d(TAG, "Weather updated: " + info);
        } else {
            Log.w(TAG, "Received incomplete weather XML (id=" + id + ")");
            //mWeatherInfo = null;
            info = null;
        }
    } catch (ParserConfigurationException e) {
        Log.e(TAG, "Could not create XML parser", e);
        //mWeatherInfo = null;
        info = null;
    } catch (SAXException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
        //mWeatherInfo = null;
        info = null;
    } catch (IOException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
        //mWeatherInfo = null;
        info = null;
    }
    if (mWeatherDataChangedListener != null)
        mWeatherDataChangedListener.onDataChanged();
    return info;
}