List of usage examples for android.util Xml newPullParser
public static XmlPullParser newPullParser()
From source file:com.googlecode.CallerLookup.Main.java
public void parseLookupEntries() { mLookupEntries = new HashMap<String, LookupEntry>(); mUserLookupEntries = new HashMap<String, LookupEntry>(); boolean updateFound = false; for (String fileName : getApplicationContext().fileList()) { if (fileName.equals(UPDATE_FILE)) { try { FileInputStream file = getApplicationContext().openFileInput(UPDATE_FILE); XmlPullParser xml = Xml.newPullParser(); xml.setInput(file, null); parseLookupEntries(xml, mLookupEntries); file.close();/*from ww w. j a v a 2 s . c o m*/ updateFound = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (fileName.equals(SAVED_FILE)) { try { FileInputStream file = getApplicationContext().openFileInput(SAVED_FILE); InputStreamReader reader = new InputStreamReader(file); char[] content = new char[8000]; reader.read(content); JSONArray userLookupEntries = new JSONArray(new String(content)); int count = userLookupEntries.length(); for (int i = 0; i < count; i++) { JSONObject userLookupEntry = userLookupEntries.getJSONObject(i); mUserLookupEntries.put(userLookupEntry.getString("name"), new LookupEntry(userLookupEntry)); } file.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } if (!updateFound) { XmlResourceParser xml = getApplicationContext().getResources().getXml(R.xml.lookups); parseLookupEntries(xml, mLookupEntries); xml.close(); } }
From source file:org.schabi.newpipe.services.youtube.YoutubeVideoExtractor.java
private VideoInfo.AudioStream[] parseDashManifest(String dashManifest, String decryptoinCode) { if (!dashManifest.contains("/signature/")) { String encryptedSig = matchGroup1("/s/([a-fA-F0-9\\.]+)", dashManifest); String decryptedSig;// ww w . j a va 2 s .co m decryptedSig = decryptSignature(encryptedSig, decryptoinCode); dashManifest = dashManifest.replace("/s/" + encryptedSig, "/signature/" + decryptedSig); } String dashDoc = Downloader.download(dashManifest); Vector<VideoInfo.AudioStream> audioStreams = new Vector<>(); try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(new StringReader(dashDoc)); int eventType = parser.getEventType(); String tagName = ""; String currentMimeType = ""; int currentBandwidth = -1; int currentSamplingRate = -1; boolean currentTagIsBaseUrl = false; while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: tagName = parser.getName(); if (tagName.equals("AdaptationSet")) { currentMimeType = parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "mimeType"); } else if (tagName.equals("Representation") && currentMimeType.contains("audio")) { currentBandwidth = Integer .parseInt(parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "bandwidth")); currentSamplingRate = Integer.parseInt( parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "audioSamplingRate")); } else if (tagName.equals("BaseURL")) { currentTagIsBaseUrl = true; } break; case XmlPullParser.TEXT: if (currentTagIsBaseUrl && (currentMimeType.contains("audio"))) { int format = -1; if (currentMimeType.equals(MediaFormat.WEBMA.mimeType)) { format = MediaFormat.WEBMA.id; } else if (currentMimeType.equals(MediaFormat.M4A.mimeType)) { format = MediaFormat.M4A.id; } audioStreams.add(new VideoInfo.AudioStream(parser.getText(), format, currentBandwidth, currentSamplingRate)); } case XmlPullParser.END_TAG: if (tagName.equals("AdaptationSet")) { currentMimeType = ""; } else if (tagName.equals("BaseURL")) { currentTagIsBaseUrl = false; } break; default: } eventType = parser.next(); } } catch (Exception e) { e.printStackTrace(); } return audioStreams.toArray(new VideoInfo.AudioStream[audioStreams.size()]); }
From source file:biz.varkon.shelvesom.server.ServerInfo.java
/** * Parses a valid XML response from the specified input stream. This method * must invoke parse//w w w . j a v a 2 s . com * {@link ResponseParser#parseResponse(org.xmlpull.v1.XmlPullParser)} if the * XML response is valid, or throw an exception if it is not. * * @param in * The input stream containing the response sent by the web * service. * @param responseParser * The parser to use when the response is valid. * * @throws java.io.IOException */ public static void parseResponse(InputStream in, ResponseParser responseParser, IOUtilities.inputTypes inputType) throws IOException { final XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new InputStreamReader(in)); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } String name; boolean valid = false; final int topDepth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > topDepth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_REQUEST.equals(name)) { valid = isRequestValid(parser); break; } } if (valid) responseParser.parseResponse(parser); } catch (XmlPullParserException e) { final IOException ioe = new IOException("Could not parse the response"); ioe.initCause(e); throw ioe; } }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
@SuppressWarnings("unchecked") protected T transform(String url, byte[] data, AjaxStatus status) { if (type == null) { return null; }/* www. j a v a 2s. c om*/ File file = status.getFile(); if (data != null) { if (type.equals(Bitmap.class)) { return (T) BitmapFactory.decodeByteArray(data, 0, data.length); } if (type.equals(JSONObject.class)) { JSONObject result = null; String str = null; try { str = new String(data, encoding); result = (JSONObject) new JSONTokener(str).nextValue(); } catch (Exception e) { AQUtility.debug(e); AQUtility.debug(str); } return (T) result; } if (type.equals(JSONArray.class)) { JSONArray result = null; try { String str = new String(data, encoding); result = (JSONArray) new JSONTokener(str).nextValue(); } catch (Exception e) { AQUtility.debug(e); } return (T) result; } if (type.equals(String.class)) { String result = null; if (status.getSource() == AjaxStatus.NETWORK) { AQUtility.debug("network"); result = correctEncoding(data, encoding, status); } else { AQUtility.debug("file"); try { result = new String(data, encoding); } catch (Exception e) { AQUtility.debug(e); } } return (T) result; } /* * if(type.equals(XmlDom.class)){ XmlDom result = null; try { result = new XmlDom(data); } catch (Exception * e) { AQUtility.debug(e); } return (T) result; } */ if (type.equals(byte[].class)) { return (T) data; } if (transformer != null) { return transformer.transform(url, type, encoding, data, status); } if (st != null) { return st.transform(url, type, encoding, data, status); } } else if (file != null) { if (type.equals(File.class)) { return (T) file; } if (type.equals(XmlDom.class)) { XmlDom result = null; try { FileInputStream fis = new FileInputStream(file); result = new XmlDom(fis); status.closeLater(fis); } catch (Exception e) { AQUtility.report(e); return null; } return (T) result; } if (type.equals(XmlPullParser.class)) { XmlPullParser parser = Xml.newPullParser(); try { FileInputStream fis = new FileInputStream(file); parser.setInput(fis, encoding); status.closeLater(fis); } catch (Exception e) { AQUtility.report(e); return null; } return (T) parser; } if (type.equals(InputStream.class)) { try { FileInputStream fis = new FileInputStream(file); status.closeLater(fis); return (T) fis; } catch (Exception e) { AQUtility.report(e); return null; } } } return null; }
From source file:org.zywx.wbpalmstar.plugin.chatkeyboard.ACEChatKeyboardView.java
/** * Reading all emoticons in local cache//from ww w .j ava2 s . c o m */ private void initEmojicons() { InputStream in = null; try { String xmlPath = mEmojiconsXmlPath.substring(BUtility.F_Widget_RES_SCHEMA.length()); String emojiconsFolder = BUtility.F_Widget_RES_path + xmlPath.substring(0, xmlPath.lastIndexOf("/") + 1); String resXmlPath = BUtility.F_Widget_RES_path + xmlPath; in = getContext().getAssets().open(resXmlPath); XmlPullParser parser = Xml.newPullParser(); parser.setInput(in, "utf-8"); int tokenType = 0; boolean needContinue = true; do { tokenType = parser.next(); switch (tokenType) { case XmlPullParser.START_TAG: String localName = (parser.getName()).toLowerCase(); if ("emojicons".equals(localName)) { mEmojiconsDeletePath = emojiconsFolder + parser.getAttributeValue(null, "delete"); } else if ("key".equals(localName)) { mEmojiconsText.add(parser.nextText()); } else if ("string".equals(localName)) { mEmojiconsPath.add(emojiconsFolder + parser.nextText()); } break; case XmlPullParser.END_DOCUMENT: needContinue = false; break; } } while (needContinue); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); in = null; } catch (IOException e1) { e1.printStackTrace(); } } } NUMBER_OF_EMOJICONS = mEmojiconsPath.size(); }
From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java
@SuppressWarnings("unchecked") protected T transform(String url, byte[] data, AjaxStatus status) { if (type == null) { return null; }/* w w w .ja v a2 s . com*/ File file = status.getFile(); if (data != null) { if (type.equals(Bitmap.class)) { return (T) BitmapFactory.decodeByteArray(data, 0, data.length); } if (type.equals(JSONObject.class)) { JSONObject result = null; String str = null; try { str = new String(data, encoding); result = (JSONObject) new JSONTokener(str).nextValue(); } catch (Exception e) { AQUtility.debug(e); AQUtility.debug(str); } return (T) result; } if (type.equals(JSONArray.class)) { JSONArray result = null; try { String str = new String(data, encoding); result = (JSONArray) new JSONTokener(str).nextValue(); } catch (Exception e) { AQUtility.debug(e); } return (T) result; } if (type.equals(String.class)) { String result = null; if (status.getSource() == AjaxStatus.NETWORK) { AQUtility.debug("network"); result = correctEncoding(data, encoding, status); } else { AQUtility.debug("file"); try { result = new String(data, encoding); } catch (Exception e) { AQUtility.debug(e); } } return (T) result; } /* if(type.equals(XmlDom.class)){ XmlDom result = null; try { result = new XmlDom(data); } catch (Exception e) { AQUtility.debug(e); } return (T) result; } */ if (type.equals(byte[].class)) { return (T) data; } if (transformer != null) { return transformer.transform(url, type, encoding, data, status); } if (st != null) { return st.transform(url, type, encoding, data, status); } } else if (file != null) { if (type.equals(File.class)) { return (T) file; } if (type.equals(XmlDom.class)) { XmlDom result = null; try { FileInputStream fis = new FileInputStream(file); result = new XmlDom(fis); status.closeLater(fis); } catch (Exception e) { AQUtility.report(e); return null; } return (T) result; } if (type.equals(XmlPullParser.class)) { XmlPullParser parser = Xml.newPullParser(); try { FileInputStream fis = new FileInputStream(file); parser.setInput(fis, encoding); status.closeLater(fis); } catch (Exception e) { AQUtility.report(e); return null; } return (T) parser; } if (type.equals(InputStream.class)) { try { FileInputStream fis = new FileInputStream(file); status.closeLater(fis); return (T) fis; } catch (Exception e) { AQUtility.report(e); return null; } } } return null; }
From source file:fr.outadev.android.timeo.TimeoRequestHandler.java
/** * Gets an XmlPullParser for an XML string. * * @param xml an xml document in a String, sexy * @return an XmlPullParser ready to parse the document *//*from ww w .ja v a 2 s . co m*/ private static XmlPullParser getParserForXMLString(String xml) throws XmlPullParserException, IOException { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(new StringReader(xml)); parser.nextTag(); return parser; }
From source file:org.ohmage.db.DbHelper.java
/** * Utility method that populates the Survey and SurveyPrompt tables for the * campaign identified by campaignUrn and containing the given xml as * campaignXML.//from w ww .j a v a2 s . co m * * Note that this method takes a db handle so that it can be used in a * transaction. * * @param db * a handle to an existing writable db * @param campaignUrn * the urn of the campaign for which we're populating subtables * @param campaignXML * the XML for the campaign (not validated by this method) * @return * */ public boolean populateSurveysFromCampaignXML(SQLiteDatabase db, String campaignUrn, String campaignXML) { try { // dump all the surveys (and consequently survey prompts) before we // do anything // this is (perhaps surprisingly) desired behavior, as the surveys + // survey prompts // should always reflect the state of the campaign XML, valid or not db.delete(Tables.SURVEYS, Surveys.CAMPAIGN_URN + "=?", new String[] { campaignUrn }); // do a pass over the XML to gather surveys and survey prompts XmlPullParser xpp = Xml.newPullParser(); xpp.setInput(new ByteArrayInputStream(campaignXML.getBytes("UTF-8")), "UTF-8"); int eventType = xpp.getEventType(); String tagName; // various stacks to maintain state while walking through the xml // tree Stack<String> tagStack = new Stack<String>(); Survey curSurvey = null; // valid only within a survey, null // otherwise Vector<SurveyPrompt> prompts = new Vector<SurveyPrompt>(); // valid // only // within // a // survey, // empty // otherwise Vector<JSONObject> properties = new Vector<JSONObject>(); // valid // only // within // a // prompt, // empty // otherwise // iterate through the xml, paying attention only to surveys and // prompts // note that this does no validation outside of preventing itself // from crashing catastrophically while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); tagStack.push(tagName); if (tagName.equalsIgnoreCase("survey")) { if (curSurvey != null) throw new XmlPullParserException("encountered a survey tag inside another survey tag"); curSurvey = new Survey(); curSurvey.mCampaignUrn = campaignUrn; } else if (tagName.equalsIgnoreCase("prompt")) { SurveyPrompt sp = new SurveyPrompt(); // FIXME: add the campaign + survey ID to make lookups // easier? prompts.add(sp); } else if (tagName.equalsIgnoreCase("property")) { properties.add(new JSONObject()); } } else if (eventType == XmlPullParser.TEXT) { if (tagStack.size() >= 2) { // we may be in an entity>property situation, so check // and assign accordingly if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("survey")) { // populating the current survey object with its // properties here if (tagStack.peek().equalsIgnoreCase("id")) curSurvey.mSurveyID = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("title")) curSurvey.mTitle = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("description")) curSurvey.mDescription = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("submitText")) curSurvey.mSubmitText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("showSummary")) curSurvey.mShowSummary = xpp.getText().equals("true") ? true : false; else if (tagStack.peek().equalsIgnoreCase("editSummary")) curSurvey.mEditSummary = xpp.getText().equals("true") ? true : false; else if (tagStack.peek().equalsIgnoreCase("summaryText")) curSurvey.mSummaryText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("introText")) curSurvey.mIntroText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("anytime")) curSurvey.mAnytime = xpp.getText().equals("true") ? true : false; } else if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("prompt")) { SurveyPrompt sp = prompts.lastElement(); // populating the last encountered survey prompt // with its properties here if (tagStack.peek().equalsIgnoreCase("id")) sp.mPromptID = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("promptText")) sp.mPromptText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("promptType")) sp.mPromptType = xpp.getText(); } else if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("property")) { JSONObject curProperty = properties.lastElement(); // populating the last encountered property if (tagStack.peek().equalsIgnoreCase("key")) curProperty.put("key", xpp.getText()); else if (tagStack.peek().equalsIgnoreCase("label")) curProperty.put("label", xpp.getText()); else if (tagStack.peek().equalsIgnoreCase("value")) curProperty.put("value", xpp.getText()); } } } else if (eventType == XmlPullParser.END_TAG) { tagName = xpp.getName(); tagStack.pop(); if (tagName.equalsIgnoreCase("survey")) { // store the current survey to the database long surveyPID = db.insert(Tables.SURVEYS, null, curSurvey.toCV()); // also store all the prompts we accumulated for it for (SurveyPrompt sp : prompts) { sp.mSurveyID = curSurvey.mSurveyID; sp.mSurveyPID = surveyPID; sp.mCompositeID = curSurvey.mCampaignUrn + ":" + curSurvey.mSurveyID; db.insert(Tables.SURVEY_PROMPTS, null, sp.toCV()); } // flush the prompts we've stored up so far prompts.clear(); // Create Streams here OhmagePDVManager.getInstance().createStreamForSurvey(campaignUrn, curSurvey.mSurveyID); // and clear us from being in any survey curSurvey = null; } else if (tagName.equalsIgnoreCase("prompt")) { SurveyPrompt sp = prompts.lastElement(); // update the current prompt with the collected // properties JSONArray propertyArray = new JSONArray(); for (JSONObject property : properties) propertyArray.put(property); // encode it as json and stuff it in the surveyprompt sp.mProperties = propertyArray.toString(); // and wipe the properties properties.clear(); } } eventType = xpp.next(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; }
From source file:org.zywx.wbpalmstar.plugin.chatkeyboard.ACEChatKeyboardView.java
private void initShares() { InputStream in = null;/*w w w .j a va 2s . c om*/ try { String xmlPath = mSharesXmlPath.substring(BUtility.F_Widget_RES_SCHEMA.length()); String sharesFolder = BUtility.F_Widget_RES_path + xmlPath.substring(0, xmlPath.lastIndexOf("/") + 1); String resXmlPath = BUtility.F_Widget_RES_path + xmlPath; in = getContext().getAssets().open(resXmlPath); XmlPullParser parser = Xml.newPullParser(); parser.setInput(in, "utf-8"); int tokenType = 0; boolean needContinue = true; do { tokenType = parser.next(); switch (tokenType) { case XmlPullParser.START_TAG: String localName = (parser.getName()).toLowerCase(); if ("key".equals(localName)) { mSharesText.add(parser.nextText()); } else if ("string".equals(localName)) { mSharesPath.add(sharesFolder + parser.nextText()); } break; case XmlPullParser.END_DOCUMENT: needContinue = false; break; } } while (needContinue); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); in = null; } catch (IOException e1) { e1.printStackTrace(); } } } NUMBER_OF_SHARES = mSharesPath.size(); }
From source file:android.support.v7.internal.widget.ActivityChooserModel.java
/** * Command for reading the historical records from a file off the UI thread. *//* w w w .j av a 2 s . c o m*/ private void readHistoricalDataImpl() { FileInputStream fis = null; try { fis = mContext.openFileInput(mHistoryFileName); } catch (FileNotFoundException fnfe) { if (DEBUG) { Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName); } return; } try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(fis, null); int type = XmlPullParser.START_DOCUMENT; while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) { type = parser.next(); } if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) { throw new XmlPullParserException( "Share records file does not start with " + TAG_HISTORICAL_RECORDS + " tag."); } List<HistoricalRecord> historicalRecords = mHistoricalRecords; historicalRecords.clear(); while (true) { type = parser.next(); if (type == XmlPullParser.END_DOCUMENT) { break; } if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { continue; } String nodeName = parser.getName(); if (!TAG_HISTORICAL_RECORD.equals(nodeName)) { throw new XmlPullParserException("Share records file not well-formed."); } String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY); final long time = Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME)); final float weight = Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT)); HistoricalRecord readRecord = new HistoricalRecord(activity, time, weight); historicalRecords.add(readRecord); if (DEBUG) { Log.i(LOG_TAG, "Read " + readRecord.toString()); } } if (DEBUG) { Log.i(LOG_TAG, "Read " + historicalRecords.size() + " historical records."); } } catch (XmlPullParserException xppe) { Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe); } catch (IOException ioe) { Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { /* ignore */ } } } }