List of usage examples for com.google.gson.stream JsonReader JsonReader
public JsonReader(Reader in)
From source file:com.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java
License:Open Source License
/** * Parses the legality file and populates the database with the different formats, their respective sets, and their * banned and restricted lists//ww w.j a va2 s . com * * @param prefAdapter The preference adapter is used to get the last update time * @return An object with all of the legal info, to be added to the database in one fell swoop * @throws IOException Thrown if something goes wrong with the InputStream * @throws com.gelakinetic.mtgfam.helpers.database.FamiliarDbException Thrown if something goes wrong with database writing */ public LegalInfo readLegalityJsonStream(PreferenceAdapter prefAdapter) throws IOException, FamiliarDbException { LegalInfo legalInfo = new LegalInfo(); String legalSet; String bannedCard; String restrictedCard; String formatName; String jsonArrayName; String jsonTopLevelName; URL legal = new URL(LEGALITY_URL); InputStream in = new BufferedInputStream(legal.openStream()); JsonReader reader = new JsonReader(new InputStreamReader(in, "ISO-8859-1")); reader.beginObject(); while (reader.hasNext()) { jsonTopLevelName = reader.nextName(); if (jsonTopLevelName.equalsIgnoreCase("Date")) { mCurrentRulesDate = reader.nextString(); /* compare date, maybe return, update shared prefs */ String spDate = prefAdapter.getLegalityDate(); if (spDate != null && spDate.equals(mCurrentRulesDate)) { reader.close(); return null; /* dates match, nothing new here. */ } } else if (jsonTopLevelName.equalsIgnoreCase("Formats")) { reader.beginObject(); while (reader.hasNext()) { formatName = reader.nextName(); legalInfo.formats.add(formatName); reader.beginObject(); while (reader.hasNext()) { jsonArrayName = reader.nextName(); if (jsonArrayName.equalsIgnoreCase("Sets")) { reader.beginArray(); while (reader.hasNext()) { legalSet = reader.nextString(); legalInfo.legalSets.add(new NameAndMetadata(legalSet, formatName)); } reader.endArray(); } else if (jsonArrayName.equalsIgnoreCase("Banlist")) { reader.beginArray(); while (reader.hasNext()) { bannedCard = reader.nextString(); legalInfo.bannedCards.add(new NameAndMetadata(bannedCard, formatName)); } reader.endArray(); } else if (jsonArrayName.equalsIgnoreCase("Restrictedlist")) { reader.beginArray(); while (reader.hasNext()) { restrictedCard = reader.nextString(); legalInfo.restrictedCards.add(new NameAndMetadata(restrictedCard, formatName)); } reader.endArray(); } } reader.endObject(); } reader.endObject(); } } reader.endObject(); reader.close(); return legalInfo; }
From source file:com.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java
License:Open Source License
/** * This method parses the mapping between set codes and the names TCGPlayer.com uses * * @param prefAdapter The preference adapter is used to get the last update time * @param tcgNames A place to store tcg names before adding to the database * @throws IOException Thrown if something goes wrong with the InputStream *//*w ww.j a v a 2s. co m*/ public void readTCGNameJsonStream(PreferenceAdapter prefAdapter, ArrayList<NameAndMetadata> tcgNames) throws IOException { URL update; String label; String label2; String name = null, code = null; update = new URL(TCG_NAMES_URL); InputStreamReader isr = new InputStreamReader(update.openStream(), "ISO-8859-1"); JsonReader reader = new JsonReader(isr); reader.beginObject(); while (reader.hasNext()) { label = reader.nextName(); if (label.equals("Date")) { String lastUpdate = prefAdapter.getLastTCGNameUpdate(); mCurrentTCGNamePatchDate = reader.nextString(); if (lastUpdate.equals(mCurrentTCGNamePatchDate)) { reader.close(); return; } } else if (label.equals("Sets")) { reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); while (reader.hasNext()) { label2 = reader.nextName(); if (label2.equals("Code")) { code = reader.nextString(); } else if (label2.equals("TCGName")) { name = reader.nextString(); } } tcgNames.add(new NameAndMetadata(name, code)); reader.endObject(); } reader.endArray(); } } reader.endObject(); reader.close(); }
From source file:com.gelakinetic.mtgfam.helpers.updaters.DbUpdaterService.java
License:Open Source License
/** * This method does the heavy lifting. It opens transactional access to the database, checks the web for new files * to patch in, patches them as necessary, and manipulates the notification to inform the user. * * @param intent The value passed to startService(Intent), it's not used */// w w w . j a va 2 s . com @Override public void onHandleIntent(Intent intent) { showStatusNotification(); /* Try to open up a log */ PrintWriter logWriter = null; try { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { /* Open the log */ File logfile = new File(this.getApplicationContext().getExternalFilesDir(null), "mtgf_update.txt"); logWriter = new PrintWriter(new FileWriter(logfile)); /* Datestamp it */ logWriter.write((new Date()).toString() + '\n'); } } catch (IOException e) { /* Couldn't open log, oh well */ } try { PreferenceAdapter mPrefAdapter = new PreferenceAdapter(this); ProgressReporter reporter = new ProgressReporter(); ArrayList<String> updatedStuff = new ArrayList<>(); CardAndSetParser parser = new CardAndSetParser(); boolean commitDates = true; boolean newRulesParsed = false; try { ArrayList<MtgCard> cardsToAdd = new ArrayList<>(); ArrayList<Expansion> setsToAdd = new ArrayList<>(); ArrayList<String> setsToDrop = new ArrayList<>(); /* Look for updates with the banned / restricted lists and formats */ LegalityData legalityDatas = parser.readLegalityJsonStream(mPrefAdapter, logWriter); /* Log the date */ if (logWriter != null) { logWriter.write("mCurrentRulesDate: " + parser.mCurrentRulesTimestamp + '\n'); } /* Look for new cards */ Manifest manifest = parser.readUpdateJsonStream(logWriter); /* Log the date */ if (logWriter != null) { logWriter.write("mCurrentPatchDate: " + parser.mCurrentPatchTimestamp + '\n'); } if (manifest != null) { /* Make an arraylist of all the current set codes */ ArrayList<String> currentSetCodes = new ArrayList<>(); HashMap<String, String> storedDigests = new HashMap<>(); /* Get readable database access */ SQLiteDatabase database = DatabaseManager.getInstance(getApplicationContext(), false) .openDatabase(false); Cursor setCursor = CardDbAdapter.fetchAllSets(database); if (setCursor != null) { setCursor.moveToFirst(); while (!setCursor.isAfterLast()) { String code = setCursor.getString(setCursor.getColumnIndex(CardDbAdapter.KEY_CODE)); String digest = setCursor.getString(setCursor.getColumnIndex(CardDbAdapter.KEY_DIGEST)); storedDigests.put(code, digest); currentSetCodes.add(code); setCursor.moveToNext(); } /* Cleanup */ setCursor.close(); } DatabaseManager.getInstance(getApplicationContext(), false).closeDatabase(false); /* Look through the list of available patches, and if it doesn't exist in the database, add it. */ for (Manifest.ManifestEntry set : manifest.mPatches) { if (!set.mCode.equals("DD3")) { /* Never download the old Duel Deck Anthologies patch */ try { /* If the digest doesn't match, mark the set for dropping * and remove it from currentSetCodes so it redownloads */ if (set.mDigest != null && !storedDigests.get(set.mCode).equals(set.mDigest)) { currentSetCodes.remove(set.mCode); setsToDrop.add(set.mCode); } } catch (NullPointerException e) { /* eat it */ } if (!currentSetCodes .contains(set.mCode)) { /* check to see if the patch is known already */ int retries = 5; while (retries > 0) { try { /* Change the notification to the specific set */ switchToUpdating( String.format(getString(R.string.update_updating_set), set.mName)); InputStream streamToRead = FamiliarActivity.getHttpInputStream(set.mURL, logWriter); if (streamToRead != null) { GZIPInputStream gis = new GZIPInputStream(streamToRead); JsonReader reader = new JsonReader(new InputStreamReader(gis, "UTF-8")); parser.readCardJsonStream(reader, reporter, cardsToAdd, setsToAdd); streamToRead.close(); updatedStuff.add(set.mName); /* Everything was successful, retries = 0 breaks the while loop */ retries = 0; } } catch (IOException e) { if (logWriter != null) { logWriter.print("Retry " + retries + '\n'); e.printStackTrace(logWriter); } } retries--; } } } } } /* Change the notification to generic "checking for updates" */ switchToChecking(); /* Parse the rules * Instead of using a hardcoded string, the default lastRulesUpdate is the timestamp of when the APK was * built. This is a safe assumption to make, since any market release will have the latest database baked * in. */ long lastRulesUpdate = mPrefAdapter.getLastRulesUpdate(); RulesParser rp = new RulesParser(new Date(lastRulesUpdate), reporter); ArrayList<RulesParser.RuleItem> rulesToAdd = new ArrayList<>(); ArrayList<RulesParser.GlossaryItem> glossaryItemsToAdd = new ArrayList<>(); if (rp.needsToUpdate(logWriter)) { switchToUpdating(getString(R.string.update_updating_rules)); if (rp.parseRules(logWriter)) { rp.loadRulesAndGlossary(rulesToAdd, glossaryItemsToAdd); /* Only save the timestamp of this if the update was 100% successful; if something went screwy, we * should let them know and try again next update. */ newRulesParsed = true; updatedStuff.add(getString(R.string.update_added_rules)); } switchToChecking(); } if (logWriter != null) { logWriter.write("legalityDatas: " + ((legalityDatas == null) ? "null" : "not null") + '\n'); logWriter.write("setsToAdd: " + setsToAdd.size() + '\n'); logWriter.write("cardsToAdd: " + cardsToAdd.size() + '\n'); logWriter.write("rulesToAdd: " + rulesToAdd.size() + '\n'); logWriter.write("glossaryItemsToAdd: " + glossaryItemsToAdd.size() + '\n'); } /* Open a writable database, as briefly as possible */ if (legalityDatas != null || setsToDrop.size() > 0 || setsToAdd.size() > 0 || cardsToAdd.size() > 0 || rulesToAdd.size() > 0 || glossaryItemsToAdd.size() > 0) { SQLiteDatabase database = DatabaseManager.getInstance(getApplicationContext(), true) .openDatabase(true); /* Add all the data we've downloaded */ if (legalityDatas != null) { CardDbAdapter.dropLegalTables(database); CardDbAdapter.createLegalTables(database); for (LegalityData.Format format : legalityDatas.mFormats) { CardDbAdapter.createFormat(format.mName, database); for (String legalSet : format.mSets) { CardDbAdapter.addLegalSet(legalSet, format.mName, database); } for (String bannedCard : format.mBanlist) { CardDbAdapter.addLegalCard(bannedCard, format.mName, CardDbAdapter.BANNED, database); } for (String restrictedCard : format.mRestrictedlist) { CardDbAdapter.addLegalCard(restrictedCard, format.mName, CardDbAdapter.RESTRICTED, database); } } } /* Drop any out of date sets */ for (String code : setsToDrop) { CardDbAdapter.dropSetAndCards(code, database); } /* Add set data */ for (Expansion set : setsToAdd) { CardDbAdapter.createSet(set, database); /* Add the corresponding TCG name */ CardDbAdapter.addTcgName(set.mName_tcgp, set.mCode_gatherer, database); /* Add the corresponding foil information */ CardDbAdapter.addFoilInfo(set.mCanBeFoil, set.mCode_gatherer, database); } /* Add cards */ for (MtgCard card : cardsToAdd) { CardDbAdapter.createCard(card, database); } /* Add stored rules */ if (rulesToAdd.size() > 0 || glossaryItemsToAdd.size() > 0) { CardDbAdapter.dropRulesTables(database); CardDbAdapter.createRulesTables(database); } for (RulesParser.RuleItem rule : rulesToAdd) { CardDbAdapter.insertRule(rule.category, rule.subcategory, rule.entry, rule.text, rule.position, database); } for (RulesParser.GlossaryItem term : glossaryItemsToAdd) { CardDbAdapter.insertGlossaryTerm(term.term, term.definition, database); } /* Close the writable database */ DatabaseManager.getInstance(getApplicationContext(), true).closeDatabase(true); } } catch (FamiliarDbException e1) { commitDates = false; /* don't commit the dates */ if (logWriter != null) { e1.printStackTrace(logWriter); } } /* Parse the MTR and IPG */ MTRIPGParser mtrIpgParser = new MTRIPGParser(mPrefAdapter, this); if (mtrIpgParser.performMtrIpgUpdateIfNeeded(MTRIPGParser.MODE_MTR, logWriter)) { updatedStuff.add(getString(R.string.update_added_mtr)); } if (logWriter != null) { logWriter.write("MTR date: " + mtrIpgParser.mPrettyDate + '\n'); } if (mtrIpgParser.performMtrIpgUpdateIfNeeded(MTRIPGParser.MODE_IPG, logWriter)) { updatedStuff.add(getString(R.string.update_added_ipg)); } if (logWriter != null) { logWriter.write("IPG date: " + mtrIpgParser.mPrettyDate + '\n'); } if (mtrIpgParser.performMtrIpgUpdateIfNeeded(MTRIPGParser.MODE_JAR, logWriter)) { updatedStuff.add(getString(R.string.update_added_jar)); } if (logWriter != null) { logWriter.write("JAR date: " + mtrIpgParser.mPrettyDate + '\n'); } /* If everything went well so far, commit the date and show the update complete notification */ if (commitDates) { parser.commitDates(mPrefAdapter); long curTime = new Date().getTime(); mPrefAdapter.setLastLegalityUpdate((int) (curTime / 1000)); if (newRulesParsed) { mPrefAdapter.setLastRulesUpdate(curTime); } if (updatedStuff.size() > 0) { showUpdatedNotification(updatedStuff); } } } catch (Exception e) { /* Generally pokemon handling is bad, but I don't want miss anything */ if (logWriter != null) { e.printStackTrace(logWriter); } } /* Always cancel the status notification */ cancelStatusNotification(); /* close the log */ if (logWriter != null) { logWriter.close(); } }
From source file:com.getperka.flatpack.fast.JavaDialect.java
License:Apache License
/** * If {@value #concreteTypeMapFile} is defined, load the file into {@link #concreteTypeMap}. *//*from w w w . jav a2s . co m*/ private void loadConcreteTypeMap() throws IOException { if (baseTypeArrayFile != null) { JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(baseTypeArrayFile), UTF8)); reader.setLenient(true); reader.beginArray(); while (reader.hasNext()) { baseTypes.add(reader.nextString()); } reader.endArray(); reader.close(); } }
From source file:com.getperka.flatpack.Unpacker.java
License:Apache License
/** * Reify a {@link FlatPackEntity} from its serialized form. * //from w ww.j a v a 2 s. co m * @param <T> the type of data to return * @param returnType a reference to {@code T} * @param in the source of the serialized data * @param principal the identity for which the unpacking is occurring * @return the reified {@link FlatPackEntity}. */ public <T> FlatPackEntity<T> unpack(Type returnType, Reader in, Principal principal) throws IOException { in = ioObserver.observe(in); packScope.enter().withPrincipal(principal); try { return unpack(returnType, new JsonReader(in), principal); } finally { packScope.exit(); } }
From source file:com.github.chenxiaolong.dualbootpatcher.RomConfig.java
License:Open Source License
private void loadFile() throws FileNotFoundException { FileReader fr = null;/*from ww w.j av a2 s . com*/ JsonReader jr = null; try { fr = new FileReader(mFilename); jr = new JsonReader(fr); RawRoot root = new Gson().fromJson(jr, RawRoot.class); deserialize(root); } catch (JsonParseException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(jr); IOUtils.closeQuietly(fr); } }
From source file:com.github.dpsm.android.print.gson.GsonResultOperator.java
License:Apache License
@Override public Subscriber<? super Response> call(final Subscriber<? super T> subscriber) { return new Subscriber<Response>() { @Override/*from www .j a v a 2s.c om*/ public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(final Throwable e) { subscriber.onError(e); } @Override public void onNext(final Response response) { switch (response.getStatus()) { case HttpURLConnection.HTTP_OK: InputStreamReader reader = null; try { reader = new InputStreamReader(response.getBody().in()); final JsonElement jsonElement = mGSON.fromJson(new JsonReader(reader), JsonObject.class); if (jsonElement != null && jsonElement.isJsonObject()) { final T result = mConstructor.newInstance(jsonElement.getAsJsonObject()); subscriber.onNext(result); } } catch (Exception e) { subscriber.onError(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Nothing to do here } } } break; default: subscriber.onError(new IOException("Http Response Failed: " + response.getStatus())); break; } } }; }
From source file:com.github.gv2011.hprops.Converter.java
License:Open Source License
public Properties toProperties(final Reader json) { final Properties result = new Properties(); toProperties(new JsonReader(json), (p) -> result.setProperty(p.key(), p.value())); return result; }
From source file:com.github.gv2011.jsong.JsongAdapter.java
License:Open Source License
@Override public JsonNode deserialize(final JsonFactoryImp jf, final String json) { final JsonReader in = new JsonReader(new StringReader(json)); return deserialize(jf, in); }
From source file:com.github.kevinsawicki.halligan.Resource.java
License:Open Source License
/** * Fill this resource by opening a request to the URL and parsing the response * * @param url//from www . ja v a 2 s.co m * @return this resource * @throws IOException */ protected Resource parse(final String url) throws IOException { BufferedReader buffer; try { HttpRequest request = createRequest(url); code = request.code(); buffer = request.bufferedReader(); prefix = getPrefix(request.getConnection().getURL()); } catch (HttpRequestException e) { throw e.getCause(); } JsonReader reader = new JsonReader(buffer); try { parse(reader); } catch (JsonParseException e) { IOException ioException = new IOException("JSON parsing failed"); ioException.initCause(e); throw ioException; } finally { try { reader.close(); } catch (IOException ignored) { // Ignored } } return this; }