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.entertailion.java.fling.FlingFrame.java

public void onBroadcastFound(final BroadcastAdvertisement advert) {
    if (advert.getLocation() != null) {
        new Thread(new Runnable() {
            public void run() {
                Log.d(LOG_TAG, "location=" + advert.getLocation());
                HttpResponse response = new HttpRequestHelper().sendHttpGet(advert.getLocation());
                if (response != null) {
                    String appsUrl = null;
                    Header header = response.getLastHeader(HEADER_APPLICATION_URL);
                    if (header != null) {
                        appsUrl = header.getValue();
                        if (!appsUrl.endsWith("/")) {
                            appsUrl = appsUrl + "/";
                        }/*from   w ww . j  a v a 2 s. c  om*/
                        Log.d(LOG_TAG, "appsUrl=" + appsUrl);
                    }
                    try {
                        InputStream inputStream = response.getEntity().getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                        InputSource inStream = new org.xml.sax.InputSource();
                        inStream.setCharacterStream(reader);
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();
                        XMLReader xr = sp.getXMLReader();
                        BroadcastHandler broadcastHandler = new BroadcastHandler();
                        xr.setContentHandler(broadcastHandler);
                        xr.parse(inStream);
                        Log.d(LOG_TAG, "modelName=" + broadcastHandler.getDialServer().getModelName());
                        // Only handle ChromeCast devices; not other DIAL
                        // devices like ChromeCast devices
                        if (broadcastHandler.getDialServer().getModelName().equals(CHROME_CAST_MODEL_NAME)) {
                            Log.d(LOG_TAG,
                                    "ChromeCast device found: " + advert.getIpAddress().getHostAddress());
                            DialServer dialServer = new DialServer(advert.getLocation(), advert.getIpAddress(),
                                    advert.getPort(), appsUrl,
                                    broadcastHandler.getDialServer().getFriendlyName(),
                                    broadcastHandler.getDialServer().getUuid(),
                                    broadcastHandler.getDialServer().getManufacturer(),
                                    broadcastHandler.getDialServer().getModelName());
                            trackedServers.add(dialServer);
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "parse device description", e);
                    }
                }
            }
        }).start();
    }
}

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

/**
public Node parse(InputSource source) throws IOException, SAXException {
//        _dtd=null;//from w ww  .j a  va  2 s.co  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:net.smart_json_database.JSONDatabase.java

private JSONDatabase(Context context, String configurationName) throws InitJSONDatabaseExcepiton {

    AssetManager assetManager = context.getAssets();
    InputStream stream = null;/*w  w w . j a v  a 2s .c  om*/

    String configXML = null;
    try {
        configXML = configurationName + ".xml";
        stream = assetManager.open(configXML);

    } catch (IOException e) {
        throw new InitJSONDatabaseExcepiton("Could not load asset " + configXML);
    } finally {
        if (stream != null) {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLConfigHandler handler = new XMLConfigHandler();
            SAXParser saxparser;
            try {
                saxparser = factory.newSAXParser();
                saxparser.parse(stream, handler);
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("Parser-Error while reading the " + configXML, e);
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("SAX-Error while reading the " + configXML, e);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("IO-Error while reading the " + configXML, e);
            }

            mDbName = handler.getDbName();

            if (Util.IsNullOrEmpty(mDbName))
                throw new InitJSONDatabaseExcepiton("db name is empty check the xml configuration");

            mDbVersion = handler.getDbVersion();

            if (mDbVersion < 1)
                throw new InitJSONDatabaseExcepiton(
                        "db version must be 1 or greater -  check the xml configuration");

            mUpgradeClassPath = handler.getUpgradeClass();

            if (!Util.IsNullOrEmpty(mUpgradeClassPath)) {
                try {
                    Class<?> x = Class.forName(mUpgradeClassPath);
                    dbUpgrade = (IUpgrade) x.newInstance();
                } catch (Exception e) {
                }
            }

            dbHelper = new DBHelper(context, mDbName, mDbVersion);
            listeners = new ArrayList<IDatabaseChangeListener>();
            tags = new HashMap<String, Integer>();
            invertedTags = new HashMap<Integer, String>();
            updateTagMap();

        } else {
            throw new InitJSONDatabaseExcepiton(configXML + " is empty");
        }
    }
}

From source file:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java

public boolean setICSasMultiStatus(String stringMultiStatus) {
    boolean Result = false;
    String ics = "";
    MultiStatus multistatus;/*w  ww.  j av a2  s  .  c  o  m*/
    ArrayList<Response> responselist;
    Response response;
    PropStat propstat;
    Prop prop;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        MultiStatusHandler contentHandler = new MultiStatusHandler();
        reader.setContentHandler(contentHandler);
        reader.parse(new InputSource(new StringReader(stringMultiStatus)));

        multistatus = contentHandler.mMultiStatus;
        if (multistatus != null) {
            responselist = multistatus.ResponseList;
            if (responselist.size() == 1) {
                response = responselist.get(0);
                //HINT: bugfix for google calendar
                if (response.href.equals(this.getUri().getPath().replace("@", "%40"))) {
                    propstat = response.propstat;
                    if (propstat.status.contains("200 OK")) {
                        prop = propstat.prop;
                        ics = prop.calendardata;
                        this.setETag(prop.getetag);
                        Result = true;
                    }
                }
            }
        }
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    } catch (SAXException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.stringIcs = ics;
    return Result;
}

From source file:com.sun.faban.harness.webclient.CLIServlet.java

private void sendLogs(String[] reqC, HttpServletResponse response) throws ServletException, IOException {
    if (reqC.length < 2) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing RunId.");
        return;//from  w  w w  . ja  va  2 s . c o m
    }
    RunId runId = new RunId(reqC[1]);
    boolean[] options = new boolean[2];
    options[TAIL] = false;
    options[FOLLOW] = false;
    for (int i = 2; i < reqC.length; i++) {
        if ("tail".equals(reqC[i])) {
            options[TAIL] = true;
        } else if ("follow".equals(reqC[i])) {
            options[FOLLOW] = true;
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid option \"" + reqC[i] + "\".");
            ;
            return;
        }
    }
    File logFile = new File(Config.OUT_DIR + runId, "log.xml");
    String status = null;
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    while (!logFile.exists()) {
        String[] pending = RunQ.listPending();
        if (pending == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found");
            return;
        }
        boolean queued = false;
        for (String run : pending) {
            if (run.equals(runId.toString())) {
                if (status == null) {
                    status = "QUEUED";
                    out.println(status);
                    response.flushBuffer();
                }
                queued = true;
                try {
                    Thread.sleep(1000); // Check back in one sec.
                } catch (InterruptedException e) {
                    //Noop, just look it up again.
                }
                break;
            }
        }
        if (!queued) { // Either never queued or deleted from queue.
            // Check for 10x, 100ms each to allow for start time.
            for (int i = 0; i < 10; i++) {
                if (logFile.exists()) {
                    status = "STARTED";
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    logger.log(Level.WARNING, "Interrupted checking existence of log file.");
                }
            }

            if (!"STARTED".equals(status)) {
                if ("QUEUED".equals(status)) { // was queued before
                    status = "DELETED";
                    out.println(status);
                    out.flush();
                    out.close();
                    return;
                } else { // Never queued or just removed.
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found");
                    return;
                }
            }
        }
    }

    LogOutputHandler handler = new LogOutputHandler(response, options);
    InputStream logInput;
    if (options[FOLLOW]) {
        // The XMLInputStream reads streaming XML and does not EOF.
        XMLInputStream input = new XMLInputStream(logFile);
        input.addEOFListener(handler);
        logInput = input;
    } else {
        logInput = new FileInputStream(logFile);
    }
    try {
        SAXParserFactory sFact = SAXParserFactory.newInstance();
        sFact.setFeature("http://xml.org/sax/features/validation", false);
        sFact.setFeature("http://apache.org/xml/features/" + "allow-java-encodings", true);
        sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-dtd-grammar", false);
        sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-external-dtd", false);
        SAXParser parser = sFact.newSAXParser();
        parser.parse(logInput, handler);
        handler.xmlComplete = true; // If we get here, the XML is good.
    } catch (ParserConfigurationException e) {
        throw new ServletException(e);
    } catch (SAXParseException e) {
        Throwable t = e.getCause();
        // If it is caused by an IOException, we'll just throw it.
        if (t != null) {
            if (t instanceof IOException)
                throw (IOException) t;
            else if (options[FOLLOW])
                throw new ServletException(t);
        } else if (options[FOLLOW]) {
            throw new ServletException(e);
        }
    } catch (SAXException e) {
        throw new ServletException(e);
    } finally {
        if (options[TAIL] && !options[FOLLOW]) // tail not yet printed
            handler.eof();
    }
}

From source file:self.philbrown.javaQuery.AjaxTask.java

@Override
protected TaskResponse doInBackground(Void... arg0) {
    //handle cached responses
    CachedResponse cachedResponse = URLresponses
            .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()));
    //handle ajax caching option
    if (cachedResponse != null) {
        if (options.cache()) {
            if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) {
                //return cached response
                Success s = new Success();
                s.obj = cachedResponse.response;
                s.reason = "cached response";
                s.headers = null;/*from   ww w.j a v  a  2  s  . c  o m*/
                return s;
            }
        }

    }

    if (request == null) {
        String type = options.type();
        if (type == null)
            type = "GET";
        if (type.equalsIgnoreCase("DELETE")) {
            request = new HttpDelete(options.url());
        } else if (type.equalsIgnoreCase("GET")) {
            request = new HttpGet(options.url());
        } else if (type.equalsIgnoreCase("HEAD")) {
            request = new HttpHead(options.url());
        } else if (type.equalsIgnoreCase("OPTIONS")) {
            request = new HttpOptions(options.url());
        } else if (type.equalsIgnoreCase("POST")) {
            request = new HttpPost(options.url());
        } else if (type.equalsIgnoreCase("PUT")) {
            request = new HttpPut(options.url());
        } else if (type.equalsIgnoreCase("TRACE")) {
            request = new HttpTrace(options.url());
        } else if (type.equalsIgnoreCase("CUSTOM")) {
            try {
                request = options.customRequest();
            } catch (Exception e) {
                request = null;
            }

            if (request == null) {
                Log.w("javaQuery.ajax",
                        "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                request = new HttpGet();
            }

        } else {
            //default to GET
            request = new HttpGet();
        }
    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", request);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class });
            if (options.processData() == null) {
                setEntity.invoke(request, new StringEntity(options.data().toString()));
            } else {
                Class<?> dataProcessor = Class.forName(options.processData());
                Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class });
                setEntity.invoke(request, constructor.newInstance(options.data()));
            }
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    HttpParams params = new BasicHttpParams();

    if (options.timeout() != 0) {
        HttpConnectionParams.setConnectionTimeout(params, options.timeout());
        HttpConnectionParams.setSoTimeout(params, options.timeout());
    }

    HttpClient client = new DefaultHttpClient(params);

    HttpResponse response = null;
    try {

        if (options.cookies() != null) {
            CookieStore cookies = new BasicCookieStore();
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
            }
            HttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
            response = client.execute(request, httpContext);
        } else {
            response = client.execute(request);
        }

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke(new $(options.context()), response, options.dataType());
            else
                options.dataFilter().invoke(null, response, options.dataType());
        }

        StatusLine statusLine = response.getStatusLine();

        Function function = options.statusCode().get(statusLine);
        if (function != null) {
            if (options.context() != null)
                function.invoke(new $(options.context()));
            else
                function.invoke(null);
        }

        if (statusLine.getStatusCode() >= 300) {
            //an error occurred
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } else {
            //handle dataType
            String dataType = options.dataType();
            if (dataType == null)
                dataType = "text";
            Object parsedResponse = null;
            boolean success = true;
            try {
                if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                    parsedResponse = parseText(response);
                } else if (dataType.equalsIgnoreCase("xml")) {
                    if (options.customXMLParser() != null) {
                        InputStream is = response.getEntity().getContent();
                        if (options.SAXContentHandler() != null)
                            options.customXMLParser().parse(is, options.SAXContentHandler());
                        else
                            options.customXMLParser().parse(is, new DefaultHandler());
                        parsedResponse = "Response handled by custom SAX parser";
                    } else if (options.SAXContentHandler() != null) {
                        InputStream is = response.getEntity().getContent();

                        SAXParserFactory factory = SAXParserFactory.newInstance();

                        factory.setFeature("http://xml.org/sax/features/namespaces", false);
                        factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                        SAXParser parser = factory.newSAXParser();

                        XMLReader reader = parser.getXMLReader();
                        reader.setContentHandler(options.SAXContentHandler());
                        reader.parse(new InputSource(is));
                        parsedResponse = "Response handled by custom SAX content handler";
                    } else {
                        parsedResponse = parseXML(response);
                    }
                } else if (dataType.equalsIgnoreCase("json")) {
                    parsedResponse = parseJSON(response);
                } else if (dataType.equalsIgnoreCase("script")) {
                    parsedResponse = parseScript(response);
                } else if (dataType.equalsIgnoreCase("image")) {
                    parsedResponse = parseImage(response);
                }
            } catch (ClientProtocolException cpe) {
                if (options.debug())
                    cpe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            } catch (Exception ioe) {
                if (options.debug())
                    ioe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            }
            if (success) {
                //Handle cases where successful requests still return errors (these include
                //configurations in AjaxOptions and HTTP Headers
                String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType());
                CachedResponse cache = URLresponses.get(key);
                Date now = new Date();
                //handle ajax caching option
                if (cache != null) {
                    if (options.cache()) {
                        if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) {
                            parsedResponse = cache;
                        } else {
                            cache.response = parsedResponse;
                            cache.timestamp = now;
                            synchronized (URLresponses) {
                                URLresponses.put(key, cache);
                            }
                        }
                    }

                }
                //handle ajax ifModified option
                Header[] lastModifiedHeaders = response.getHeaders("last-modified");
                if (lastModifiedHeaders.length >= 1) {
                    try {
                        Header h = lastModifiedHeaders[0];
                        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                        Date lastModified = format.parse(h.getValue());
                        if (options.ifModified() && lastModified != null) {
                            if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) {
                                //request response has not been modified. 
                                //Causes an error instead of a success.
                                Error e = new Error();
                                AjaxError error = new AjaxError();
                                error.request = request;
                                error.options = options;
                                e.status = statusLine.getStatusCode();
                                e.reason = statusLine.getReasonPhrase();
                                error.status = e.status;
                                error.reason = e.reason;
                                e.headers = response.getAllHeaders();
                                e.error = error;
                                Function func = options.statusCode().get(304);
                                if (func != null) {
                                    if (options.context() != null)
                                        func.invoke(new $(options.context()));
                                    else
                                        func.invoke(null);
                                }
                                return e;
                            } else {
                                cache.lastModified = lastModified;
                                synchronized (URLresponses) {
                                    URLresponses.put(key, cache);
                                }
                            }
                        }
                    } catch (Throwable t) {
                        Log.e("Ajax", "Could not parse Last-Modified Header");
                    }

                }

                //Now handle a successful request

                Success s = new Success();
                s.obj = parsedResponse;
                s.reason = statusLine.getReasonPhrase();
                s.headers = response.getAllHeaders();
                return s;
            }
            //success
            Success s = new Success();
            s.obj = parsedResponse;
            s.reason = statusLine.getReasonPhrase();
            s.headers = response.getAllHeaders();
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:org.hil.webservice.mobile.impl.ChildrenWebServiceImpl.java

private void parseXml(String xml) {
    list = new ArrayList<Children>();
    tmpAuth = "";
    tmpAuthor = "";
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {/* ww  w  .ja v a2  s .com*/
        SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

            Children tempChild;
            String tempVal = "";

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                if (qName.equalsIgnoreCase("Children")) {
                    tmpAuth = attributes.getValue("sessionAuth");

                    if (!tmpAuth.equalsIgnoreCase("sessionAuth"))
                        return;
                    tmpAuthor = attributes.getValue("author");
                    force = Boolean.parseBoolean(attributes.getValue("force"));
                }
                tempVal = "";
                if (qName.equalsIgnoreCase("Child")) {
                    tempChild = new Children();
                }
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (qName.equalsIgnoreCase("Child")) {
                    //add it to the list
                    list.add(tempChild);
                } else if (qName.equalsIgnoreCase("id")) {
                    if (tempVal.length() > 0)
                        tempChild.setId(Long.parseLong(tempVal));
                } else if (qName.equalsIgnoreCase("fullName")) {
                    if (tempVal.length() > 0)
                        tempChild.setFullName(tempVal);
                } else if (qName.equalsIgnoreCase("dateOfBirth")) {
                    if (tempVal.length() > 0) {
                        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
                        try {
                            Date bdate = format.parse(tempVal);
                            tempChild.setDateOfBirth(bdate);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                } else if (qName.equalsIgnoreCase("gender")) {
                    if (tempVal.length() > 0)
                        tempChild.setGender(Boolean.parseBoolean(tempVal));
                } else if (qName.equalsIgnoreCase("childCode")) {
                    if (tempVal.length() > 0)
                        tempChild.setChildCode(tempVal);
                } else if (qName.equalsIgnoreCase("fatherName")) {
                    if (tempVal.length() > 0)
                        tempChild.setFatherName(tempVal);
                } else if (qName.equalsIgnoreCase("fatherBirthYear")) {
                    if (tempVal.length() > 0)
                        tempChild.setFatherBirthYear(Integer.parseInt(tempVal));
                } else if (qName.equalsIgnoreCase("fatherID")) {
                    if (tempVal.length() > 0)
                        tempChild.setFatherID(tempVal);
                } else if (qName.equalsIgnoreCase("fatherMobile")) {
                    if (tempVal.length() > 0)
                        tempChild.setFatherMobile(tempVal);
                } else if (qName.equalsIgnoreCase("motherName")) {
                    if (tempVal.length() > 0)
                        tempChild.setMotherName(tempVal);
                } else if (qName.equalsIgnoreCase("motherBirthYear")) {
                    if (tempVal.length() > 0)
                        tempChild.setMotherBirthYear(Integer.parseInt(tempVal));
                } else if (qName.equalsIgnoreCase("motherID")) {
                    if (tempVal.length() > 0)
                        tempChild.setMotherID(tempVal);
                } else if (qName.equalsIgnoreCase("motherMobile")) {
                    if (tempVal.length() > 0)
                        tempChild.setMotherMobile(tempVal);
                } else if (qName.equalsIgnoreCase("caretakerName")) {
                    if (tempVal.length() > 0)
                        tempChild.setCaretakerName(tempVal);
                } else if (qName.equalsIgnoreCase("caretakerBirthYear")) {
                    if (tempVal.length() > 0)
                        tempChild.setCaretakerBirthYear(Integer.parseInt(tempVal));
                } else if (qName.equalsIgnoreCase("caretakerID")) {
                    if (tempVal.length() > 0)
                        tempChild.setCaretakerID(tempVal);
                } else if (qName.equalsIgnoreCase("caretakerMobile")) {
                    if (tempVal.length() > 0)
                        tempChild.setCaretakerMobile(tempVal);
                } else if (qName.equalsIgnoreCase("currentCaretaker")) {
                    if (tempVal.length() > 0)
                        tempChild.setCurrentCaretaker(Short.parseShort(tempVal));
                } else if (qName.equalsIgnoreCase("villageId")) {
                    if (tempVal.length() > 0) {
                        tempChild.setVillage(villageDao.get(Long.parseLong(tempVal)));
                    }
                }
            }

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

        };
        saxParser.parse(new InputSource(new StringReader(xml)), handler);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:se.lu.nateko.edca.svc.GeoHelper.java

/**
 * Parses an XML response from a WFS Transaction (Insert) request and
 * reports if the response contains a Service Exception.
 * @param xmlResponse String containing the XML response from a DescribeFeatureType request.
 *//* w w w.  jav a  2  s.c  om*/
protected boolean parseXMLResponse(InputStream xmlResponse) {
    Log.d(TAG, "parseXMLResponse(InputStream) called.");

    mInsertedIDs = new ArrayList<Long>();

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return false;
    }
    return true;
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //www.  j  a va2 s. c  o  m
 * getArtistArt
 * 
 *********************************/
private String getArtistArt(String artistName) {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader;
        xmlReader = saxParser.getXMLReader();
        XMLArtistInfoHandler xmlHandler = new XMLArtistInfoHandler();
        xmlReader.setContentHandler(xmlHandler);
        /*
         * Get artist art from Last.FM
         */
        String artistNameFiltered = filterString(artistName);
        URL lastFmApiRequest = new URL(
                this.LAST_FM_ARTIST_GETINFO_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
        BufferedReader in = new BufferedReader(new InputStreamReader(lastFmApiRequest.openStream()));
        xmlReader.parse(new InputSource(in));

        if (xmlHandler.xlargeAlbumArt != null) {
            return xmlHandler.xlargeAlbumArt;
        } else if (xmlHandler.largeAlbumArt != null) {
            return xmlHandler.largeAlbumArt;
        } else if (xmlHandler.mediumAlbumArt != null) {
            return xmlHandler.mediumAlbumArt;
        }

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

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * /*  w  w w  . j  a  v a2  s  .  c om*/
 * getAlbumArtByAlbumName
 * 
 *********************************/
private String getAlbumArtByAlbumName(String albumName, String artistName) {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader;
        xmlReader = saxParser.getXMLReader();
        XMLAlbumSearchHandler xmlHandler = new XMLAlbumSearchHandler();
        xmlReader.setContentHandler(xmlHandler);
        /*
         * Get artist art from Last.FM
         */
        String artistNameFiltered = filterString(artistName);
        String albumNameFiltered = filterString(albumName);
        URL lastFmApiRequest = new URL(
                this.LAST_FM_ALBUM_SEARCH_URL + "&album=" + URLEncoder.encode(albumNameFiltered));
        BufferedReader in = new BufferedReader(new InputStreamReader(lastFmApiRequest.openStream()));
        xmlReader.parse(new InputSource(in));

        for (int i = 0; i < xmlHandler.albumSearchList.size(); i++) {
            AlbumSearch albumSearch = xmlHandler.albumSearchList.get(i);
            if (artistNameIsSimilarEnough(filterString(albumSearch.artistName), artistNameFiltered)) {
                if (albumSearch.xlargeAlbumArt != null) {
                    return albumSearch.xlargeAlbumArt;
                } else if (albumSearch.largeAlbumArt != null) {
                    return albumSearch.largeAlbumArt;
                } else if (albumSearch.mediumAlbumArt != null) {
                    return albumSearch.mediumAlbumArt;
                }
            }
        }
        return null;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}