public static int readGeneric(File f) { int count = 0; Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapter(Location.class, new LocationAdapter()).create(); try (FileReader reader = new FileReader(f)) { GenericNPC[] vils = gson.fromJson(reader, GenericNPC[].class); for (GenericNPC gv : vils) { if (gv == null) continue; NPCManager.register(gv); genericVillagers.add(gv); } count += vils.length; } catch (JsonSyntaxException | JsonIOException | IOException e) { System.err.println("Error reading NPC in " + f.getName() + "."); e.printStackTrace(); } return count; }
@Override public void handleResponseError(Context context, Throwable t) { Timber.tag("Catch-Error").w(t.getMessage()); //这里不光是只能打印错误,还可以根据不同的错误作出不同的逻辑处理 String msg = "未知错误"; if (t instanceof UnknownHostException) { msg = "网络不可用"; } else if (t instanceof SocketTimeoutException) { msg = "请求网络超时"; } else if (t instanceof HttpException) { HttpException httpException = (HttpException) t; msg = convertStatusCode(httpException); } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) { msg = "数据解析错误"; } ArmsUtils.snackbarText(msg); }
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { Charset charset = this.getCharset(outputMessage.getHeaders()); OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset); try { if(this.jsonPrefix != null) { writer.append(this.jsonPrefix); } this.gson.toJson(o, writer); writer.close(); } catch (JsonIOException var7) { throw new HttpMessageNotWritableException("Could not write JSON: " + var7.getMessage(), var7); } }
/** * Creates a {@link JsonArray} from the given json string. * * @param jsonString the json string to parse * @return the {@link JsonArray} received while parsing the given json string * @throws JsonParsingFailedException if any exception occurred at runtime */ public static JsonArray createJsonArrayFromString(final String jsonString) throws JsonParsingFailedException { InputStream stream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8)); Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); JsonArray readJsonArray = null; try { readJsonArray = new Gson().fromJson(reader, JsonArray.class); } catch (JsonSyntaxException jsonSyntaxException) { throw new JsonParsingFailedException(jsonSyntaxException); } catch (JsonIOException jsonIoException) { throw new JsonParsingFailedException(jsonIoException); } return readJsonArray; }
/** * Creates a {@link JsonObject} from the given json string. * * @param jsonString the json string to parse * @return the {@link JsonObject} received while parsing the given json string * @throws JsonParsingFailedException if any exception occurred at runtime */ public static JsonObject createJsonObjectFromString(final String jsonString) throws JsonParsingFailedException { InputStream stream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8)); Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); JsonObject readJsonObject = null; try { readJsonObject = new Gson().fromJson(reader, JsonObject.class); } catch (JsonSyntaxException jsonSyntaxException) { throw new JsonParsingFailedException(jsonSyntaxException); } catch (JsonIOException jsonIoException) { throw new JsonParsingFailedException(jsonIoException); } return readJsonObject; }
/** * Creates a {@link JsonObject} from the json file which can be found at the given path. * * Note that this method should only be used with a jsonFilePath starting at folders inside the * resource directory, e.g. algorithm/baselearner/... . Otherwise it will result in a * {@link NullPointerException}. For accessing {@link JsonObject}s with a more detailed path, use * {@link #createJsonObjectFromFile(File)}. * * @param jsonFilePath the path of the json file * @return the {@link JsonObject} received while parsing the json file * @throws JsonParsingFailedException if any exception occurred at runtime * @throws NullPointerException if the given file path does not start with a folder or file * inside the resource directory */ public static JsonObject createJsonObjectFromFilePath(final String jsonFilePath) throws JsonParsingFailedException { JsonObject readJsonObject = null; InputStream inputStream = JsonUtils.class.getResourceAsStream(jsonFilePath); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); try (Reader reader = new BufferedReader(inputStreamReader)) { readJsonObject = new Gson().fromJson(reader, JsonObject.class); } catch (JsonSyntaxException jsonSyntaxException) { throw new JsonParsingFailedException(jsonSyntaxException); } catch (JsonIOException jsonIoException) { throw new JsonParsingFailedException(jsonIoException); } catch (FileNotFoundException fileNotFoundException) { throw new JsonParsingFailedException(fileNotFoundException); } catch (IOException ioException) { throw new JsonParsingFailedException(ioException); } return readJsonObject; }
/** * Creates a {@link JsonObject} from the given json file. * * @param jsonFile the json filet to read * @return the {@link JsonObject} received while parsing the json file * @throws JsonParsingFailedException if any exception occurred at runtime */ public static JsonObject createJsonObjectFromFile(final File jsonFile) throws JsonParsingFailedException { JsonObject readJsonObject = null; try (Reader reader = new FileReader(jsonFile)) { readJsonObject = new Gson().fromJson(reader, JsonObject.class); } catch (JsonSyntaxException jsonSyntaxException) { throw new JsonParsingFailedException(jsonSyntaxException); } catch (JsonIOException jsonIoException) { throw new JsonParsingFailedException(jsonIoException); } catch (FileNotFoundException fileNotFoundException) { throw new JsonParsingFailedException(fileNotFoundException); } catch (IOException ioException) { throw new JsonParsingFailedException(ioException); } return readJsonObject; }
public static JsonElement parse(JsonReader reader) throws JsonParseException { boolean isEmpty = true; try { reader.peek(); isEmpty = false; return (JsonElement) TypeAdapters.JSON_ELEMENT.read(reader); } catch (Throwable e) { if (isEmpty) { return JsonNull.INSTANCE; } throw new JsonIOException(e); } catch (Throwable e2) { throw new JsonSyntaxException(e2); } catch (Throwable e22) { throw new JsonIOException(e22); } catch (Throwable e222) { throw new JsonSyntaxException(e222); } }
@Override public Object decode(Response response, Type type) throws IOException { if (response.status() == 404) return Util.emptyValueOf(type); if (response.body() == null) return null; Reader reader = response.body().asReader(); try { return gson.fromJson(reader, type); } catch (JsonIOException e) { if (e.getCause() != null && e.getCause() instanceof IOException) { throw IOException.class.cast(e.getCause()); } throw e; } finally { ensureClosed(reader); } }
@Override public Object decode(Response response, Type type) throws IOException { if (void.class == type || response.body() == null) { return null; } Reader reader = response.body().asReader(); try { return gson.fromJson(reader, type); } catch (JsonIOException e) { if (e.getCause() != null && e.getCause() instanceof IOException) { throw IOException.class.cast(e.getCause()); } throw e; } finally { ensureClosed(reader); } }
@Override protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { Charset charset = getCharset(outputMessage.getHeaders()); try (OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset)) { if (ignoreType) { gsonForWriter.toJson(o, writer); return; } if (type != null) { gsonForWriter.toJson(o, type, writer); return; } gsonForWriter.toJson(o, writer); } catch (JsonIOException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
public static JsonElement parse(JsonReader reader) throws JsonParseException { boolean isEmpty = true; try { reader.peek(); isEmpty = false; return (JsonElement) TypeAdapters.JSON_ELEMENT.read(reader); } catch (Throwable e) { if (isEmpty) { return JsonNull.INSTANCE; } throw new JsonSyntaxException(e); } catch (Throwable e2) { throw new JsonSyntaxException(e2); } catch (Throwable e22) { throw new JsonIOException(e22); } catch (Throwable e222) { throw new JsonSyntaxException(e222); } }
private void fetchUserAccounts() { NetworkManager.Get(requestUrl, new HttpResponse() { @Override public void success(String response) { try { Type listType = new TypeToken<ArrayList<NRAccount>>() { }.getType(); List<NRAccount> accounts = new Gson().fromJson(response, listType); initRecyclerView(accounts); } catch(JsonSyntaxException | JsonIOException jioe) { Log.i("gson", "parse failed"); } } @Override public void error() { } }); }
@Override public void handleResponseError(Context context, Throwable t) { //Used to provide a monitor for handling all errors //rxjava need to use ErrorHandleSubscriber (the default implementation of Subscriber's onError method), this monitor to take effect Timber.tag("Catch-Error").w(t.getMessage()); //Here is not only print errors, but also according to different errors to make different logical processing String msg = "Unknown"; if (t instanceof UnknownHostException) { msg = "The network is not available"; } else if (t instanceof SocketTimeoutException) { msg = "Network timeout"; } else if (t instanceof HttpException) { HttpException httpException = (HttpException) t; msg = convertStatusCode(httpException); } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) { msg = "Data parsing error"; } UiUtils.snackbarText(msg); }
public List<Recipe> LoadRecipes() { Gson gson = new Gson(); List<Recipe> recipes = new ArrayList<>(); for (File file : getRecipesFolder().listFiles()) { if (!file.getName().endsWith(".json")) continue; try { JsonReader reader = new JsonReader(new FileReader(file)); Recipe recipe = gson.fromJson(reader, Recipe.class); recipes.add(recipe); } catch (FileNotFoundException | JsonSyntaxException | JsonIOException e) { logger.error(e.getMessage()); e.printStackTrace(); } } return recipes; }
private void writeTempData(File file) { JsonObject root = new JsonObject(); for (EndWorldWrapper world : dedManager.getWorldWrappers()) { if (!world.isRespawnInProgress() && world.getActiveBattle() == null) return; JsonObject jsonWorld = new JsonObject(); if (world.isRespawnInProgress()) jsonWorld.addProperty("respawnTime", world.getTimeUntilRespawn()); if (world.getActiveBattle() != null) jsonWorld.addProperty("activeTemplate", world.getActiveBattle().getIdentifier()); root.add(world.getWorld().getName(), jsonWorld); } try (PrintWriter writer = new PrintWriter(tempDataFile)) { GSON.toJson(root, new JsonWriter(writer)); } catch (JsonIOException | IOException e) { e.printStackTrace(); } }
public static String extractCheckinErrorMessage(Response<CheckinResult> response) { if (response != null && response.errorBody() != null && response.errorBody().source() != null) { Buffer buffer = response.errorBody().source().buffer().clone(); try { CheckinError error = GsonSingleton.gson().fromJson(buffer.readUtf8(), CheckinError.class); if (error != null && error.errors != null) { for (Map.Entry<String, JsonElement> entry : error.errors.entrySet()) { String message = entry.getValue().getAsJsonObject().getAsJsonPrimitive("message").getAsString(); if (message != null) { return message; } } } } catch (JsonSyntaxException | JsonIOException ignored) { } } return null; }
@Test public void testInvalidSerialize() { // Gson is final so we need to call on PowerMock here. Gson gson = PowerMock.createMock(Gson.class); gson.toJson(EasyMock.isA(Object.class), EasyMock.isA(Appendable.class)); EasyMock.expectLastCall().andThrow(new JsonIOException("error")); PowerMock.replay(gson); ServiceInstance instance = new ServiceInstance(new Endpoint("foo", 1000), ImmutableMap.of(), Status.ALIVE); try { new JsonCodec(gson).serialize(instance, new ByteArrayOutputStream()); fail(); } catch (IOException e) { // Expected. } PowerMock.verify(gson); }
@Override protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { Charset charset = getCharset(outputMessage.getHeaders()); OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset); try { if (this.jsonPrefix != null) { writer.append(this.jsonPrefix); } if (type != null) { this.gson.toJson(o, type, writer); } else { this.gson.toJson(o, writer); } writer.close(); } catch (JsonIOException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
public static String hastebin(String trace) { try { HttpPost req = new HttpPost("https://hastebin.com/documents"); req.addHeader("Content-Type", "text/plain"); req.addHeader("User-Agent", "Mozilla/5.0 FlareBot"); StringEntity ent = new StringEntity(trace); req.setEntity(ent); HttpResponse response = FlareBot.HTPP_CLIENT.execute(req); if (response.getStatusLine().getStatusCode() != 200) { FlareBot.LOGGER.error("HasteBin API did not respond with a correct code! Code was: {}! Response: {}", response.getStatusLine().getStatusCode(), IOUtils.toString(response.getEntity().getContent(), Charset.defaultCharset())); return null; } return "https://hastebin.com/" + FlareBot.GSON.fromJson(new InputStreamReader(response.getEntity().getContent()), HastebinResponse.class).key; } catch (JsonSyntaxException | JsonIOException | IOException e) { FlareBot.LOGGER.error("Could not make POST request to hastebin!", e); return null; } }
static <T> JsonElement toJsonTree(TypeAdapter<T> paramTypeAdapter, T paramT) { JsonTreeWriter localJsonTreeWriter; try { localJsonTreeWriter = new JsonTreeWriter(); localJsonTreeWriter.lenient = true; paramTypeAdapter.write(localJsonTreeWriter, paramT); if (!localJsonTreeWriter.stack.isEmpty()) { throw new IllegalStateException("Expected one JSON element but was " + localJsonTreeWriter.stack); } } catch (IOException localIOException) { throw new JsonIOException(localIOException); } JsonElement localJsonElement = localJsonTreeWriter.product; return localJsonElement; }
/** * Checks if the sender is a follower of channel * * @param sender * @param channel * @return - true if sender is following channel */ public static boolean isFollower(String channel, String sender) { try { String nextUrl = "https://api.twitch.tv/kraken/users/" + sender + "/follows/channels/" + channel; System.out.println(nextUrl); JsonObject following = new JsonParser().parse( new JsonReader(new InputStreamReader(new URL(nextUrl) .openStream()))).getAsJsonObject(); if (following.get("error") != null) { return false; } else { return true; } } catch (JsonIOException | JsonSyntaxException | IOException e) { logger.log(Level.SEVERE, "An error occurred checking if " + sender + " is following " + channel.substring(1), e); } return false; }
public GeocodeResponse getLocation(String... addressElements) throws JsonSyntaxException, JsonIOException, MalformedURLException, IOException { StringBuilder sb = new StringBuilder(); for (String string : addressElements) { if (sb.length() > 0) { sb.append('+'); } sb.append(URLEncoder.encode(string.replace(' ', '+'), "UTF-8")); } String url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + sb.toString(); // Google limits this web service to 2500/day and 10 requests/s synchronized (this) { try { long elapsed = System.currentTimeMillis() - lastRequest; if (elapsed < 100) { try { Thread.sleep(100 - elapsed); } catch (InterruptedException e) { } } return gson.fromJson(new BufferedReader(new InputStreamReader(new URL(url).openStream())), GeocodeResponse.class); } finally { lastRequest = System.currentTimeMillis(); } } }
protected AbstractDvidSetupImageLoader( final int setupId, final T t, final V v, final ConstructorParameters parameters, final CacheArrayLoader< A > loader ) throws JsonSyntaxException, JsonIOException, IOException { super( setupId, new long[][]{ parameters.dimensions }, new int[][]{ parameters.cellDimensions }, new double[][]{ parameters.resolutions }, t, v, loader, new VolatileGlobalCellCache( 1, 10 ) ); }
public static ValueObjectSubscription func_148788_a(String p_148788_0_) { ValueObjectSubscription var1 = new ValueObjectSubscription(); try { JsonParser var2 = new JsonParser(); JsonObject var3 = var2.parse(p_148788_0_).getAsJsonObject(); var1.field_148790_a = var3.get("startDate").getAsLong(); var1.field_148789_b = var3.get("daysLeft").getAsInt(); } catch (JsonIOException var4) { ; } catch (JsonSyntaxException var5) { ; } return var1; }
public static SaveFile getFromFile(String filePath) { //PerceptParser parser = new PerceptParser(filePath); //parser.parse(); SaveFile savefile = null; Gson gson = new Gson(); try { savefile = gson.fromJson(new BufferedReader(new FileReader(new File(filePath))), SaveFile.class); } catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) { e.printStackTrace(); } return savefile; //return new SaveFile(filePath, parser.getPerceptList()); }
@Override protected void writeInternal( Object o, HttpOutputMessage outputMessage ) throws IOException, HttpMessageNotWritableException{ OutputStreamWriter writer = new OutputStreamWriter( outputMessage.getBody(), getCharset( outputMessage.getHeaders() ) ); try{ if( this.prefixJson ){ writer.append( "{} && " ); } Type typeOfSrc = getType(); if( typeOfSrc != null ){ this.gson.toJson( o, typeOfSrc, writer ); } else{ this.gson.toJson( o, writer ); } writer.close(); } catch( JsonIOException ex ){ throw new HttpMessageNotWritableException( "Could not write JSON: " + ex.getMessage(), ex ); } }
@Override protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), getCharset(outputMessage.getHeaders())); try { if (this.prefixJson) { writer.append("{} && "); } Type typeOfSrc = getType(); if (typeOfSrc != null) { this.gson.toJson(o, typeOfSrc, writer); } else { this.gson.toJson(o, writer); } writer.close(); } catch(JsonIOException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
/** * Returns message parsed from JSON stream. * * @return object of class passed as parameter of constructor or null if stream is empty * @throws IOException if error occurs on reading stream */ public T next() throws IOException { // on first read we check if this stream is empty with reading of the first byte of stream // if so we do not call JsonStreamParser.hasNext() because it will throw exception // if not we return read byte to stream using PushbackInputStream if (firstRead) { int firstChar = reader.read(); if (firstChar == -1) { return null; } else { reader.unread(firstChar); firstRead = false; } } try { if (streamParser.hasNext()) { return GSON.fromJson(streamParser.next(), messageClass); } } catch (JsonIOException e) { throw new IOException(e); } catch (JsonParseException ignore) { } return null; }
/** * * @param jsonFile * @return */ public String getFileAsString(String jsonFile){ String fileContents = ""; try { if(!jsonFile.startsWith("/")){ //All of the JSON files are stored in the "questions" package/folder //All json file paths should start with '/questions/' jsonFile = "/" + jsonFile; } JsonElement jelmnt = new JsonParser().parse(new InputStreamReader(this.getClass().getResourceAsStream(jsonFile))); fileContents = jelmnt.toString(); } catch (JsonIOException | JsonSyntaxException e) { e.printStackTrace(); } return fileContents; }
/** * * @param type * @param jsonFile * @return */ public ArrayList<String> getMovieOptions(String type, String jsonFile){ ArrayList<String> values = new ArrayList<String>(); try { if(!jsonFile.startsWith("/")){ jsonFile = "/" + jsonFile; } jsonFile = "/questions" + jsonFile; JsonElement jelmnt = new JsonParser().parse(new InputStreamReader(this.getClass().getResourceAsStream(jsonFile))); JsonArray jarray = jelmnt.getAsJsonObject().getAsJsonArray(type); Iterator<JsonElement> questOpt = jarray.iterator(); while (questOpt.hasNext()) { values.add(questOpt.next().getAsString()); } } catch (JsonIOException | JsonSyntaxException e) { e.printStackTrace(); } return values; }
private static CacheMeta readCacheMeta(FileSystemFacade fs, Path cacheFilePath) throws JsonSyntaxException, JsonIOException, UnsupportedEncodingException, IOException { if (fs.exists(cacheFilePath)) { InputStream inputStream = fs.open(cacheFilePath); InputStreamReader reader = new InputStreamReader( inputStream, DEFAULT_ENCODING); try { Gson gson = new Gson(); return gson.fromJson(reader, CacheMeta.class); } finally { reader.close(); inputStream.close(); } } else { return null; } }
public Object construct() { if (a instanceof ParameterizedType) { Type type = ((ParameterizedType)a).getActualTypeArguments()[0]; if (type instanceof Class) { return EnumSet.noneOf((Class)type); } else { throw new JsonIOException((new StringBuilder()).append("Invalid EnumSet type: ").append(a.toString()).toString()); } } else { throw new JsonIOException((new StringBuilder()).append("Invalid EnumSet type: ").append(a.toString()).toString()); } }
/** * Loads the user preferences * * @return UserPreferences */ public UserPreferences load() { if (preferencesFileExists()) { try { FileReader fileReader = new FileReader(getPreferencesFile()); return new GsonBuilder().create().fromJson(fileReader, UserPreferences.class); } catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) { ExceptionHandler.get().handle(e); } } return new UserPreferences(); }
public static BidResponse.Builder parse(final String result, final SSPAdapter adapter) { RtbResponseLogProcessor.instance.setLogData(result, "bidresponse", adapter.getName()); try { // TODO: define new responsetype final BidResponse response = gson.fromJson(result, BidResponse.class); return response.getBuilder(); } catch (final JsonIOException | JsonSyntaxException e) { log.error(e.getMessage()); } return null; }
@Override @SuppressWarnings("unchecked") public T read() throws JsonSyntaxException, JsonIOException { if (Primitives.isPrimitive(valueType)) { Object parsed = mapper.fromJson(source, valueType); return (T) Primitives.wrap(parsed.getClass()).cast(parsed); } else { return mapper.fromJson(source, valueType); } }
@Override public void write(Appendable sink, T body) throws JsonIOException { requireNonNull(sink, "sink"); requireNonNull(body, "body"); mapper.toJson(body, sink); }
@Override @SuppressWarnings("unchecked") public T read(Reader source) throws JsonSyntaxException, JsonIOException { requireNonNull(source, "source"); if (Primitives.isPrimitive(valueType)) { Object parsed = mapper.fromJson(source, valueType); return (T) Primitives.wrap(parsed.getClass()).cast(parsed); } else { return mapper.fromJson(source, valueType); } }
private static <T> JsonElement toJsonTree(TypeAdapter<T> typeAdapter, T value) { try { JsonTreeWriter jsonWriter = new JsonTreeWriter(); jsonWriter.setLenient(true); typeAdapter.write(jsonWriter, value); return jsonWriter.get(); } catch (Throwable e) { throw new JsonIOException(e); } }