Example usage for javax.xml.parsers SAXParser parse

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

Introduction

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

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:es.ehu.si.ixa.pipe.convert.Convert.java

/**
 * Process the ancora constituent XML annotation into Penn Treebank bracketing
 * style./* w  w w.  ja  v a2s.com*/
 * 
 * @param inXML
 *          the ancora xml constituent document
 * @return the ancora trees in penn treebank one line format
 * @throws IOException
 *           if io exception
 */
public String ancora2treebank(File inXML) throws IOException {
    String filteredTrees = null;
    if (inXML.isFile()) {

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            AncoraTreebank ancoraParser = new AncoraTreebank();
            saxParser.parse(inXML, ancoraParser);
            String trees = ancoraParser.getTrees();
            // remove empty trees created by "missing" and "elliptic" attributes
            filteredTrees = trees.replaceAll("\\(\\SN\\)", "");
            // format correctly closing brackets
            filteredTrees = filteredTrees.replace(") )", "))");
            // remove double spaces
            filteredTrees = filteredTrees.replaceAll("  ", " ");
            // remove empty sentences created by <sentence title="yes"> elements
            filteredTrees = filteredTrees.replaceAll("\\(SENTENCE \\)\n", "");
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        System.out.println("Please choose a valid file as input");
    }
    return filteredTrees;
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * @throws IOException//from   w  w w  .  j  a  v a2  s .c om
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private static void initializeSchemas() throws IOException, SAXException, ParserConfigurationException {
    File[] schemaFiles = ResourceUtil.getFilenamesInDirectory("xsd/", TestBase.class.getClassLoader());
    schemas = new HashMap<String, Schema>();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (File file : schemaFiles) {
        try {
            Schema schema = sf.newSchema(file);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                private String nameSpace = null;
                private boolean found = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if (!found) {
                        String tagName = null;
                        int ix = qName.indexOf(":");
                        if (ix >= 0) {
                            tagName = qName.substring(ix + 1);
                        } else {
                            tagName = qName;
                        }
                        if ("schema".equals(tagName)) {
                            nameSpace = attributes.getValue("targetNamespace");
                            found = true;
                        }
                    }
                }

                public String toString() {
                    return nameSpace;
                }
            };
            parser.parse(file, handler);
            if (handler.toString() != null) {
                schemas.put(handler.toString(), schema);
            } else {
                logger.warn("Error reading xml schema: " + file);
            }

        } catch (Exception e) {
            logger.warn("Invalid xml schema " + file);
            logger.debug("Stacktrace: ", e);
        }

    }
}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

static public void parseUrlOutput(String path, SAXParserFactory factory, DefaultHandler handler) {
    SAXParser parser;
    URL url;//from www  .j  a v a2  s .com

    try {
        url = new URL(path);
        parser = factory.newSAXParser();
        parser.parse(Utils.getInputStream(url), handler);
        // Dont bother catching general exceptions, they will be caught by the caller.
    } catch (MalformedURLException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (ParserConfigurationException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (SAXException e) {
        String s = e.getMessage(); // "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    } catch (java.io.IOException e) {
        String s = "unknown";
        try {
            s = e.getMessage();
        } catch (Exception e2) {
        }
        ;
        Logger.logError(e, s);
    }
}

From source file:ee.ria.xroad.common.message.SaxSoapParserImpl.java

private XRoadSoapHandler handleSoap(Writer writer, InputStream inputStream) throws Exception {
    try (BufferedWriter out = new BufferedWriter(writer)) {
        XRoadSoapHandler handler = new XRoadSoapHandler(out);
        SAXParser saxParser = PARSER_FACTORY.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, handler);
        // ensure both builtin entities and character entities are reported to the parser
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true);
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true);

        saxParser.parse(inputStream, handler);
        return handler;
    } catch (SAXException ex) {
        throw new SOAPException(ex);
    }/*w w  w  .  jav  a  2  s  .  c  o m*/
}

From source file:iarnrodProducer.java

public static DefaultFeatureCollection parseXML(final SimpleFeatureBuilder builder) {

    // sft schema = "trainStatus:String,trainCode:String,publicMessage:String,direction:String,dtg:Date,*geom:Point:srid=4326"
    final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    try {/*  www .j  av  a  2  s .c  o m*/
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

            StringBuilder textContent = new StringBuilder();
            String tagName;
            double lat;
            double lon;
            String trainCode;

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                tagName = qName;
                textContent.setLength(0);
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {
                tagName = qName;
                String text = textContent.toString();

                if (tagName == TRAIN_LAT) {
                    lat = Double.parseDouble(text);
                } else if (tagName == TRAIN_LON) {
                    lon = Double.parseDouble(text);
                } else if (tagName == TRAIN_STATUS) {
                    builder.add(text);
                } else if (tagName == TRAIN_CODE) {
                    trainCode = text; // use this as feature ID
                    builder.add(text);
                } else if (tagName == PUBLIC_MESSAGE) {
                    builder.add(text);
                } else if (tagName == DIRECTION) {
                    builder.add(text); // add direction
                    // this is the last field, so finish up
                    builder.add(DateTime.now().toDate());
                    builder.add(WKTUtils$.MODULE$.read("POINT(" + (lon) + " " + (lat) + ")"));
                    SimpleFeature feature = builder.buildFeature(trainCode);
                    featureCollection.add(feature);
                }

            }

            public void characters(char ch[], int start, int length) throws SAXException {
                textContent.append(ch, start, length);
            }

            public void startDocument() throws SAXException {
                // System.out.println("document started");
            }

            public void endDocument() throws SAXException {
                // System.out.println("document ended");
            }
        }; //handler

        saxParser.parse(API_PATH, handler);
        return featureCollection;

    } catch (Exception e) {
        System.out.println("Parsing exception: " + e);
        System.out.println("exception");
        return null;
    }
}

From source file:org.corpus_tools.pepper.connectors.impl.MavenAccessor.java

/**
 * This method checks the provided pepper plugin for updates and triggers
 * the installation process if a newer version is available
 *///from   w w w.  ja  v a 2s .c om
public boolean update(String groupId, String artifactId, String repositoryUrl, boolean isSnapshot,
        boolean ignoreFrameworkVersion, Bundle installedBundle) {
    if (forbiddenFruits.isEmpty() && !initDependencies()) {
        logger.warn("Update could not be performed, because the pepper dependencies could not be listed.");
        return false;
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Starting update process for " + groupId + ", " + artifactId + ", " + repositoryUrl
                + ", isSnapshot=" + isSnapshot + ", ignoreFrameworkVersion=" + ignoreFrameworkVersion
                + ", installedBundle=" + installedBundle);
    } else {
        logger.info("Starting update process for " + artifactId);
    }

    String newLine = System.getProperty("line.separator");

    DefaultRepositorySystemSession session = getNewSession();

    boolean update = true; // MUST be born true!

    /* build repository */

    RemoteRepository repo = getRepo("repo", repositoryUrl);

    /* build artifact */
    Artifact artifact = new DefaultArtifact(groupId, artifactId, "zip", "[0,)");

    try {
        /* version range request */
        VersionRangeRequest rangeRequest = new VersionRangeRequest();
        rangeRequest.addRepository(repo);
        rangeRequest.setArtifact(artifact);
        VersionRangeResult rangeResult = mvnSystem.resolveVersionRange(session, rangeRequest);
        rangeRequest.setArtifact(artifact);

        /* utils needed for request */
        ArtifactRequest artifactRequest = new ArtifactRequest();
        artifactRequest.addRepository(repo);
        ArtifactResult artifactResult = null;

        /* get all pepperModules versions listed in the maven repository */
        List<Version> versions = rangeResult.getVersions();
        Collections.reverse(versions);

        /* utils for version comparison */
        Iterator<Version> itVersions = versions.iterator();
        VersionScheme vScheme = new GenericVersionScheme();
        boolean srcExists = false;
        Version installedVersion = installedBundle == null ? vScheme.parseVersion("0.0.0")
                : vScheme.parseVersion(
                        installedBundle.getVersion().toString().replace(".SNAPSHOT", "-SNAPSHOT"));
        Version newestVersion = null;

        /*
         * compare, if the listed version really exists in the maven
         * repository
         */
        File file = null;
        while (!srcExists && itVersions.hasNext() && update) {
            newestVersion = itVersions.next();
            artifact = new DefaultArtifact(groupId, artifactId, "zip", newestVersion.toString());
            if (!(artifact.isSnapshot() && !isSnapshot)) {
                update = newestVersion.compareTo(installedVersion) > 0;
                artifactRequest.setArtifact(artifact);
                try {
                    artifactResult = mvnSystem.resolveArtifact(session, artifactRequest);
                    artifact = artifactResult.getArtifact();
                    srcExists = update && artifact.getFile().exists();
                    file = artifact.getFile();

                } catch (ArtifactResolutionException e) {
                    logger.warn("Plugin version " + newestVersion
                            + " could not be found in repository. Checking the next lower version ...");
                }
            }
        }
        update &= file != null;// in case of only snapshots in the maven
        // repository vs. isSnapshot=false
        /*
         * if an update is possible/necessary, perform dependency collection
         * and installation
         */
        if (update) {
            /* create list of necessary repositories */
            Artifact pom = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "pom",
                    artifact.getVersion());
            artifactRequest.setArtifact(pom);
            boolean pomReadingErrors = false;
            try {
                artifactResult = null;
                artifactResult = mvnSystem.resolveArtifact(session, artifactRequest);
            } catch (ArtifactResolutionException e1) {
                pomReadingErrors = true;
            }
            List<RemoteRepository> repoList = new ArrayList<RemoteRepository>();
            repoList.add(repos.get(CENTRAL_REPO));
            repoList.add(repos.get(repositoryUrl));
            if (artifactResult != null && artifactResult.getArtifact().getFile().exists()) {
                try {
                    SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
                    saxParser.parse(artifactResult.getArtifact().getFile().getAbsolutePath(),
                            new POMReader(repoList));
                } catch (SAXException | IOException | ParserConfigurationException e) {
                    pomReadingErrors = true;
                }
            }
            if (pomReadingErrors) {
                logger.warn(
                        "Could not determine all relevant repositories, update might fail. Trying to continue ...");
                repoList.add(repos.get(KORPLING_MAVEN_REPO));
            }

            /* remove older version */
            if (installedBundle != null) {
                try {
                    if (!pepperOSGiConnector.remove(installedBundle.getSymbolicName())) {
                        logger.warn("Could not remove older version. Update process aborted.");
                        return false;
                    }
                } catch (BundleException | IOException e) {
                    logger.warn("An error occured while trying to remove OSGi bundle "
                            + installedBundle.getSymbolicName()
                            + ". This may cause update problems. Trying to continue ...");
                }
            }

            /* utils for file-collection */
            List<Artifact> installArtifacts = new ArrayList<Artifact>();
            installArtifacts.add(artifact);

            /* utils for dependency collection */
            CollectRequest collectRequest = new CollectRequest();
            collectRequest.setRoot(new Dependency(artifact, ""));
            collectRequest.setRepositories(repoList);
            CollectResult collectResult = mvnSystem.collectDependencies(session, collectRequest);
            List<Dependency> allDependencies = getAllDependencies(collectResult.getRoot(), true);

            /*
             * we have to remove the dependencies of pepperParent from the
             * dependency list, since they are (sometimes) not already on
             * the blacklist
             */
            String parentVersion = null;
            for (int i = 0; i < allDependencies.size() && parentVersion == null; i++) {
                if (ARTIFACT_ID_PEPPER_FRAMEWORK.equals(allDependencies.get(i).getArtifact().getArtifactId())) {
                    parentVersion = allDependencies.get(i).getArtifact().getVersion();
                }
            }
            if (parentVersion == null) {
                logger.warn(artifactId
                        + ": Could not perform update: pepper-parent version could not be determined.");
                return false;
            }
            VersionRange range = isCompatiblePlugin(parentVersion);
            if (!ignoreFrameworkVersion && range != null) {
                logger.info((new StringBuilder()).append(
                        "No update was performed because of a version incompatibility according to pepper-framework: ")
                        .append(newLine).append(artifactId).append(" only supports ").append(range.toString())
                        .append(", but ").append(pepperOSGiConnector.getFrameworkVersion())
                        .append(" is installed!").append(newLine)
                        .append("You can make pepper ignore this by using \"update")
                        .append(isSnapshot ? " snapshot " : " ").append("iv ").append(artifactId).append("\"")
                        .toString());
                return false;
            }
            allDependencies = cleanDependencies(allDependencies, session, parentVersion);
            Bundle bundle = null;
            Dependency dependency = null;
            // in the following we ignore the first dependency (i=0),
            // because it is the module itself
            for (int i = 1; i < allDependencies.size(); i++) {
                dependency = allDependencies.get(i);
                if (!ARTIFACT_ID_PEPPER_FRAMEWORK.equals(dependency.getArtifact().getArtifactId())) {
                    artifactRequest = new ArtifactRequest();
                    artifactRequest.setArtifact(dependency.getArtifact());
                    artifactRequest.setRepositories(repoList);
                    try {
                        artifactResult = mvnSystem.resolveArtifact(session, artifactRequest);
                        installArtifacts.add(artifactResult.getArtifact());
                    } catch (ArtifactResolutionException e) {
                        logger.warn("Artifact " + dependency.getArtifact().getArtifactId()
                                + " could not be resolved. Dependency will not be installed.");
                        if (!Boolean.parseBoolean(pepperOSGiConnector.getPepperStarterConfiguration()
                                .getProperty("pepper.forceUpdate").toString())) {
                            logger.error("Artifact ".concat(artifact.getArtifactId())
                                    .concat(" will not be installed. Resolution of dependency ")
                                    .concat(dependency.getArtifact().getArtifactId())
                                    .concat(" failed and \"force update\" is disabled in pepper.properties."));
                            return false;
                        }
                    }
                }
            }
            artifact = null;
            Artifact installArtifact = null;
            for (int i = installArtifacts.size() - 1; i >= 0; i--) {
                try {
                    installArtifact = installArtifacts.get(i);
                    logger.info("installing: " + installArtifact);
                    bundle = pepperOSGiConnector.installAndCopy(installArtifact.getFile().toURI());
                    if (i != 0) {// the module itself must not be put on the
                                 // blacklist
                        putOnBlacklist(installArtifact);
                    } else if (installedBundle != null) {
                        pepperOSGiConnector.remove(installedBundle.getSymbolicName());
                        logger.info(
                                "Successfully removed version ".concat(installedBundle.getVersion().toString())
                                        .concat(" of ").concat(artifactId));
                    }
                    if (bundle != null) {
                        bundle.start();
                    }
                } catch (IOException | BundleException e) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("File could not be installed: " + installArtifact + " ("
                                + installArtifact.getFile() + "); " + e.getClass().getSimpleName());
                    } else {
                        logger.warn("File could not be installed: " + installArtifact.getFile());
                    }
                }
            }
            /*
             * btw: root is not supposed to be stored as forbidden
             * dependency. This makes the removal of a module much less
             * complicated. If a pepper module would be put onto the
             * blacklist and the bundle would be removed, we always had to
             * make sure, it its entry on the blacklist would be removed.
             * Assuming the entry would remain on the blacklist, the module
             * could be reinstalled, BUT(!) the dependencies would all be
             * dropped and never being installed again, since the modules
             * node dominates all other nodes in the dependency tree.
             */
            write2Blacklist();
        } else {
            logger.info("No (newer) version of " + artifactId + " could be found.");
        }
    } catch (VersionRangeResolutionException | InvalidVersionSpecificationException
            | DependencyCollectionException e) {
        if (e instanceof DependencyCollectionException) {
            Throwable t = e.getCause();
            while (t.getCause() != null) {
                t = t.getCause();
            }
            if (t instanceof ArtifactNotFoundException) {
                if (logger.isDebugEnabled()) {
                    logger.debug(t.getMessage(), e);
                } else {
                    logger.warn("Update of " + artifactId + " failed, could not resolve dependencies "/*
                                                                                                      * ,
                                                                                                      * e
                                                                                                      */);// TODO
                                                                                                           // decide
                }
            }
            if (t instanceof HttpResponseException) {
                logger.error("Dependency resolution failed!" + System.lineSeparator()
                        + "\tUnsatisfying http response: " + t.getMessage());
            }
        }
        update = false;
    }
    return update;
}

From source file:com.cloudhopper.sxmp.SxmpParser.java

/**
public Node parse(InputSource source) throws IOException, SAXException {
//        _dtd=null;/*w ww .  java2  s . c o  m*/
Handler handler = new Handler();
XMLReader reader = _parser.getXMLReader();
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
reader.setEntityResolver(handler);
if (logger.isDebugEnabled())
    logger.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId());
_parser.parse(source, handler);
if (handler.error != null)
    throw handler.error;
Node root = (Node)handler.root;
handler.reset();
return root;
}
        
public synchronized Node parse(String xml) throws IOException, SAXException {
ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
return parse(is);
}
        
public synchronized Node parse(File file) throws IOException, SAXException {
return parse(new InputSource(file.toURI().toURL().toString()));
}
        
public synchronized Node parse(InputStream in) throws IOException, SAXException {
//_dtd=null;
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 root = (Node)handler.root;
handler.reset();
return root;
}
 */

public Operation parse(InputStream in)
        throws SxmpParsingException, IOException, SAXException, ParserConfigurationException {
    // create a new SAX parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    //factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    SAXParser parser = factory.newSAXParser();
    //_parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", validating);
    parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
    parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    parser.getXMLReader().setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);

    //_dtd=null;
    Handler handler = new Handler();
    XMLReader reader = parser.getXMLReader();
    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);
    reader.setEntityResolver(handler);

    // try parsing (may throw an SxmpParsingException in the handler)
    try {
        parser.parse(new InputSource(in), handler);
    } catch (com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException e) {
        throw new SxmpParsingException(SxmpErrorCode.INVALID_XML, "XML encoding mismatch", null);
    }

    // check if there was an error
    if (handler.error != null) {
        throw handler.error;
    }

    // check to see if an operation was actually parsed
    if (handler.getOperation() == null) {
        throw new SxmpParsingException(SxmpErrorCode.MISSING_REQUIRED_ELEMENT,
                "The operation type [" + handler.operationType.getValue() + "] requires a request element",
                new PartialOperation(handler.operationType));
    }

    // if we got here, an operation was parsed -- now we need to validate it
    // to make sure that it has all required elements
    try {
        handler.getOperation().validate();
    } catch (SxmpErrorException e) {
        throw new SxmpParsingException(e.getErrorCode(), e.getErrorMessage(), handler.getOperation());
    }

    return handler.getOperation();
}

From source file:edu.scripps.fl.pubchem.web.entrez.ELinkWebSession.java

@SuppressWarnings("unchecked")
protected Collection<ELinkResult> getELinkResultsSAX(final Collection<ELinkResult> relations) throws Exception {
    log.info("Memory in use before inputstream: " + memUsage());
    InputStream is = EUtilsWebSession.getInstance()
            .getInputStream("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi", getParams()).call();
    log.info("Memory in use after inputstream: " + memUsage());
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler() {
        private ELinkResult result;
        private List<Long> idList;
        private StringBuffer buf;
        private int depth;
        private String linkName;
        private String dbTo;

        public void characters(char ch[], int start, int length) throws SAXException {
            buf.append(ch, start, length);
        }//from w  w w . ja va2  s .co m

        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (qName.equalsIgnoreCase("LinkSet"))
                relations.add(result);
            else if (qName.equalsIgnoreCase("LinkSetDb")) {
                if (idList.size() > 0)
                    result.setIds(dbTo, linkName, idList);
            } else if (qName.equalsIgnoreCase("LinkName"))
                linkName = buf.toString();
            else if (qName.equalsIgnoreCase("dbTo"))
                dbTo = buf.toString();
            else if (qName.equalsIgnoreCase("DbFrom"))
                result.setDbFrom(buf.toString());
            else if (qName.equalsIgnoreCase("Id")) {
                Long id = Long.parseLong(buf.toString());
                if (depth == 4)
                    result.setId(id);
                else if (depth == 5)
                    idList.add(id);
            }
            depth--;
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            depth++;
            buf = new StringBuffer();
            if (qName.equalsIgnoreCase("LinkSet"))
                result = new ELinkResult();
            else if (qName.equalsIgnoreCase("LinkSetDb"))
                idList = new ArrayList();
        }
    };
    log.info("Memory in use before parsing: " + memUsage());
    log.info("Parsing elink results using SAX.");
    try {
        saxParser.parse(is, handler);
    } catch (SAXParseException ex) {
        throw new Exception("Error parsing ELink output: " + ex.getMessage());
    }
    log.info("Finished parsing elink results.");
    log.info("Memory in use after parsing: " + memUsage());
    return relations;
}

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 .jav a2  s  .  c o  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:com.connectsdk.service.NetcastTVService.java

private JSONObject parseVolumeXmlToJSON(String data) {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {//from  w  w  w  .  j a  v a  2  s.com
        InputStream stream = new ByteArrayInputStream(data.getBytes("UTF-8"));

        SAXParser saxParser = saxParserFactory.newSAXParser();
        NetcastVolumeParser handler = new NetcastVolumeParser();
        saxParser.parse(stream, handler);

        return handler.getVolumeStatus();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}