/** * Parse the repository. * * @param parser * @throws Exception */ private void parseRepository(XmlPullParser parser) throws Exception { try { parser.require(XmlPullParser.START_DOCUMENT, null, null); parser.nextTag(); if (parser.getName().equals("bundles")) parseOscar(parser); else { parser.require(XmlPullParser.START_TAG, null, "repository"); date = parser.getAttributeValue(null, "lastmodified"); name = parser.getAttributeValue(null, "name"); if (name == null) name = "Untitled"; while (parser.nextTag() == XmlPullParser.START_TAG) { if (parser.getName().equals("resource")) { ResourceImpl resource = new ResourceImpl(this, parser); resources.add(resource); } else if (parser.getName().equals("referral")) referral(parser); else throw new IllegalArgumentException( "Invalid tag in repository: " + url + " " + parser.getName()); } parser.require(XmlPullParser.END_TAG, null, "repository"); } } catch (XmlPullParserException e) { e.printStackTrace(); throw new IllegalArgumentException( "XML unregognized around: " + e.getLineNumber() + " " + e.getMessage()); } }
public List<Bird> parseXML(Context context) { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); InputStream stream = context.getResources().openRawResource(com.example.birdnote.R.raw.birds); xpp.setInput(stream, null); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { handleStartTag(xpp.getName()); } else if (eventType == XmlPullParser.END_TAG) { currentTag = null; } else if (eventType == XmlPullParser.TEXT) { handleText(xpp.getText()); } eventType = xpp.next(); } } catch (NotFoundException e) { Log.d(LOGTAG, e.getMessage()); } catch (XmlPullParserException e) { Log.d(LOGTAG, e.getMessage()); } catch (IOException e) { Log.d(LOGTAG, e.getMessage()); } return birds; }
private List<String> checkAssets(IProgress progress) { String fv = Version.getFullVersion(context); if (!fv.equalsIgnoreCase(context.getSettings().PREVIOUS_INSTALLED_VERSION.get())) { File applicationDataDir = context.getAppPath(null); applicationDataDir.mkdirs(); if (applicationDataDir.canWrite()) { try { progress.startTask(context.getString(R.string.installing_new_resources), -1); AssetManager assetManager = context.getAssets(); boolean isFirstInstall = context.getSettings().PREVIOUS_INSTALLED_VERSION.get().equals(""); unpackBundledAssets(assetManager, applicationDataDir, progress, isFirstInstall); context.getSettings().PREVIOUS_INSTALLED_VERSION.set(fv); copyRegionsBoundaries(); copyPoiTypes(); for (String internalStyle : context.getRendererRegistry().getInternalRenderers().keySet()) { File fl = context.getRendererRegistry().getFileForInternalStyle(internalStyle); if (fl.exists()) { context.getRendererRegistry().copyFileForInternalStyle(internalStyle); } } } catch (SQLiteException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } catch (XmlPullParserException e) { log.error(e.getMessage(), e); } } } return Collections.emptyList(); }
@SuppressWarnings("unchecked") public synchronized T inflate(XmlPullParser parser, P root, boolean attachToRoot) { final AttributeSet attrs = Xml.asAttributeSet(parser); T result = (T) root; try { int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {; } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } T xmlRoot = createItemFromTag(parser, parser.getName(), attrs); result = (T) onMergeRoots(root, attachToRoot, (P) xmlRoot); rInflate(parser, result, attrs); } catch (InflateException e) { throw e; } catch (XmlPullParserException e) { InflateException ex = new InflateException(e.getMessage()); ex.initCause(e); throw ex; } catch (IOException e) { InflateException ex = new InflateException(parser.getPositionDescription() + ": " + e.getMessage()); ex.initCause(e); throw ex; } return result; }
public void testParse20100823_departure() { TravelDelayParser parser = null; try { parser = getParser(); parser.setEncoding("EUC-JP"); parser.setAirline(true); parser.setArrival(false); } catch (XmlPullParserException e) { e.printStackTrace(); fail(e.getMessage()); } TravelDelayResult result = null; try { result = parser.parse( getClass().getResourceAsStream("/delay/travel_delay_result_detail_20100823.html")); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertEquals(1, result.getCategories().size()); Category c = result.getCategories().get(0); OperationCompany oc = c.getOperationCompanies().get(0); assertEquals(4, oc.getTravelDelays().size()); TravelDelay td = oc.getTravelDelays().get(3); assertEquals("08/23 08:30", td.getDate()); assertEquals("日本航空", td.getAirline()); assertEquals("旭川", td.getPlace()); assertEquals("JAL1103便(羽田→旭川) は出発に遅れが出ています。07:25→08:29", td.getCondition()); }
public void testParse20100823_arrival() { TravelDelayParser parser = null; try { parser = getParser(); parser.setEncoding("EUC-JP"); parser.setAirline(true); parser.setArrival(true); } catch (XmlPullParserException e) { e.printStackTrace(); fail(e.getMessage()); } TravelDelayResult result = null; try { result = parser.parse( getClass().getResourceAsStream("/delay/travel_delay_result_detail_20100823.html")); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertEquals(1, result.getCategories().size()); Category c = result.getCategories().get(0); OperationCompany oc = c.getOperationCompanies().get(0); assertEquals(3, oc.getTravelDelays().size()); TravelDelay td = oc.getTravelDelays().get(1); assertEquals("08/23 11:30", td.getDate()); assertEquals("全日本空輸", td.getAirline()); assertEquals("三宅島", td.getPlace()); assertEquals("定刻13:40着 ANA1850便(三宅島→羽田) は欠航です。", td.getCondition()); }
protected synchronized void parse(XmlPullParser parser) throws XmlParseException, IOException { try { parser.nextTag(); parseElement(parser); } catch (XmlPullParserException e) { throw new XmlParseException(parser, e.getMessage(), e); } }
public synchronized void parse(Reader reader) throws XmlParseException, IOException { try { XmlPullParser parser = createParser(); parser.setInput(reader); parse(parser); } catch (XmlPullParserException e) { throw new XmlParseException(getParser(), e.getMessage(), e); } }
/** * Load the STUN configuration from a stream. * * @param stunConfigStream An InputStream with the configuration file. * @return A list of loaded servers */ public ArrayList loadSTUNServers(java.io.InputStream stunConfigStream) { final ArrayList serversList = new ArrayList(); String serverName; int serverPort; try { final XmlPullParser parser = new MXParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); parser.setInput(stunConfigStream, "UTF-8"); int eventType = parser.getEventType(); do { if (eventType == XmlPullParser.START_TAG) { // Parse a STUN server definition if (parser.getName().equals("stunServer")) { serverName = null; serverPort = -1; // Parse the hostname parser.next(); parser.next(); serverName = parser.nextText(); // Parse the port parser.next(); parser.next(); try { serverPort = Integer.parseInt(parser.nextText()); } catch (final Exception e) { } // If we have a valid hostname and port, add // it to the list. if (serverName != null && serverPort != -1) { final STUNService service = new STUNService(serverName, serverPort); serversList.add(service); } } } eventType = parser.next(); } while (eventType != XmlPullParser.END_DOCUMENT); } catch (final XmlPullParserException e) { LOGGER.error(e.getMessage(), e); } catch (final IOException e) { LOGGER.error(e.getMessage(), e); } currentServer = bestSTUNServer(serversList); return serversList; }
public Rest saveAddress(Map<String, String> data) { String path = "checkout/saveShippingAddress"; String response = this.request(path, Rest.METHOD_POST, data); try { mResponseMessage = this.getFormSaveStatus(response); } catch (XmlPullParserException xppe) { Log.e(TAG, xppe.getMessage(), xppe); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage(), ioe); } return this; }
public Rest requestForm() { String path = "checkout/newShippingAddressForm"; String response = this.request(path, null, null); try { mForm = this.getFormFromResponse(response); } catch (XmlPullParserException xppe) { Log.e(TAG, xppe.getMessage(), xppe); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage(), ioe); } return this; }
public synchronized void parse(InputStream is, String enc) throws XmlParseException, IOException { if (is == null) { throw new NullPointerException("InputStream"); } try { XmlPullParser parser = createParser(); parser.setInput(is, enc); parse(parser); } catch (XmlPullParserException e) { throw new XmlParseException(getParser(), e.getMessage()); } }
public KeyboardBuilder<KP> load(final int xmlId, final KeyboardId id) { mParams.mId = id; final XmlResourceParser parser = mResources.getXml(xmlId); try { parseKeyboard(parser); } catch (XmlPullParserException e) { Log.w(BUILDER_TAG, "keyboard XML parse error", e); throw new IllegalArgumentException(e.getMessage(), e); } catch (IOException e) { Log.w(BUILDER_TAG, "keyboard XML parse error", e); throw new RuntimeException(e.getMessage(), e); } finally { parser.close(); } return this; }
private void loadConditionsFromXml() { XmlPullParser parser = mContext.getResources().getXml(mResouseId); try { XmlUtils.beginDocument(parser, "resources"); boolean hasPushNext = false; String item; while (true) { if (!hasPushNext) { XmlUtils.nextElement(parser); } item = parser.getName(); if ("condition".equals(item)) { int code = 3200; String strCode = parser.getAttributeValue(null, "code"); if (!TextUtils.isEmpty(strCode)) { code = Integer.parseInt(strCode); } String key = parser.getAttributeValue(null, "key"); String displayName = parser.getAttributeValue(null, "displayName"); String strType = parser.getAttributeValue(null, "type"); int type = -1; if (!TextUtils.isEmpty(strType)) { type = Integer.parseInt(strType); } if (DEBUG) { Log.d(TAG, "code = " + code); Log.d(TAG, "key = " + key); Log.d(TAG, "displayName = " + displayName); Log.d(TAG, "type = " + type); } Condition con = new Condition(code, key, displayName, type); mAllConditions.put(con.mCode, con); } else { break; } } } catch (XmlPullParserException e) { Log.e(TAG, "Got exception parsing XmlPullParserException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "Got exception parsing IOException: " + e.getMessage()); } }
@Override protected List<Asset> doInBackground(Void... params) { for (int i = 0; i < data.length; i++) { loadArray(data[i]); try { String filename = "/" + data[i] + ".xml"; AssetParser parser = new AssetParser(); List<Asset> assets = parser.parse(filename); return assets; } catch (IOException e) { mError = e.getMessage(); } catch (XmlPullParserException e) { mError = e.getMessage(); } catch (Exception e) { mError = e.getMessage(); } } return null; }
@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Log.d(LabDemoActivity.LOG_TAG, getClass().getSimpleName() + "-> onCreate"); Intent intentInput = getIntent(); if (intentInput.hasExtra(XML_FILEPATH)) { mXMLFile = intentInput.getStringExtra(XML_FILEPATH); Log.d(LabDemoActivity.LOG_TAG, "file: " + mXMLFile); File f = new File(mXMLFile); if (f != null && f.exists()) { try { // FileInputStream fis = new FileInputStream(f); FileReader fr = new FileReader(f); // if (fis != null) { if (fr != null) { LayoutInflater linflate = getLayoutInflater(); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parse = factory.newPullParser(); // parse.setInput(fis, "utf-8"); parse.setInput(fr); mView = linflate.inflate(parse, mViewGroup); setContentView(mView); } } catch (FileNotFoundException e) { Log.e(LabDemoActivity.LOG_TAG, "no file found: " + e.getMessage()); } catch (XmlPullParserException e) { Log.e(LabDemoActivity.LOG_TAG, "XMLPullPaser failed: " + e.getMessage()); } catch (InflateException e) { Log.e(LabDemoActivity.LOG_TAG, "InflateException failed: " + e.getMessage()); } } else { Log.d(LabDemoActivity.LOG_TAG, "no file found."); } } else { Log.d(LabDemoActivity.LOG_TAG, "no file input"); mXMLFile = null; } }
/** * Inflate a new hierarchy from the specified XML node. Throws InflaterException if there is an * error. * * <p><em><strong>Important</strong></em> For performance reasons, inflation * relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not * currently possible to use inflater with an XmlPullParser over a plain XML file at runtime. * * @param parser XML dom node containing the description of the hierarchy. * @param root Optional to be the parent of the generated hierarchy (if <em>attachToRoot</em> is * true), or else simply an object that provides a set of values for root of the returned * hierarchy (if <em>attachToRoot</em> is false.) * @return The root of the inflated hierarchy. If root was supplied, this is root; otherwise it is * the root of the inflated XML file. */ public Preference inflate(XmlPullParser parser, @Nullable PreferenceGroup root) { synchronized (mConstructorArgs) { final AttributeSet attrs = Xml.asAttributeSet(parser); mConstructorArgs[0] = mContext; final Preference result; try { // Look for the root node. int type; do { type = parser.next(); } while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT); if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } // Temp is the root that was found in the xml Preference xmlRoot = createItemFromTag(parser.getName(), attrs); result = onMergeRoots(root, (PreferenceGroup) xmlRoot); // Inflate all children under temp rInflate(parser, result, attrs); } catch (InflateException e) { throw e; } catch (XmlPullParserException e) { final InflateException ex = new InflateException(e.getMessage()); ex.initCause(e); throw ex; } catch (IOException e) { final InflateException ex = new InflateException(parser.getPositionDescription() + ": " + e.getMessage()); ex.initCause(e); throw ex; } return result; } }
private Object uploadFileHelper(Object[] params, final File tempFile) { // Create listener for tracking upload progress in the notification if (mClient instanceof XMLRPCClient) { XMLRPCClient xmlrpcClient = (XMLRPCClient) mClient; xmlrpcClient.setOnBytesUploadedListener( new XMLRPCClient.OnBytesUploadedListener() { @Override public void onBytesUploaded(long uploadedBytes) { if (tempFile.length() == 0) { return; } float percentage = (uploadedBytes * 100) / tempFile.length(); mPostUploadNotifier.updateNotificationProgress(percentage); } }); } try { return mClient.call(ApiHelper.Methods.UPLOAD_FILE, params, tempFile); } catch (XMLRPCException e) { AppLog.e(T.API, e); mErrorMessage = mContext.getResources().getString(R.string.error_media_upload) + ": " + e.getMessage(); return null; } catch (IOException e) { AppLog.e(T.API, e); mErrorMessage = mContext.getResources().getString(R.string.error_media_upload) + ": " + e.getMessage(); return null; } catch (XmlPullParserException e) { AppLog.e(T.API, e); mErrorMessage = mContext.getResources().getString(R.string.error_media_upload) + ": " + e.getMessage(); return null; } finally { // remove the temporary upload file now that we're done with it if (tempFile != null && tempFile.exists()) { tempFile.delete(); } } }
public Feed parse(final InputStream inputStream) throws FeedParserException, IOException { final Feed feed = new Feed(); final KXmlParser parser = new KXmlParser(); try { parser.setInput(new InputStreamReader(inputStream)); parser.nextTag(); parser.require(XmlPullParser.START_TAG, null, "rss"); parser.nextTag(); parser.require(XmlPullParser.START_TAG, null, "channel"); parser.nextTag(); parseChannel(feed, parser); } catch (XmlPullParserException e) { throw new FeedParserException(e.getMessage(), e); } return feed; }
/** * @param response done by the Web service * @param encoding of the response * @return A list of four Strings (wind, temperature, pressure, time) if response was successfully * analyzed; a void list otherwise */ public List<String> handleResponse(InputStream response, String encoding) throws IOException { mRes = new ArrayList<String>(); try { /* Format of the 2 embedded files * <?xml version="1.0" encoding="utf-8"?> * <string> * <?xml version="1.0" encoding="utf-16"?> * <CurrentWeather> * <Location>Seoul / Kimp'O International Airport, Korea, South (RKSS) 37-33N 126-48E 18M</Location> * <Time>Nov 06, 2014 - 04:00 PM EST / 2014.11.06 2100 UTC</Time> * <Wind> from the NNW (340 degrees) at 2 MPH (2 KT):0</Wind> * <Visibility> greater than 7 mile(s):0</Visibility> * <Temperature> 35 F (2 C)</Temperature> * <DewPoint> 28 F (-2 C)</DewPoint> * <RelativeHumidity> 74%</RelativeHumidity> * <Pressure> 30.27 in. Hg (1025 hPa)</Pressure> * <Status>Success</Status> * </CurrentWeather> * </string> */ // Create the Pull Parser XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(response, encoding); // start iterating over the first XML document iterate(xpp); // Create another Pull Parser xpp = factory.newPullParser(); xpp.setInput(new StringReader(mString)); // start iterating over the 2nd embedded XML document iterate(xpp); } catch (XmlPullParserException e) { Log.e(TAG, e.getMessage()); } return mRes; }
// Get the changelog in html code, this will be shown in the dialog's webview private String GetHTMLChangelog(int aResourceId, Resources aResource) { String _Result = "<html><head>" + GetStyle() + "</head><body>"; XmlResourceParser _xml = aResource.getXml(aResourceId); try { int eventType = _xml.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("release"))) { _Result = _Result + ParseReleaseTag(_xml); } eventType = _xml.next(); } } catch (XmlPullParserException e) { Log.e(TAG, e.getMessage(), e); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } finally { _xml.close(); } _Result = _Result + "</body></html>"; return _Result; }
private Object uploadFileHelper(XMLRPCClientInterface client, Object[] params, File tempFile) { try { return client.call("wp.uploadFile", params, tempFile); } catch (XMLRPCException e) { AppLog.e(T.API, e); mErrorMessage = context.getResources().getString(R.string.error_media_upload) + ": " + e.getMessage(); return null; } catch (IOException e) { AppLog.e(T.API, e); mErrorMessage = context.getResources().getString(R.string.error_media_upload) + ": " + e.getMessage(); return null; } catch (XmlPullParserException e) { AppLog.e(T.API, e); mErrorMessage = context.getResources().getString(R.string.error_media_upload) + ": " + e.getMessage(); return null; } finally { // remove the temporary upload file now that we're done with it if (tempFile != null && tempFile.exists()) tempFile.delete(); } }
/** * Read the change log from an XML file. * * @param xml The {@code XmlPullParser} instance used to read the change log. * @param full If {@code true} the full change log is read. Otherwise only the changes since the * last (saved) version are read. * @return A {@code SparseArray} mapping the version codes to release information. */ protected SparseArray<ReleaseItem> readChangeLog(XmlPullParser xml, boolean full) { SparseArray<ReleaseItem> result = new SparseArray<ReleaseItem>(); try { int eventType = xml.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG && xml.getName().equals(ReleaseTag.NAME)) { if (parseReleaseTag(xml, full, result)) { // Stop reading more elements if this entry is not newer than the last // version. break; } } eventType = xml.next(); } } catch (XmlPullParserException e) { Log.e(LOG_TAG, e.getMessage(), e); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } return result; }
@Override protected String doInBackground(Integer... params) { try { SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); SoapObject request = new SoapObject(Utilities.connection.NAMESPACE, Utilities.connection.method_names.getdp); request.addProperty("reg_id", params[0]); envelope.bodyOut = request; HttpTransportSE transport = new HttpTransportSE( Utilities.connection.url + Utilities.connection.x + Utilities.connection.exs); try { transport.call( Utilities.connection.NAMESPACE + Utilities.connection.SOAP_PREFIX + Utilities.connection.method_names.getdp, envelope); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } catch (XmlPullParserException e) { e.printStackTrace(); return e.getMessage(); } result = envelope.getResponse().toString(); if (envelope.bodyIn != null) { SoapPrimitive resultSOAP = (SoapPrimitive) ((SoapObject) envelope.bodyIn).getProperty(0); result = resultSOAP.toString(); } } catch (Exception e) { e.printStackTrace(); result = e.getMessage(); } return result; }
/** * Parses the XML for relevant information * * @param paths a file hopefully containing test related data in correct format * @return a collection of test results */ public TestNGResult parse(FilePath[] paths) { if (null == paths) { log("File paths not specified. paths var is null. Returning empty test results."); return new TestNGResult(); } finalResults = new TestNGResult(); for (FilePath path : paths) { File file = new File(path.getRemote()); if (!file.isFile()) { log("'" + file.getAbsolutePath() + "' points to an invalid test report"); continue; // move to next file } else { log("Processing '" + file.getAbsolutePath() + "'"); } BufferedInputStream bufferedInputStream = null; try { bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); xmlPullParser = createXmlPullParser(bufferedInputStream); // some initial setup testList = new ArrayList<TestNGTestResult>(); while (XmlPullParser.END_DOCUMENT != xmlPullParser.nextToken()) { TAGS tag = TAGS.fromString(xmlPullParser.getName()); int eventType = xmlPullParser.getEventType(); switch (eventType) { // all opening tags case XmlPullParser.START_TAG: switch (tag) { case SUITE: startSuite(get("name")); break; case GROUPS: startGroups(); break; case GROUP: startGroup(get("name")); break; case METHOD: startGroupMethod(get("class"), get("name")); break; case TEST: startTest(get("name")); break; case CLASS: startClass(get("name")); break; case TEST_METHOD: startTestMethod( get("name"), get("test-instance-name"), get("status"), get("description"), get("duration-ms"), get("started-at"), get("is-config")); break; case REPORTER_OUTPUT: startReporterOutput(); break; case LINE: startLine(); currentCDATAParent = TAGS.LINE; break; case PARAMS: startMethodParameters(); currentCDATAParent = TAGS.PARAMS; break; case EXCEPTION: startException(get("class")); break; case MESSAGE: currentCDATAParent = TAGS.MESSAGE; break; case SHORT_STACKTRACE: currentCDATAParent = TAGS.SHORT_STACKTRACE; break; case FULL_STACKTRACE: currentCDATAParent = TAGS.FULL_STACKTRACE; break; } break; // all closing tags case XmlPullParser.END_TAG: switch (tag) { case SUITE: finishSuite(); break; case GROUP: finishGroup(); break; case METHOD: finishGroupMethod(); break; case TEST: finishTest(); break; case CLASS: finishClass(); break; case TEST_METHOD: finishTestMethod(); break; case REPORTER_OUTPUT: endReporterOutput(); break; case LINE: endLine(); currentCDATAParent = TAGS.UNKNOWN; break; case PARAMS: finishMethodParameters(); currentCDATAParent = TAGS.UNKNOWN; break; case EXCEPTION: finishException(); break; case MESSAGE: case SHORT_STACKTRACE: case FULL_STACKTRACE: currentCDATAParent = TAGS.UNKNOWN; break; } break; // all cdata reading case XmlPullParser.CDSECT: handleCDATA(); break; } } finalResults.addUniqueTests(testList); } catch (XmlPullParserException e) { log("Failed to parse XML: " + e.getMessage()); log(e); } catch (FileNotFoundException e) { log("Failed to find XML file"); log(e); } catch (IOException e) { log(e); } finally { try { if (bufferedInputStream != null) { bufferedInputStream.close(); } } catch (IOException e) { log(e); } } } // tally up the results properly before returning finalResults.tally(); return finalResults; }
private boolean uploadOneSubmission( String id, String instanceFilePath, String jrFormId, String token, String formFilePath) { // if the token is null fail immediately if (token == null) { mResults.put(id, oauth_fail + Collect.getInstance().getString(R.string.invalid_oauth)); return false; } HashMap<String, String> answersToUpload = new HashMap<String, String>(); HashMap<String, String> photosToUpload = new HashMap<String, String>(); HashMap<String, PhotoEntry> uploadedPhotos = new HashMap<String, PhotoEntry>(); HttpTransport h = AndroidHttp.newCompatibleTransport(); GoogleCredential gc = new GoogleCredential(); gc.setAccessToken(token); PicasaClient client = new PicasaClient(h.createRequestFactory(gc)); // get instance file File instanceFile = new File(instanceFilePath); // first check to see how many columns we have: ArrayList<String> columnNames = new ArrayList<String>(); try { getColumns(formFilePath, columnNames); } catch (FileNotFoundException e2) { e2.printStackTrace(); mResults.put(id, e2.getMessage()); return false; } catch (XmlPullParserException e2) { e2.printStackTrace(); mResults.put(id, e2.getMessage()); return false; } catch (IOException e2) { e2.printStackTrace(); mResults.put(id, e2.getMessage()); return false; } catch (FormException e2) { e2.printStackTrace(); mResults.put(id, e2.getMessage()); return false; } if (columnNames.size() > 255) { mResults.put( id, Collect.getInstance().getString(R.string.sheets_max_columns, columnNames.size())); return false; } // make sure column names are legal for (String n : columnNames) { if (!isValidGoogleSheetsString(n)) { mResults.put( id, Collect.getInstance().getString(R.string.google_sheets_invalid_column_form, n)); return false; } } // parses the instance file and populates the answers and photos // hashmaps. try { processInstanceXML(instanceFile, answersToUpload, photosToUpload); } catch (XmlPullParserException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (FormException e) { mResults.put(id, form_fail + Collect.getInstance().getString(R.string.google_repeat_error)); return false; } catch (FileNotFoundException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (IOException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } try { Thread.sleep(GOOGLE_SLEEP_TIME); } catch (InterruptedException e3) { e3.printStackTrace(); } // make sure column names in submission are legal (may be different than form) for (String n : answersToUpload.keySet()) { if (!isValidGoogleSheetsString(n)) { mResults.put( id, Collect.getInstance().getString(R.string.google_sheets_invalid_column_instance, n)); return false; } } // if we have any photos to upload, // get the picasa album or create a new one // then upload the photos if (photosToUpload.size() > 0) { // First set up a picasa album to upload to: // maybe we should move this, because if we don't have any // photos we don't care... AlbumEntry albumToUse; try { albumToUse = getOrCreatePicasaAlbum(client, jrFormId); } catch (IOException e) { e.printStackTrace(); GoogleAuthUtil.invalidateToken(Collect.getInstance(), token); mResults.put(id, picasa_fail + e.getMessage()); return false; } try { uploadPhotosToPicasa(photosToUpload, uploadedPhotos, client, albumToUse, instanceFile); } catch (IOException e1) { e1.printStackTrace(); mResults.put(id, picasa_fail + e1.getMessage()); return false; } } // All photos have been sent to picasa (if there were any) // now upload data to Google Sheet String selection = InstanceColumns._ID + "=?"; String[] selectionArgs = {id}; Cursor cursor = null; String urlString = null; try { // see if the submission element was defined in the form cursor = Collect.getInstance() .getContentResolver() .query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (cursor.getCount() > 0) { cursor.moveToPosition(-1); while (cursor.moveToNext()) { int subIdx = cursor.getColumnIndex(InstanceColumns.SUBMISSION_URI); urlString = cursor.isNull(subIdx) ? null : cursor.getString(subIdx); // if we didn't find one in the content provider, // try to get from settings if (urlString == null) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect.getInstance()); urlString = settings.getString( PreferencesActivity.KEY_GOOGLE_SHEETS_URL, Collect.getInstance().getString(R.string.default_google_sheets_url)); } } } } finally { if (cursor != null) { cursor.close(); } } // now parse the url string if we have one final String googleHeader = "docs.google.com/spreadsheets/d/"; String sheetId; if (urlString == null || urlString.length() < googleHeader.length()) { mResults.put( id, form_fail + Collect.getInstance().getString(R.string.invalid_sheet_id, urlString)); return false; } else { int start = urlString.indexOf(googleHeader) + googleHeader.length(); int end = urlString.indexOf("/", start); if (end == -1) { // if there wasn't a "/", just try to get the end end = urlString.length(); } if (start == -1 || end == -1) { mResults.put( id, form_fail + Collect.getInstance().getString(R.string.invalid_sheet_id, urlString)); return false; } sheetId = urlString.substring(start, end); } SpreadsheetService service = new SpreadsheetService("ODK-Collect"); service.setAuthSubToken(token); // Define the URL to request. URL spreadsheetFeedURL = null; try { spreadsheetFeedURL = new URL("https://spreadsheets.google.com/feeds/worksheets/" + sheetId + "/private/full"); } catch (MalformedURLException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } WorksheetQuery query = new WorksheetQuery(spreadsheetFeedURL); WorksheetFeed feed = null; try { feed = service.query(query, WorksheetFeed.class); } catch (IOException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (ServiceException e) { e.printStackTrace(); if (e.getLocalizedMessage().equalsIgnoreCase("forbidden")) { mResults.put( id, form_fail + Collect.getInstance().getString(R.string.google_sheets_access_denied)); } else { mResults.put(id, form_fail + Html.fromHtml(e.getResponseBody())); } return false; } List<WorksheetEntry> spreadsheets = feed.getEntries(); // get the first worksheet WorksheetEntry we = spreadsheets.get(0); // check the headers.... URL headerFeedUrl = null; try { headerFeedUrl = new URI( we.getCellFeedUrl().toString() + "?min-row=1&max-row=1&min-col=1&max-col=" + we.getColCount() + "&return-empty=true") .toURL(); } catch (MalformedURLException e1) { e1.printStackTrace(); mResults.put(id, form_fail + e1.getMessage()); return false; } catch (URISyntaxException e1) { e1.printStackTrace(); mResults.put(id, form_fail + e1.getMessage()); return false; } CellFeed headerFeed = null; try { headerFeed = service.getFeed(headerFeedUrl, CellFeed.class); } catch (IOException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (ServiceException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } boolean emptyheaders = true; // go through headers // if they're empty, resize and add for (CellEntry c : headerFeed.getEntries()) { if (c.getCell().getValue() != null) { emptyheaders = false; break; } } if (emptyheaders) { // if the headers were empty, resize the spreadsheet // and add the headers we.setColCount(columnNames.size()); try { we.update(); } catch (IOException e2) { e2.printStackTrace(); mResults.put(id, form_fail + e2.getMessage()); return false; } catch (ServiceException e2) { e2.printStackTrace(); mResults.put(id, form_fail + e2.getMessage()); return false; } catch (UnsupportedOperationException e) { e.printStackTrace(); mResults.put( id, form_fail + Collect.getInstance().getString(R.string.google_sheets_update_error)); return false; } // get the cell feed url URL cellFeedUrl = null; try { cellFeedUrl = new URI( we.getCellFeedUrl().toString() + "?min-row=1&max-row=1&min-col=1&max-col=" + columnNames.size() + "&return-empty=true") .toURL(); } catch (MalformedURLException e1) { e1.printStackTrace(); mResults.put(id, form_fail + e1.getMessage()); return false; } catch (URISyntaxException e1) { e1.printStackTrace(); mResults.put(id, form_fail + e1.getMessage()); return false; } // and the cell feed CellFeed cellFeed = null; try { cellFeed = service.getFeed(cellFeedUrl, CellFeed.class); } catch (IOException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (ServiceException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } // write the headers for (int i = 0; i < cellFeed.getEntries().size(); i++) { CellEntry cell = cellFeed.getEntries().get(i); String column = columnNames.get(i); cell.changeInputValueLocal(column); try { cell.update(); } catch (IOException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (ServiceException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } } } // we may have updated the feed, so get a new one // update the feed try { headerFeedUrl = new URI( we.getCellFeedUrl().toString() + "?min-row=1&max-row=1&min-col=1&max-col=" + we.getColCount() + "&return-empty=true") .toURL(); } catch (MalformedURLException e3) { e3.printStackTrace(); mResults.put(id, form_fail + e3.getMessage()); return false; } catch (URISyntaxException e3) { e3.printStackTrace(); mResults.put(id, form_fail + e3.getMessage()); return false; } try { headerFeed = service.getFeed(headerFeedUrl, CellFeed.class); } catch (IOException e2) { e2.printStackTrace(); mResults.put(id, form_fail + e2.getMessage()); return false; } catch (ServiceException e2) { e2.printStackTrace(); mResults.put(id, form_fail + e2.getMessage()); return false; } // see if our columns match, now URL cellFeedUrl = null; try { cellFeedUrl = new URI( we.getCellFeedUrl().toString() + "?min-row=1&max-row=1&min-col=1&max-col=" + headerFeed.getEntries().size() + "&return-empty=true") .toURL(); } catch (MalformedURLException e1) { e1.printStackTrace(); mResults.put(id, form_fail + e1.getMessage()); return false; } catch (URISyntaxException e1) { e1.printStackTrace(); mResults.put(id, form_fail + e1.getMessage()); return false; } CellFeed cellFeed = null; try { cellFeed = service.getFeed(cellFeedUrl, CellFeed.class); } catch (IOException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (ServiceException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } // first, get all the columns in the spreadsheet ArrayList<String> sheetCols = new ArrayList<String>(); for (int i = 0; i < cellFeed.getEntries().size(); i++) { CellEntry cell = cellFeed.getEntries().get(i); sheetCols.add(cell.getPlainTextContent()); } ArrayList<String> missingColumns = new ArrayList<String>(); for (String col : columnNames) { if (!sheetCols.contains(col)) { missingColumns.add(col); } } if (missingColumns.size() > 0) { // we had some missing columns, so error out String missingString = ""; for (int i = 0; i < missingColumns.size(); i++) { missingString += missingColumns.get(i); if (i < missingColumns.size() - 1) { missingString += ", "; } } mResults.put( id, form_fail + Collect.getInstance() .getString(R.string.google_sheets_missing_columns, missingString)); return false; } // if we get here.. all has matched // so write the values ListEntry row = new ListEntry(); // add photos to answer set Iterator<String> photoIterator = uploadedPhotos.keySet().iterator(); while (photoIterator.hasNext()) { String key = photoIterator.next(); String url = uploadedPhotos.get(key).getImageLink(); answersToUpload.put(key, url); } Iterator<String> answerIterator = answersToUpload.keySet().iterator(); while (answerIterator.hasNext()) { String path = answerIterator.next(); String answer = answersToUpload.get(path); // Check to see if answer is a location, if so, get rid of accuracy // and altitude // try to match a fairly specific pattern to determine // if it's a location // [-]#.# [-]#.# #.# #.# Pattern p = Pattern.compile( "^-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\" + ".[0-9]+\\s[0-9]+\\.[0-9]+$"); Matcher m = p.matcher(answer); if (m.matches()) { // get rid of everything after the second space int firstSpace = answer.indexOf(" "); int secondSpace = answer.indexOf(" ", firstSpace + 1); answer = answer.substring(0, secondSpace); answer = answer.replace(' ', ','); } row.getCustomElements().setValueLocal(TextUtils.htmlEncode(path), answer); } // Send the new row to the API for insertion. try { URL listFeedUrl = we.getListFeedUrl(); row = service.insert(listFeedUrl, row); } catch (IOException e) { e.printStackTrace(); mResults.put(id, form_fail + e.getMessage()); return false; } catch (ServiceException e) { e.printStackTrace(); if (e.getLocalizedMessage().equalsIgnoreCase("Forbidden")) { mResults.put( id, form_fail + Collect.getInstance().getString(R.string.google_sheets_access_denied)); } else { mResults.put(id, form_fail + Html.fromHtml(e.getResponseBody())); } return false; } mResults.put(id, Collect.getInstance().getString(R.string.success)); return true; }
@Override protected String doInBackground(Uri... params) { Bitmap bitmap = null; Bitmap icon = null; try { bitmap = MediaStore.Images.Media.getBitmap( getApplicationContext().getContentResolver(), params[0]); icon = bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, false); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ByteArrayOutputStream stream2 = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 45, stream); icon.compress(Bitmap.CompressFormat.PNG, 10, stream2); byte[] array = stream.toByteArray(); byte[] icon_array = stream2.toByteArray(); String Imagestr = Base64.encodeToString(array, Base64.DEFAULT); String icon_str = Base64.encodeToString(icon_array, Base64.DEFAULT); array = null; icon_array = null; // converted to byte array and have to send it SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); SoapObject request = new SoapObject( Utilities.connection.NAMESPACE, Utilities.connection.method_names.changedp); int x = getApplicationContext() .getSharedPreferences(Utilities.SharesPresfKeys.key, Context.MODE_PRIVATE) .getInt("reg_id", 0); request.addProperty("Reg_id", x); request.addProperty("x", Imagestr); request.addProperty("y", icon_str); envelope.bodyOut = request; envelope.setOutputSoapObject(request); HttpTransportSE transport = new HttpTransportSE( Utilities.connection.url + Utilities.connection.x + Utilities.connection.exs); try { transport.call( Utilities.connection.NAMESPACE + Utilities.connection.SOAP_PREFIX + Utilities.connection.method_names.changedp, envelope); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } catch (XmlPullParserException e) { e.printStackTrace(); return e.getMessage(); } result = envelope.getResponse().toString(); if (envelope.bodyIn != null) { SoapPrimitive resultSOAP = (SoapPrimitive) ((SoapObject) envelope.bodyIn).getProperty(0); result = resultSOAP.toString(); } return result; } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } catch (Exception e) { e.printStackTrace(); result = e.getMessage(); } return "no result sorry"; }
/** * Get specific color of related theme from theme apk asset resource path. * * @param colorName the key string of the color. * @return the color value for the current theme, if the current theme is the default theme, or * the colorName is not present in the color.xml, return 0. */ public int getThemeColor(String colorName) { if (EncapsulationConstant.USE_MTK_PLATFORM) { return mResources.getThemeColor(colorName); } else { InputStream raw = null; AssetManager am = mResources.getAssets(); String themepath = SystemProperties.get("persist.sys.skin", DEFAULT_THEME_PATH); // If the current theme is the default theme, return 0 directly. if (DEFAULT_THEME_PATH.equals(themepath)) { return 0; } // get themeColor from cache Integer themeColor = mMtkColorCache.get(colorName); if (themeColor != null) { return themeColor; } // Add theme path to asset path to access it, if add asset path failed, // return 0 directly. int cookie = am.addAssetPath(themepath); if (cookie == 0) { return 0; } // Get color value from xml file. try { // Open color.xml as assets. raw = am.openNonAsset(cookie, THEME_COLOR_PATH, AssetManager.ACCESS_STREAMING); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setValidating(false); XmlPullParser myxml = factory.newPullParser(); myxml.setInput(raw, null); int eventType = myxml.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: if (STR_COLOR.equals(myxml.getName())) { if (colorName.equals(myxml.getAttributeValue(0))) { String colorStr = myxml.nextText(); themeColor = Color.parseColor(colorStr); mMtkColorCache.put(colorName, themeColor); return themeColor; } } break; case XmlPullParser.END_TAG: break; default: break; } eventType = myxml.next(); } } catch (IOException e) { Log.e(TAG, "IOException happened when getThemeColor, msg = " + e.getMessage()); } catch (XmlPullParserException e) { Log.e(TAG, "XmlPullParserException happened when getThemeColor, msg = " + e.getMessage()); } return 0; } }
/** * Unescapes the HTML-escaped data in the parameter string htmlEncodedData. The string is then * parsed with an XmlPullParser to extract fleet and resource data. The data is inserted into a * Map<String, Long> object. This Map is then returned. * * @param htmlEncodedData - HTML-escaped string containing the details of the fleet breakdown and * composition * @return a Map<String, Long> object containing fleet and resource composition. Keys are listed * in class FleetAndResources */ private void parseFleetResComposition( String htmlEncodedData, Map<String, Long> fleet, FleetResources res) { StringReader strReader = null; XmlPullParser subxpp = null; try { strReader = new StringReader(htmlEncodedData); subxpp = XmlPullParserFactory.newInstance().newPullParser(); subxpp.setInput(strReader); subxpp.defineEntityReplacementText("nbsp", " "); boolean parsingShips = false; boolean parsingRes = false; String currentShip; String currentRes; int eventType = subxpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (subxpp.getEventType() == XmlPullParser.TEXT) { String textData = subxpp.getText(); textData = textData.replaceAll(":", ""); if (textData.equals("Ships")) { parsingShips = true; break; } } try { subxpp.next(); eventType = subxpp.getEventType(); } catch (XmlPullParserException e) { // System.out.println("Caught an exception. Not stopping: " + e + '\n' + // e.getMessage()); // e.printStackTrace(); } } while (parsingShips && eventType != XmlPullParser.END_DOCUMENT) { subxpp.next(); eventType = subxpp.getEventType(); if (eventType == XmlPullParser.TEXT) { String textData = subxpp.getText(); if (textData != null) { textData = textData.trim(); } if (textData != null && textData.length() > 0) { if (textData.equals("Shipment:")) { parsingRes = true; break; } else { textData = textData.substring(0, textData.length() - 1); currentShip = FleetAndResources.getName(textData); } textData = ""; while (textData.length() == 0) { subxpp.next(); eventType = subxpp.getEventType(); if (eventType == XmlPullParser.TEXT) { textData = subxpp.getText(); textData = textData.trim(); } } String numshipstr = textData; numshipstr = numshipstr.replaceAll("\\.", ""); if (currentShip != null && currentShip.length() > 0) { Long numships = Long.valueOf(numshipstr); fleet.put(currentShip, numships); } } } } eventType = subxpp.getEventType(); while (parsingRes && eventType != XmlPullParser.END_DOCUMENT) { subxpp.next(); eventType = subxpp.getEventType(); if (eventType == XmlPullParser.TEXT) { String textData = subxpp.getText(); if (textData != null) { textData = textData.trim(); } if (textData != null && textData.length() > 0) { String resType = subxpp.getText(); if (FleetAndResources.METAL_TAG.equals(resType)) { currentRes = FleetAndResources.METAL; } else if (FleetAndResources.CRYSTAL_TAG.equals(resType)) { currentRes = FleetAndResources.CRYSTAL; } else if (FleetAndResources.DEUT_TAG.equals(resType)) { currentRes = FleetAndResources.DEUT; } else { continue; } textData = ""; while (textData.length() == 0) { subxpp.next(); eventType = subxpp.getEventType(); if (eventType == XmlPullParser.TEXT) { textData = subxpp.getText(); textData = textData.trim(); } } String amount = textData; amount = amount.replaceAll("\\.", ""); if (amount.length() > 0) { long amt = Long.valueOf(amount); if (currentRes == FleetAndResources.METAL) { res.metal = amt; } else if (currentRes == FleetAndResources.CRYSTAL) { res.crystal = amt; } else if (currentRes == FleetAndResources.DEUT) { res.deuterium = amt; } } } } } } catch (XmlPullParserException | IOException e) { System.err.println(e.toString() + '\n' + e.getMessage()); e.printStackTrace(); } finally { if (subxpp != null) { try { subxpp.setInput(null); } catch (XmlPullParserException e) { System.err.println(e.toString() + '\n' + e.getMessage()); e.printStackTrace(); } } if (strReader != null) strReader.close(); } }
public List<FleetEvent> parse(InputStream stream, OgameResources resources) { List<FleetEvent> eventList = new LinkedList<>(); try { XmlPullParserFactory xppfactory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = xppfactory.newPullParser(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); xpp.setInput(reader); xpp.defineEntityReplacementText("ndash", "-"); xpp.defineEntityReplacementText("nbsp", " "); FleetEvent lastScannedEvent = null; // To make the next for loop look easier to read and understand, we get to the first instance // of // <tr class="eventFleet"> int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String tagName = xpp.getName(); if (tagName != null && tagName.equals("tr") && hasAttrValue(xpp, "class", "eventFleet")) { lastScannedEvent = new FleetEvent(); int attrCount = xpp.getAttributeCount(); for (int index = 0; index < attrCount; index++) { String attrName = xpp.getAttributeName(index); if (attrName.equals("data-mission-type")) { String value = xpp.getAttributeValue(index); lastScannedEvent.data_mission_type = Integer.valueOf(value); } else if (attrName.equals("data-return-flight")) { String value = xpp.getAttributeValue(index); lastScannedEvent.data_return_flight = Boolean.valueOf(value); } else if (attrName.equals("data-arrival-time")) { String value = xpp.getAttributeValue(index); lastScannedEvent.data_arrival_time = Long.valueOf(value); } } // We must call next() here before breaking. Otherwise, the next loop // will add the incomplete FleetEvent object since it will detect // the same <tr...> element and think it's a new event when it's // still the same first event. xpp.next(); break; } try { eventType = xpp.next(); } catch (XmlPullParserException e) { /* For some strange reason, the emulator can reach this catch block with * e set to null. (Why and how?) Might be a debugger bug */ System.out.println("Analysis of an error: " + e + '\n' + e.getMessage()); e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { // This exception occurs near the end of the document, but it is not something that // should stop the app over. System.err.println( "Possibly reached end of document (HTML is painful): " + e + '\n' + e.getMessage()); e.printStackTrace(); eventType = XmlPullParser.END_DOCUMENT; } } // No events scanned. Just return. if (lastScannedEvent == null) return eventList; eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { // Begin parsing for fleet events. if (eventType == XmlPullParser.START_TAG) { String tagName = xpp.getName(); tagName = (tagName == null) ? "" : tagName; if (tagName.equals("tr") && hasAttrValue(xpp, "class", "eventFleet")) { eventList.add(lastScannedEvent); lastScannedEvent = new FleetEvent(); int attrCount = xpp.getAttributeCount(); for (int index = 0; index < attrCount; index++) { String attrName = xpp.getAttributeName(index); if (attrName.equals("data-mission-type")) { String value = xpp.getAttributeValue(index); lastScannedEvent.data_mission_type = Integer.valueOf(value); } else if (attrName.equals("data-return-flight")) { String value = xpp.getAttributeValue(index); lastScannedEvent.data_return_flight = Boolean.valueOf(value); } else if (attrName.equals("data-arrival-time")) { String value = xpp.getAttributeValue(index); lastScannedEvent.data_arrival_time = Long.valueOf(value); } } } else if (tagName.equals("td")) { if (hasAttrValue(xpp, "class", "originFleet")) { /* Example from the extracted response sample: * <td class="originFleet"> <--XPP pointer is here currently <span class="tooltip" title="A Whole New World"> <figure class="planetIcon planet"></figure> A Whole New World </span> </td> */ tagName = xpp.getName(); int htmlevent = 0; int counter = 0; // From the response extract, we need 5 next()'s to get to the text we need. // Set a hard limit just in case. while ((htmlevent != XmlPullParser.END_TAG || !tagName.equalsIgnoreCase("figure")) && counter < 5) { htmlevent = xpp.next(); tagName = xpp.getName(); counter++; } xpp.next(); if (xpp.getEventType() == XmlPullParser.TEXT) { lastScannedEvent.originFleet = xpp.getText(); if (lastScannedEvent.originFleet != null) lastScannedEvent.originFleet = lastScannedEvent.originFleet.trim(); } } else if (hasAttrValue(xpp, "class", "coordsOrigin")) { /* Example: * <td class="coordsOrigin"> <-- XPP pointer here <a href="http://s125-en.ogame.gameforge.com/game/index.php?page=galaxy&galaxy=1&system=373" target="_top"> [1:373:8] </a> </td> */ tagName = xpp.getName(); // We need 2 next()'s to get to the <a> element. Use a hard limit just in case. int htmlevent = 0; int counter = 0; while ((htmlevent != XmlPullParser.START_TAG || !tagName.equalsIgnoreCase("a")) && counter < 2) { htmlevent = xpp.next(); tagName = xpp.getName(); counter++; } xpp.next(); if (xpp.getEventType() == XmlPullParser.TEXT) { lastScannedEvent.coordsOrigin = new LinkHTML(); String coordinates = xpp.getText(); if (coordinates != null) { coordinates = coordinates.trim(); } else { coordinates = ""; } lastScannedEvent.coordsOrigin.text = coordinates; } } else if (hasAttrValue(xpp, "class", "icon_movement") || hasAttrValue(xpp, "class", "icon_movement_reserve")) { // Have to parse another HTML snippet. This HTML is both encoded to not confuse // the parser, so it must be decoded first. Then it must be put through another // XmlPullParser to gather the data. /* Example: * <td class="icon_movement"> <-- xpp point here * <span class="blah blah blah" * title="bunch of escaped HTML we have to unescape" * data-federation-user-id=""> * * </span> * </td> */ tagName = xpp.getName(); int htmlevent = 0; tagName = (tagName == null) ? "" : tagName; while (htmlevent != XmlPullParser.START_TAG || !tagName.equalsIgnoreCase("span")) { htmlevent = xpp.next(); tagName = xpp.getName(); } Map<String, Long> fleetData = null; if (xpp.getEventType() == XmlPullParser.START_TAG) { int attrSize = xpp.getAttributeCount(); String titleValue = null; for (int index = 0; index < attrSize; index++) { String attrName = xpp.getAttributeName(index); if (attrName.equals("title")) { titleValue = xpp.getAttributeValue(index); } } if (titleValue != null) { parseFleetResComposition( titleValue, lastScannedEvent.fleet, lastScannedEvent.resources); } } } else if (hasAttrValue(xpp, "class", "destFleet")) { /* Example: * <td class="destFleet"> <-- XPP pointer here <span class="tooltip" title="Slot 8 unavailable"> <figure class="planetIcon planet"></figure> Slot 8 unavailable </span> </td> */ int counter = 0; int htmlevent = 0; tagName = xpp.getName(); tagName = (tagName == null) ? "" : tagName; while ((htmlevent != XmlPullParser.END_TAG || !tagName.equalsIgnoreCase("figure")) && counter < 5) { htmlevent = xpp.next(); tagName = xpp.getName(); counter++; } xpp.next(); if (xpp.getEventType() == XmlPullParser.TEXT) { lastScannedEvent.destFleet = xpp.getText(); if (lastScannedEvent.destFleet != null) lastScannedEvent.destFleet = lastScannedEvent.destFleet.trim(); } } else if (hasAttrValue(xpp, "class", "destCoords")) { /* Example: * <td class="destCoords"> <--XPP pointer here <a href="http://s125-en.ogame.gameforge.com/game/index.php?page=galaxy&galaxy=1&system=204" target="_top"> [1:204:8] </a> </td> */ int counter = 0; int htmlevent = 0; tagName = xpp.getName(); tagName = (tagName == null) ? "" : tagName; while ((htmlevent != XmlPullParser.START_TAG || !tagName.equalsIgnoreCase("a")) && counter < 2) { htmlevent = xpp.next(); tagName = xpp.getName(); counter++; } xpp.next(); if (xpp.getEventType() == XmlPullParser.TEXT) { lastScannedEvent.destCoords = new LinkHTML(); String coordinates = xpp.getText(); if (coordinates != null) { coordinates = coordinates.trim(); } else { coordinates = ""; } lastScannedEvent.destCoords.text = coordinates; } } } } try { eventType = xpp.next(); } catch (XmlPullParserException e) { // System.out.println("Analysis of an error: " + e + '\n' + e.getMessage()); // e.printStackTrace(); eventType = XmlPullParser.END_DOCUMENT; } catch (ArrayIndexOutOfBoundsException e) { // This exception occurs near the end of the document, but it is not something that // should stop the app over. System.err.println( "Possibly reached end of document (HTML is painful): " + e + '\n' + e.getMessage()); e.printStackTrace(); eventType = XmlPullParser.END_DOCUMENT; } } eventList.add(lastScannedEvent); } catch (XmlPullParserException e) { System.err.println(e.toString() + '\n' + e.getMessage()); e.printStackTrace(); return null; } catch (IOException e) { System.err.println(e.toString() + '\n' + e.getMessage()); e.printStackTrace(); } return eventList; }