Example usage for javax.xml.parsers SAXParserFactory newInstance

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

Introduction

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

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:com.top.Ertebat.mail.store.WebDavStore.java

private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers,
        boolean needsParsing) throws MessagingException {
    DataSet dataset = new DataSet();
    if (Ertebat.DEBUG && Ertebat.DEBUG_PROTOCOL_WEBDAV) {
        Log.v(Ertebat.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '"
                + messageBody + "'");
    }//from   w  ww .j a va  2 s  .  co m

    if (url == null || method == null) {
        return dataset;
    }

    getHttpClient();

    try {
        StringEntity messageEntity = null;
        if (messageBody != null) {
            messageEntity = new StringEntity(messageBody);
            messageEntity.setContentType("text/xml");
        }
        InputStream istream = sendRequest(url, method, messageEntity, headers, true);
        if (istream != null && needsParsing) {
            try {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                WebDavHandler myHandler = new WebDavHandler();

                xr.setContentHandler(myHandler);

                xr.parse(new InputSource(istream));

                dataset = myHandler.getDataSet();
            } catch (SAXException se) {
                Log.e(Ertebat.LOG_TAG,
                        "SAXException in processRequest() " + se + "\nTrace: " + processException(se));
                throw new MessagingException("SAXException in processRequest() ", se);
            } catch (ParserConfigurationException pce) {
                Log.e(Ertebat.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: "
                        + processException(pce));
                throw new MessagingException("ParserConfigurationException in processRequest() ", pce);
            }

            istream.close();
        }
    } catch (UnsupportedEncodingException uee) {
        Log.e(Ertebat.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee));
        throw new MessagingException("UnsupportedEncodingException in processRequest() ", uee);
    } catch (IOException ioe) {
        Log.e(Ertebat.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe));
        throw new MessagingException("IOException in processRequest() ", ioe);
    }

    return dataset;
}

From source file:edwardawebb.queueman.classes.NetFlix.java

public int deleteFromQueue(Disc disc, int queueType) {
    int result = NF_ERROR_BAD_DEFAULT;
    OAuthConsumer postConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET,
            SignatureMethod.HMAC_SHA1);
    postConsumer.setTokenWithSecret(user.getAccessToken(), user.getAccessTokenSecret());

    // postProvider.setOAuth10a(false);

    HttpClient httpclient = new DefaultHttpClient();

    URL QueueUrl;/*from ww  w .ja va  2 s . c  o m*/
    InputStream xml = null;

    try {
        QueueUrl = new URL(disc.getId());
        HttpDelete httpAction = new HttpDelete(QueueUrl.toString());
        postConsumer.sign(httpAction);

        HttpResponse response = httpclient.execute(httpAction);

        xml = response.getEntity().getContent();
        result = response.getStatusLine().getStatusCode();
        lastResponseMessage = response.getStatusLine().getStatusCode() + ": "
                + response.getStatusLine().getReasonPhrase();
        /*BufferedReader in = new BufferedReader(new InputStreamReader(xml));
        String linein = null;
        while ((linein = in.readLine()) != null) {
           Log.d("NetFlix", "MovieMovie: " + linein);
        }*/

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

        XMLReader xr = sp.getXMLReader();
        QueueHandler myHandler = new QueueHandler();
        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));
        // result=response.getStatusLine().getStatusCode();
        result = myHandler.getSubCode(result);
        lastResponseMessage = "HTTP:" + response.getStatusLine().getStatusCode() + ", "
                + response.getStatusLine().getReasonPhrase();

        if (myHandler.getMessage() != null) {
            //we may have an error from netflix, check it
            lastResponseMessage += "  NF: " + result + ", " + myHandler.getMessage();
        }

    } catch (OAuthMessageSignerException e) {
        reportError(e, lastResponseMessage);
    } catch (OAuthExpectationFailedException e) {
        reportError(e, lastResponseMessage);
    } catch (ClientProtocolException e) {
        reportError(e, lastResponseMessage);
    } catch (IOException e) {
        reportError(e, lastResponseMessage);
    } catch (SAXException e) {
        reportError(e, lastResponseMessage);
    } catch (ParserConfigurationException e) {
        reportError(e, lastResponseMessage);
    }

    /*
     * On a successful; DELETE we remove our local recordss too
     */
    if (result == 200) {

        switch (queueType) {
        case NetFlixQueue.QUEUE_TYPE_DISC:
            NetFlix.discQueue.delete(disc);
            break;
        case NetFlixQueue.QUEUE_TYPE_INSTANT:
            NetFlix.instantQueue.delete(disc);
            break;
        }
        getNewETag(queueType);
    }
    return result;
}

From source file:com.bernard.beaconportal.activities.mail.store.WebDavStore.java

private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers,
        boolean needsParsing) throws MessagingException {
    DataSet dataset = new DataSet();
    if (K9.DEBUG && K9.DEBUG_PROTOCOL_WEBDAV) {
        Log.v(K9.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '"
                + messageBody + "'");
    }/*w w  w .  j a va  2s .  co m*/

    if (url == null || method == null) {
        return dataset;
    }

    getHttpClient();

    try {
        StringEntity messageEntity = null;
        if (messageBody != null) {
            messageEntity = new StringEntity(messageBody);
            messageEntity.setContentType("text/xml");
        }
        InputStream istream = sendRequest(url, method, messageEntity, headers, true);
        if (istream != null && needsParsing) {
            try {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                WebDavHandler myHandler = new WebDavHandler();

                xr.setContentHandler(myHandler);

                xr.parse(new InputSource(istream));

                dataset = myHandler.getDataSet();
            } catch (SAXException se) {
                Log.e(K9.LOG_TAG,
                        "SAXException in processRequest() " + se + "\nTrace: " + processException(se));
                throw new MessagingException("SAXException in processRequest() ", se);
            } catch (ParserConfigurationException pce) {
                Log.e(K9.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: "
                        + processException(pce));
                throw new MessagingException("ParserConfigurationException in processRequest() ", pce);
            }

            istream.close();
        }
    } catch (UnsupportedEncodingException uee) {
        Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee));
        throw new MessagingException("UnsupportedEncodingException in processRequest() ", uee);
    } catch (IOException ioe) {
        Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe));
        throw new MessagingException("IOException in processRequest() ", ioe);
    }

    return dataset;
}

From source file:com.vkassin.mtrade.Common.java

public static String generalWebServiceCall(String urlStr, ContentHandler handler) {

    String errorMsg = "";

    try {// w w  w.  j a v  a 2  s  . c  o m
        URL url = new URL(urlStr);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application: aMTrade");
        urlc.setRequestProperty("Connection", "close");
        // urlc.setRequestProperty("Accept-Charset", "windows-1251");
        // urlc.setRequestProperty("Accept-Charset",
        // "windows-1251,utf-8;q=0.7,*;q=0.7");
        urlc.setRequestProperty("Accept-Charset", "utf-8");

        urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
        urlc.setDoInput(true);
        urlc.connect();

        if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Get a SAXParser from the SAXPArserFactory.
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

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

            // Apply the handler to the XML-Reader
            xr.setContentHandler(handler);

            // Parse the XML-data from our URL.
            InputStream is = urlc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray());
            // Reader isr = new InputStreamReader(bais, "windows-1251");
            Reader isr = new InputStreamReader(bais, "utf-8");
            InputSource ist = new InputSource();
            // ist.setEncoding("UTF-8");
            ist.setCharacterStream(isr);
            xr.parse(ist);
            // Parsing has finished.

            bis.close();
            baf.clear();
            bais.close();
            is.close();
        }

        urlc.disconnect();

    } catch (SAXException e) {
        // All is OK :)
    } catch (MalformedURLException e) {
        Log.e(TAG, errorMsg = "MalformedURLException");
    } catch (IOException e) {
        Log.e(TAG, errorMsg = "IOException");
    } catch (ParserConfigurationException e) {
        Log.e(TAG, errorMsg = "ParserConfigurationException");
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException");
    }

    return errorMsg;
}

From source file:edwardawebb.queueman.classes.NetFlix.java

/**
 * Post a rating to specificed title//from   w ww . ja v a2s.c om
 * @param modifiedDisc
 * @return SubCode, httpResponseCode or NF_ERROR_BAD_DEFAULT on exception
 */
public int setRating(Disc modifiedDisc) {

    int result = NF_ERROR_BAD_DEFAULT;
    // 2 choirs, send request to netflix, and if successful update local q.
    OAuthConsumer postConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET,
            SignatureMethod.HMAC_SHA1);
    postConsumer.setTokenWithSecret(user.getAccessToken(), user.getAccessTokenSecret());

    // postProvider.setOAuth10a(false);
    InputStream xml = null;
    try {

        // Construct data
        /*
         * Log.d("NetFlix", "title_ref=" + URLEncoder.encode(disc.getId(),
         * "UTF-8")); Log.d("NetFlix", "etag=" +
         * URLEncoder.encode(NetFlixQueue.getETag(), "UTF-8"));
         */
        URL url = new URL("https://api.netflix.com/users/" + user.getUserId() + "/ratings/title/actual");

        // Log.d("NetFlix", "@URL: " + url.toString())
        HttpClient httpclient = new DefaultHttpClient();
        // Your URL
        HttpPost httppost = new HttpPost(url.toString());
        postConsumer.setTokenWithSecret(user.getAccessToken(), user.getAccessTokenSecret());

        String rating = (modifiedDisc.getUserRating() == 0) ? NF_RATING_NO_INTEREST
                : String.valueOf(modifiedDisc.getUserRating().intValue());
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        // Your DATA
        nameValuePairs.add(new BasicNameValuePair("title_ref", modifiedDisc.getId()));
        nameValuePairs.add(new BasicNameValuePair("rating", rating));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        postConsumer.sign(httppost);

        HttpResponse response;
        response = httpclient.execute(httppost);

        xml = response.getEntity().getContent();
        lastResponseMessage = response.getStatusLine().getStatusCode() + ": "
                + response.getStatusLine().getReasonPhrase();
        result = response.getStatusLine().getStatusCode();

        /* Log.d("NetFlix", "" +
         response.getEntity().getContentType().toString()); BufferedReader
         in = new BufferedReader(new InputStreamReader(xml)); String
         linein = null; while ((linein = in.readLine()) != null) {
         Log.d("NetFlix", "SetRating: " + linein); }*/

        // Log.i("NetFlix", "Parsing XML Response")
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;

        sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();
        QueueHandler myHandler = new QueueHandler();

        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));

        if (result == 201 || result == 422) {
            switch (modifiedDisc.getQueueType()) {
            //could be rating froms earch, recommends, instant, discm, or at home
            case NetFlixQueue.QUEUE_TYPE_RECOMMEND:
                ((Disc) recomemendedQueue.getDiscs().get(recomemendedQueue.indexOf(modifiedDisc)))
                        .setUserRating(modifiedDisc.getUserRating());
                break;
            case NetFlixQueue.QUEUE_TYPE_INSTANT:
                ((Disc) instantQueue.getDiscs().get(instantQueue.indexOf(modifiedDisc)))
                        .setUserRating(modifiedDisc.getUserRating());
                break;
            case NetFlixQueue.QUEUE_TYPE_DISC:
                ((Disc) discQueue.getDiscs().get(discQueue.indexOf(modifiedDisc)))
                        .setUserRating(modifiedDisc.getUserRating());
                break;
            }
        }

        lastNFResponseMessage = "NF: " + myHandler.getMessage();
        result = myHandler.getSubCode(result);

    } catch (IOException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "IO Error connecting to NetFlix queue")
    } catch (OAuthMessageSignerException e) {

        reportError(e, lastResponseMessage);
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        reportError(e, lastResponseMessage);
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        reportError(e, lastResponseMessage);
    }
    return result;
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import flat storages to the hierarchical storage
 *
 * @param con an open and valid connection to store imported data
 * @param zip zip file containing the data
 * @throws Exception on errors//  w ww  .  j av a2 s.  com
 */
protected void importFlatStoragesHierarchical(Connection con, ZipFile zip) throws Exception {
    //mapping: storage->level->columnname->assignment id
    final Map<String, Map<Integer, Map<String, Long>>> flatAssignmentMapping = new HashMap<String, Map<Integer, Map<String, Long>>>(
            5);
    //mapping: assignment id->position index
    final Map<Long, Integer> assignmentPositions = new HashMap<Long, Integer>(100);
    //mapping: flatstorage->column sizes [string,bigint,double,select,text]
    final Map<String, Integer[]> flatstoragesColumns = new HashMap<String, Integer[]>(5);
    ZipEntry zeMeta = getZipEntry(zip, FILE_FLATSTORAGE_META);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(zip.getInputStream(zeMeta));
    XPath xPath = XPathFactory.newInstance().newXPath();

    //calculate column sizes
    NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document,
            XPathConstants.NODESET);
    Node currNode;
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue());
        int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue());
        int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue());
        int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue());
        int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue());
        String tableName = null;
        if (currNode.hasChildNodes()) {
            for (int j = 0; j < currNode.getChildNodes().getLength(); j++)
                if (currNode.getChildNodes().item(j).getNodeName().equals("name")) {
                    tableName = currNode.getChildNodes().item(j).getTextContent();
                }
        }
        if (tableName != null) {
            flatstoragesColumns.put(tableName, new Integer[] { cstring, cbigInt, cdouble, cselect, ctext });
        }
    }

    //parse mappings
    nodes = (NodeList) xPath.evaluate("/flatstorageMeta/mapping", document, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        long assignment = Long.valueOf(currNode.getAttributes().getNamedItem("assid").getNodeValue());
        int level = Integer.valueOf(currNode.getAttributes().getNamedItem("lvl").getNodeValue());
        String storage = null;
        String columnname = null;
        final NodeList childNodes = currNode.getChildNodes();
        for (int c = 0; c < childNodes.getLength(); c++) {
            Node child = childNodes.item(c);
            if ("tblname".equals(child.getNodeName()))
                storage = child.getTextContent();
            else if ("colname".equals(child.getNodeName()))
                columnname = child.getTextContent();
        }
        if (storage == null || columnname == null)
            throw new Exception("Invalid flatstorage export: could not read storage or column name!");
        if (!flatAssignmentMapping.containsKey(storage))
            flatAssignmentMapping.put(storage, new HashMap<Integer, Map<String, Long>>(20));
        Map<Integer, Map<String, Long>> levelMap = flatAssignmentMapping.get(storage);
        if (!levelMap.containsKey(level))
            levelMap.put(level, new HashMap<String, Long>(30));
        Map<String, Long> columnMap = levelMap.get(level);
        if (!columnMap.containsKey(columnname))
            columnMap.put(columnname, assignment);
        //calculate position
        assignmentPositions.put(assignment,
                getAssignmentPosition(flatstoragesColumns.get(storage), columnname));
    }
    if (flatAssignmentMapping.size() == 0) {
        LOG.warn("No flatstorage assignments found to process!");
        return;
    }
    ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT);

    final String xpathStorage = "flatstorages/storage";
    final String xpathData = "flatstorages/storage/data";

    final PreparedStatement psGetAssInfo = con.prepareStatement(
            "SELECT DISTINCT a.APROPERTY,a.XALIAS,p.DATATYPE FROM " + DatabaseConst.TBL_STRUCT_ASSIGNMENTS
                    + " a, " + DatabaseConst.TBL_STRUCT_PROPERTIES + " p WHERE a.ID=? AND p.ID=a.APROPERTY");
    final Map<Long, Object[]> assignmentPropAlias = new HashMap<Long, Object[]>(assignmentPositions.size());
    final String insert1 = "INSERT INTO " + DatabaseConst.TBL_CONTENT_DATA +
    //1  2   3   4    5     6      =1     =1    =1     =1          7         8          9
            "(ID,VER,POS,LANG,TPROP,ASSIGN,XDEPTH,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISMLDEF,";
    final String insert2 = "(?,?,?,?,1,?,?,1,1,1,?,?,?,";
    final PreparedStatement psString = con
            .prepareStatement(insert1 + "FTEXT1024,UFTEXT1024,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psText = con
            .prepareStatement(insert1 + "FCLOB,UFCLOB,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psDouble = con
            .prepareStatement(insert1 + "FDOUBLE,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psNumber = con
            .prepareStatement(insert1 + "FINT,FSELECT,FBIGINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psLargeNumber = con
            .prepareStatement(insert1 + "FBIGINT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psFloat = con
            .prepareStatement(insert1 + "FFLOAT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psBoolean = con
            .prepareStatement(insert1 + "FBOOL,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psReference = con
            .prepareStatement(insert1 + "FREF,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psSelectOne = con
            .prepareStatement(insert1 + "FSELECT,FINT)VALUES" + insert2 + "?,?)");
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private String currentStorage = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            int insertCount = 0;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
                currentStorage = null;
                insertCount = 0;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                LOG.info("Imported [" + insertCount + "] flatstorage entries into the hierarchical storage");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpathData)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else if (currPath.toString().equals(xpathStorage)) {
                    currentStorage = attributes.getValue("name");
                    LOG.info("Processing storage: " + currentStorage);
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            @SuppressWarnings({ "UnusedDeclaration" })
            private void pushPath(String qName, Attributes att) {
                path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpathData)) {
                    //                        LOG.info("Insert [" + xpathData + "]: [" + data + "]");
                    inTag = false;
                    processData();
                    /*try {
                    if (insertMode) {
                        if (executeInsertPhase) {
                            processColumnSet(insertColumns, psInsert);
                            counter += psInsert.executeUpdate();
                        }
                    } else {
                        if (executeUpdatePhase) {
                            if (processColumnSet(updateSetColumns, psUpdate)) {
                                processColumnSet(updateClauseColumns, psUpdate);
                                counter += psUpdate.executeUpdate();
                            }
                        }
                    }
                    } catch (SQLException e) {
                    throw new SAXException(e);
                    } catch (ParseException e) {
                    throw new SAXException(e);
                    }*/
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            void processData() {
                //                    System.out.println("processing " + currentStorage + " -> " + data);
                final String[] cols = { "string", "bigint", "double", "select", "text" };
                for (String column : data.keySet()) {
                    if (column.endsWith("_mld"))
                        continue;
                    for (String check : cols) {
                        if (column.startsWith(check)) {
                            if ("select".equals(check) && "0".equals(data.get(column)))
                                continue; //dont insert 0-referencing selects
                            try {
                                insertData(column);
                            } catch (SQLException e) {
                                //noinspection ThrowableInstanceNeverThrown
                                throw new FxDbException(e, "ex.db.sqlError", e.getMessage())
                                        .asRuntimeException();
                            }
                        }
                    }
                }
            }

            private void insertData(String column) throws SQLException {
                final int level = Integer.parseInt(data.get("lvl"));
                long assignment = flatAssignmentMapping.get(currentStorage).get(level)
                        .get(column.toUpperCase());
                int pos = FxArrayUtils.getIntElementAt(data.get("positions"), ',',
                        assignmentPositions.get(assignment));
                String _valueData = data.get("valuedata");
                Integer valueData = _valueData == null ? null
                        : FxArrayUtils.getHexIntElementAt(data.get("valuedata"), ',',
                                assignmentPositions.get(assignment));
                Object[] propXP = getPropertyXPathDataType(assignment);
                long prop = (Long) propXP[0];
                String xpath = (String) propXP[1];
                FxDataType dataType;
                try {
                    dataType = FxDataType.getById((Long) propXP[2]);
                } catch (FxNotFoundException e) {
                    throw e.asRuntimeException();
                }
                long id = Long.parseLong(data.get("id"));
                int ver = Integer.parseInt(data.get("ver"));
                long lang = Integer.parseInt(data.get("lang"));
                boolean isMaxVer = "1".equals(data.get("ismax_ver"));
                boolean isLiveVer = "1".equals(data.get("islive_ver"));
                boolean mlDef = "1".equals(data.get(column + "_mld"));
                PreparedStatement ps;
                int vdPos;
                switch (dataType) {
                case String1024:
                    ps = psString;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Text:
                case HTML:
                    ps = psText;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Number:
                    ps = psNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case LargeNumber:
                    ps = psLargeNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Reference:
                    ps = psReference;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Float:
                    ps = psFloat;
                    ps.setFloat(10, Float.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Double:
                    ps = psDouble;
                    ps.setDouble(10, Double.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Boolean:
                    ps = psBoolean;
                    ps.setBoolean(10, "1".equals(data.get(column)));
                    vdPos = 11;
                    break;
                case SelectOne:
                    ps = psSelectOne;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                default:
                    //noinspection ThrowableInstanceNeverThrown
                    throw new FxInvalidParameterException("assignment",
                            "ex.structure.flatstorage.datatype.unsupported", dataType.name())
                                    .asRuntimeException();
                }
                ps.setLong(1, id);
                ps.setInt(2, ver);
                ps.setInt(3, pos);
                ps.setLong(4, lang);
                ps.setLong(5, prop);
                ps.setLong(6, assignment);
                ps.setBoolean(7, isMaxVer);
                ps.setBoolean(8, isLiveVer);
                ps.setBoolean(9, mlDef);
                if (valueData == null)
                    ps.setNull(vdPos, java.sql.Types.NUMERIC);
                else
                    ps.setInt(vdPos, valueData);
                ps.executeUpdate();
                insertCount++;
            }

            /**
             * Get property id, xpath and data type for an assignment
             *
             * @param assignment assignment id
             * @return Object[] {propertyId, xpath, datatype}
             */
            private Object[] getPropertyXPathDataType(long assignment) {
                if (assignmentPropAlias.get(assignment) != null)
                    return assignmentPropAlias.get(assignment);
                try {
                    psGetAssInfo.setLong(1, assignment);
                    ResultSet rs = psGetAssInfo.executeQuery();
                    if (rs != null && rs.next()) {
                        Object[] data = new Object[] { rs.getLong(1), rs.getString(2), rs.getLong(3) };
                        assignmentPropAlias.put(assignment, data);
                        return data;
                    }
                } catch (SQLException e) {
                    throw new IllegalArgumentException(
                            "Could not load data for assignment " + assignment + ": " + e.getMessage());
                }
                throw new IllegalArgumentException("Could not load data for assignment " + assignment + "!");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        parser.parse(zip.getInputStream(zeData), handler);
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psGetAssInfo, psString, psBoolean, psDouble,
                psFloat, psLargeNumber, psNumber, psReference, psSelectOne, psText);
    }
}

From source file:com.box.androidlib.BoxSynchronous.java

/**
 * Executes an Http request and triggers response parsing by the specified parser.
 * //from  w w w . j  a  v  a2s . c o  m
 * @param parser
 *            A BoxResponseParser configured to consume the response and capture data that is of interest
 * @param uri
 *            The Uri of the request
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 */
protected static void saxRequest(final DefaultResponseParser parser, final Uri uri) throws IOException {
    Uri theUri = uri;
    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        Uri.Builder builder = theUri.buildUpon();
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
        theUri = builder.build();
    }

    try {
        final XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xmlReader.setContentHandler(parser);
        HttpURLConnection conn = (HttpURLConnection) (new URL(theUri.toString())).openConnection();
        conn.setRequestProperty("User-Agent", BoxConfig.getInstance().getUserAgent());
        conn.setRequestProperty("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
        conn.setConnectTimeout(BoxConfig.getInstance().getConnectionTimeOut());
        if (mLoggingEnabled) {
            DevUtils.logcat("URL: " + theUri.toString());
            //                Iterator<String> keys = conn.getRequestProperties().keySet().iterator();
            //                while (keys.hasNext()) {
            //                    String key = keys.next();
            //                    DevUtils.logcat("Request Header: " + key + " => " + conn.getRequestProperties().get(key));
            //                }
        }

        int responseCode = -1;
        try {
            conn.connect();
            responseCode = conn.getResponseCode();
            if (mLoggingEnabled)
                DevUtils.logcat("Response Code: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                xmlReader.parse(new InputSource(inputStream));
                inputStream.close();
            } else if (responseCode == -1) {
                parser.setStatus(ResponseListener.STATUS_UNKNOWN_HTTP_RESPONSE_CODE);
            }
        } catch (IOException e) {
            try {
                responseCode = conn.getResponseCode();
            } catch (NullPointerException ee) {
                // Honeycomb devices seem to throw a null pointer exception sometimes which traces to HttpURLConnectionImpl.
            }
            // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
            if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
                parser.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
            } else {
                throw e;
            }
        } finally {
            conn.disconnect();
        }
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    } catch (final SAXException e) {
        e.printStackTrace();
    } catch (final FactoryConfigurationError e) {
        e.printStackTrace();
    }
}

From source file:cm.aptoide.pt.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    AptoideThemePicker.setAptoideTheme(this);
    super.onCreate(savedInstanceState);

    serviceDownloadManagerIntent = new Intent(this, ServiceDownloadManager.class);
    startService(serviceDownloadManagerIntent);
    mContext = this;

    File sdcard_file = new File(SDCARD);
    if (!sdcard_file.exists() || !sdcard_file.canWrite()) {
        View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null);
        Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
        final AlertDialog noSDDialog = dialogBuilder.create();
        noSDDialog.setTitle(getText(R.string.remote_in_noSD_title));
        noSDDialog.setIcon(android.R.drawable.ic_dialog_alert);
        TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
        message.setText(getText(R.string.remote_in_noSD));
        noSDDialog.setCancelable(false);
        noSDDialog.setButton(Dialog.BUTTON_NEUTRAL, getString(android.R.string.ok),
                new Dialog.OnClickListener() {
                    @Override/*  w ww  .j  a  v  a  2 s.  c  om*/
                    public void onClick(DialogInterface arg0, int arg1) {
                        finish();
                    }
                });
        noSDDialog.show();
    } else {
        StatFs stat = new StatFs(sdcard_file.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        long availableBlocks = stat.getAvailableBlocks();

        long total = (blockSize * totalBlocks) / 1024 / 1024;
        long avail = (blockSize * availableBlocks) / 1024 / 1024;
        Log.d("Aptoide", "* * * * * * * * * *");
        Log.d("Aptoide", "Total: " + total + " Mb");
        Log.d("Aptoide", "Available: " + avail + " Mb");

        if (avail < 10) {
            Log.d("Aptoide", "No space left on SDCARD...");
            Log.d("Aptoide", "* * * * * * * * * *");
            View simpleView = LayoutInflater.from(this).inflate(R.layout.dialog_simple_layout, null);
            Builder dialogBuilder = new AlertDialog.Builder(this).setView(simpleView);
            final AlertDialog noSpaceDialog = dialogBuilder.create();
            noSpaceDialog.setIcon(android.R.drawable.ic_dialog_alert);
            TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
            message.setText(getText(R.string.remote_in_noSDspace));
            noSpaceDialog.setButton(Dialog.BUTTON_NEUTRAL, getText(android.R.string.ok),
                    new Dialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            finish();
                        }
                    });
            noSpaceDialog.show();
        } else {

            SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(mContext);
            editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();

            if (!sPref.contains("matureChkBox")) {

                editor.putBoolean("matureChkBox", ApplicationAptoide.MATURECONTENTSWITCHVALUE);
                SharedPreferences sPrefOld = getSharedPreferences("aptoide_prefs", MODE_PRIVATE);
                if (sPrefOld.getString("app_rating", "none").equals("Mature")) {
                    editor.putBoolean("matureChkBox", false);
                }

            }

            if (!sPref.contains("version")) {

                ApplicationAptoide.setRestartLauncher(true);
                try {
                    editor.putInt("version",
                            getPackageManager().getPackageInfo(getPackageName(), 0).versionCode);
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }

            }

            if (sPref.getString("myId", null) == null) {
                String rand_id = UUID.randomUUID().toString();
                editor.putString("myId", rand_id);
            }

            if (sPref.getInt("scW", 0) == 0 || sPref.getInt("scH", 0) == 0) {
                DisplayMetrics dm = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                editor.putInt("scW", dm.widthPixels);
                editor.putInt("scH", dm.heightPixels);
            }
            editor.commit();
            File file = new File(LOCAL_PATH + "/apks");
            if (!file.exists()) {
                file.mkdirs();
            }

            new Thread(new Runnable() {

                @Override
                public void run() {

                    // Note the L that tells the compiler to interpret the
                    // number as a Long
                    final long MAXFILEAGE = 2678400000L; // 1 month in
                    // milliseconds

                    // Get file handle to the directory. In this case the
                    // application files dir
                    File dir = new File(LOCAL_PATH + "/apks");

                    // Optain list of files in the directory.
                    // listFiles() returns a list of File objects to each
                    // file found.
                    File[] files = dir.listFiles();

                    // Loop through all files
                    for (File f : files) {

                        // Get the last modified date. Miliseconds since
                        // 1970
                        long lastmodified = f.lastModified();

                        // Do stuff here to deal with the file..
                        // For instance delete files older than 1 month
                        if (lastmodified + MAXFILEAGE < System.currentTimeMillis()) {
                            f.delete();
                        }
                    }
                }
            }).start();
            db = Database.getInstance();

            Intent i = new Intent(mContext, MainService.class);
            startService(i);
            bindService(i, conn, Context.BIND_AUTO_CREATE);
            order = Order.values()[PreferenceManager.getDefaultSharedPreferences(mContext).getInt("order_list",
                    0)];

            registerReceiver(updatesReceiver, new IntentFilter("update"));
            registerReceiver(statusReceiver, new IntentFilter("status"));
            registerReceiver(loginReceiver, new IntentFilter("login"));
            registerReceiver(storePasswordReceiver, new IntentFilter("401"));
            registerReceiver(redrawInstalledReceiver, new IntentFilter("pt.caixamagica.aptoide.REDRAW"));
            if (!ApplicationAptoide.MULTIPLESTORES) {
                registerReceiver(parseFailedReceiver, new IntentFilter("PARSE_FAILED"));
            }

            registerReceiver(newRepoReceiver, new IntentFilter("pt.caixamagica.aptoide.NEWREPO"));
            registered = true;

            categoriesStrings = new HashMap<String, Integer>();

            //            categoriesStrings.put("Applications", R.string.applications);

            boolean serversFileIsEmpty = true;

            if (sPref.getBoolean("firstrun", true)) {
                // Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
                // shortcutIntent.setClassName("cm.aptoide.pt",
                // "cm.aptoide.pt.Start");
                // final Intent intent = new Intent();
                // intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
                // shortcutIntent);
                //
                // intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                // getString(R.string.app_name));
                // Parcelable iconResource =
                // Intent.ShortcutIconResource.fromContext(this,
                // R.drawable.ic_launcher);
                //
                // intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                // iconResource);
                // intent.putExtra("duplicate", false);
                // intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
                // sendBroadcast(intent);

                if (new File(LOCAL_PATH + "/servers.xml").exists()
                        && ApplicationAptoide.DEFAULTSTORENAME == null) {
                    try {

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

                        MyappHandler handler = new MyappHandler();

                        sp.parse(new File(LOCAL_PATH + "/servers.xml"), handler);
                        ArrayList<String> server = handler.getServers();
                        if (server.isEmpty()) {
                            serversFileIsEmpty = true;
                        } else {
                            getIntent().putExtra("newrepo", server);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                editor.putBoolean("firstrun", false);
                editor.putBoolean("orderByCategory", true);
                editor.commit();
            }

            if (getIntent().hasExtra("newrepo")) {
                ArrayList<String> repos = (ArrayList<String>) getIntent().getSerializableExtra("newrepo");
                for (final String uri2 : repos) {
                    View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout,
                            null);
                    Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
                    final AlertDialog addNewRepoDialog = dialogBuilder.create();
                    addNewRepoDialog.setTitle(getString(R.string.add_store));
                    addNewRepoDialog.setIcon(android.R.drawable.ic_menu_add);

                    TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
                    message.setText((getString(R.string.newrepo_alrt) + uri2 + " ?"));

                    addNewRepoDialog.setCancelable(false);
                    addNewRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes),
                            new Dialog.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    dialogAddStore(uri2, null, null);
                                }
                            });
                    addNewRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no),
                            new Dialog.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int arg1) {
                                    dialog.cancel();
                                }
                            });
                    addNewRepoDialog.show();
                }
            } else if (db.getStores(false).getCount() == 0 && ApplicationAptoide.DEFAULTSTORENAME == null
                    && serversFileIsEmpty) {
                View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null);
                Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
                final AlertDialog addAppsRepoDialog = dialogBuilder.create();
                addAppsRepoDialog.setTitle(getString(R.string.add_store));
                addAppsRepoDialog.setIcon(android.R.drawable.ic_menu_add);
                TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
                message.setText(getString(R.string.myrepo_alrt) + "\n" + "http://apps.store.aptoide.com/");
                addAppsRepoDialog.setCancelable(false);
                addAppsRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes),
                        new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                dialogAddStore("http://apps.store.aptoide.com", null, null);
                            }
                        });
                addAppsRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no),
                        new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.cancel();
                            }
                        });
                addAppsRepoDialog.show();
            }

            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        getUpdateParameters();
                        if (getPackageManager().getPackageInfo(getPackageName(), 0).versionCode < Integer
                                .parseInt(updateParams.get("versionCode"))) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    requestUpdateSelf();
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }

        featuredView = LayoutInflater.from(mContext).inflate(R.layout.page_featured, null);
        availableView = LayoutInflater.from(mContext).inflate(R.layout.page_available, null);
        updateView = LayoutInflater.from(mContext).inflate(R.layout.page_updates, null);
        banner = (LinearLayout) availableView.findViewById(R.id.banner);
        breadcrumbs = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.breadcrumb_container, null);
        installedView = new ListView(mContext);
        updatesListView = (ListView) updateView.findViewById(R.id.updates_list);

        availableListView = (ListView) availableView.findViewById(R.id.available_list);
        joinStores = (CheckBox) availableView.findViewById(R.id.join_stores);

        availableAdapter = new AvailableListAdapter(mContext, null,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        installedAdapter = new InstalledAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER,
                db);
        updatesAdapter = new UpdatesAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        pb = (TextView) availableView.findViewById(R.id.loading_pb);
        addStoreButton = availableView.findViewById(R.id.add_store);

        bannerStoreAvatar = (ImageView) banner.findViewById(R.id.banner_store_avatar);
        bannerStoreName = (TextView) banner.findViewById(R.id.banner_store_name);
        bannerStoreDescription = (AutoScaleTextView) banner.findViewById(R.id.banner_store_description);
    }
}

From source file:com.connectsdk.service.NetcastTVService.java

private JSONObject parseVolumeXmlToJSON(String data) {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {// w  w  w .j  a  v  a2  s  . c  o m
        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;
}

From source file:com.connectsdk.service.NetcastTVService.java

private int parseAppNumberXmlToJSON(String data) {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {//from w ww  . j  a v a2 s  . c om
        InputStream stream = new ByteArrayInputStream(data.getBytes("UTF-8"));

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

        return handler.getApplicationNumber();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}