com.google.gson.JsonIOException Java Examples
The following examples show how to use
com.google.gson.JsonIOException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonElementResolverTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testOutOfBoundIndexException() throws JsonIOException, JsonSyntaxException, FileNotFoundException { // https://github.com/trimou/trimou/issues/73 String json = "{\"numbers\": [1,2]}"; String template = "One of users is {{numbers.2}}."; final JsonElement jsonElement = new JsonParser().parse(json); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .setMissingValueHandler( new ThrowingExceptionMissingValueHandler()) .omitServiceLoaderConfigurationExtensions() .setProperty(JsonElementResolver.UNWRAP_JSON_PRIMITIVE_KEY, true) .setProperty(GsonValueConverter.ENABLED_KEY, false) .addResolver(new ThisResolver()).addResolver(new MapResolver()) .addResolver(new JsonElementResolver()).build(); final Mustache mustache = engine.compileMustache("unwrap_array_index", template); MustacheExceptionAssert.expect(MustacheProblem.RENDER_NO_VALUE) .check(() -> mustache.render(jsonElement)); }
Example #2
Source File: JavaBindingsToJson.java From api-mining with GNU General Public License v3.0 | 6 votes |
/** * Extract the bindings from the input folder to the output file, using the * bindingExtractor. * * @param inputFolder * @param outputFile * @param bindingExtractor * @throws IOException * @throws JsonIOException */ public static void extractBindings(final File inputFolder, final File outputFile, final AbstractJavaNameBindingsExtractor bindingExtractor) throws IOException, JsonIOException { final Collection<File> allFiles = FileUtils .listFiles(inputFolder, JavaTokenizer.javaCodeFileFilter, DirectoryFileFilter.DIRECTORY); final List<SerializableResolvedSourceCode> resolvedCode = allFiles .parallelStream() .map(f -> getResolvedCode(f, bindingExtractor)) .filter(r -> r != null) .map(r -> SerializableResolvedSourceCode .fromResolvedSourceCode(r)) .filter(s -> !s.boundVariables.isEmpty()) .collect(Collectors.toList()); final FileWriter writer = new FileWriter(outputFile); try { final Gson gson = new Gson(); gson.toJson(resolvedCode, writer); } finally { writer.close(); } }
Example #3
Source File: CertificateBlacklist.java From mapbox-events-android with MIT License | 6 votes |
private List<String> obtainBlacklistContents(File file) throws IOException { InputStream inputStream = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); Gson gson = new Gson(); List<String> blacklist = null; try { JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); if (jsonObject != null) { JsonArray jsonArray = jsonObject.getAsJsonArray("RevokedCertKeys"); Type listType = new TypeToken<List<String>>() { }.getType(); blacklist = gson.fromJson(jsonArray.toString(), listType); } } catch (JsonIOException | JsonSyntaxException exception) { Log.e(LOG_TAG, exception.getMessage()); } reader.close(); return blacklist != null ? blacklist : Collections.<String>emptyList(); }
Example #4
Source File: Streams.java From letv with Apache License 2.0 | 6 votes |
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); } }
Example #5
Source File: ExecuteCommandParamsTypeAdapter.java From n4js with Eclipse Public License 1.0 | 6 votes |
@SuppressWarnings("hiding") private List<Object> parseArguments(JsonReader in, String command) throws IOException, JsonIOException { JsonToken next = in.peek(); if (next == JsonToken.NULL) { in.nextNull(); return Collections.emptyList(); } Type[] argumentTypes = getArgumentTypes(command); List<Object> arguments = new ArrayList<>(argumentTypes.length); int index = 0; in.beginArray(); while (in.hasNext()) { Type parameterType = index < argumentTypes.length ? argumentTypes[index] : null; Object argument = fromJson(in, parameterType); arguments.add(argument); index++; } in.endArray(); while (index < argumentTypes.length) { arguments.add(null); index++; } return arguments; }
Example #6
Source File: k.java From MiBandDecompiled with Apache License 2.0 | 6 votes |
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()); } }
Example #7
Source File: ResponseErrorListenerImpl.java From Hands-Chopping with Apache License 2.0 | 6 votes |
@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); }
Example #8
Source File: JavaBindingsToJson.java From tassal with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * @param args * @throws IOException * @throws JsonIOException */ public static void main(final String[] args) throws JsonIOException, IOException { if (args.length != 3) { System.err .println("Usage <inputFolder> variables|methodinvocations|" + "methodinvocations_typegram|methoddeclarations|methoddeclarations_nooverride" + "methoddeclarations_typegram|types <outputFile>"); System.exit(-1); } final File inputFolder = new File(args[0]); final File outputFile = new File(args[2]); final AbstractJavaNameBindingsExtractor bindingExtractor = getExtractorForName( args[1], inputFolder); extractBindings(inputFolder, outputFile, bindingExtractor); }
Example #9
Source File: WSO2PluginProjectWizard.java From developer-studio with Apache License 2.0 | 6 votes |
private List<String> addWizardElemsFromDownloadedPlugins(String fileName) { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonElement jsonElement = null; List<String> templateIDList = new ArrayList<String>(); try { jsonElement = parser.parse(new FileReader(fileName)); Type type = new TypeToken<List<String>>() { }.getType(); templateIDList = gson.fromJson(jsonElement, type); } catch (JsonIOException | JsonSyntaxException | IOException e1) { log.error("Could not read the json file containing the plugin template information " + e1); MultiStatus status = MessageDialogUtils.createMultiStatus(e1.getLocalizedMessage(), e1, WSO2PluginConstants.PACKAGE_ID); // show error dialog ErrorDialog.openError(this.getShell(), WSO2PluginConstants.ERROR_DIALOG_TITLE, "Could not read the json file containing the plugin template information. Sample List is empty ", status); } return templateIDList; }
Example #10
Source File: JavaBindingsToJson.java From api-mining with GNU General Public License v3.0 | 6 votes |
/** * @param args * @throws IOException * @throws JsonIOException */ public static void main(final String[] args) throws JsonIOException, IOException { if (args.length != 3) { System.err .println("Usage <inputFolder> variables|methodinvocations|" + "methodinvocations_typegram|methoddeclarations|methoddeclarations_nooverride" + "methoddeclarations_typegram|types <outputFile>"); System.exit(-1); } final File inputFolder = new File(args[0]); final File outputFile = new File(args[2]); final AbstractJavaNameBindingsExtractor bindingExtractor = getExtractorForName( args[1], inputFolder); extractBindings(inputFolder, outputFile, bindingExtractor); }
Example #11
Source File: GsonHttpMessageConverter.java From lams with GNU General Public License v2.0 | 6 votes |
@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); } }
Example #12
Source File: RestAPI.java From movieapp-dialog with Apache License 2.0 | 6 votes |
/** * * @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; }
Example #13
Source File: WSO2PluginProjectWizard.java From developer-studio with Apache License 2.0 | 6 votes |
private WSO2PluginSampleExt generateWSO2PluginSampleExt(String fileName, String pluginSamlpeId) { Gson gson = new Gson(); WSO2PluginSampleExt wso2PluginSampleExt = null; String fileToRead = fileName + pluginSamlpeId + File.separator + WSO2PluginConstants.SAMPLE_DESCRIPTION_FILE; try { BufferedReader br = new BufferedReader(new FileReader(fileToRead)); wso2PluginSampleExt = gson.fromJson(br, WSO2PluginSampleExt.class); wso2PluginSampleExt.setIsUpdatedFromGit("true"); wso2PluginSampleExt.setPluginArchive( fileName + pluginSamlpeId + File.separator + wso2PluginSampleExt.getPluginArchive()); } catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) { log.error("Could not load the plugin sample from the archive, error in the sample format " + e); MultiStatus status = MessageDialogUtils.createMultiStatus(e.getLocalizedMessage(), e, WSO2PluginConstants.PACKAGE_ID); // show error dialog ErrorDialog.openError(this.getShell(), WSO2PluginConstants.ERROR_DIALOG_TITLE, "Could not load the plugin sample from the archive, error in the sample format ", status); } return wso2PluginSampleExt; }
Example #14
Source File: DiscoveryServiceTest.java From java-sdk with Apache License 2.0 | 6 votes |
/** * Creates the configuration is successful. * * @throws JsonSyntaxException the json syntax exception * @throws JsonIOException the json IO exception * @throws FileNotFoundException the file not found exception * @throws InterruptedException the interrupted exception */ @Test public void createConfigurationIsSuccessful() throws JsonSyntaxException, JsonIOException, FileNotFoundException, InterruptedException { server.enqueue(jsonResponse(createConfResp)); CreateConfigurationOptions.Builder createBuilder = new CreateConfigurationOptions.Builder(); Configuration configuration = GsonSingleton.getGson() .fromJson(new FileReader(DISCOVERY_TEST_CONFIG_FILE), Configuration.class); createBuilder.configuration(configuration); createBuilder.environmentId(environmentId); createBuilder.name(uniqueConfigName); Configuration response = discoveryService.createConfiguration(createBuilder.build()).execute().getResult(); RecordedRequest request = server.takeRequest(); assertEquals(CONF1_PATH, request.getPath()); assertEquals(POST, request.getMethod()); assertEquals(createConfResp, response); }
Example #15
Source File: RestAPI.java From movieapp-dialog with Apache License 2.0 | 6 votes |
/** * getJSONArray - read JSON and find the values associated with the element param * @param jsonBody = JSON to read in string form * @param element - element looking for * @return - String value of element */ public ArrayList<String> getJSONArrayValue(String jsonBody, String field){ ArrayList<String> values = new ArrayList<String>(); try { JsonElement je=new JsonParser().parse(jsonBody); JsonArray inner = je.getAsJsonObject().getAsJsonArray(field); Iterator<JsonElement> innerIter = inner.iterator(); while (innerIter.hasNext()){ JsonElement innerEntry = innerIter.next(); values.add(innerEntry.getAsString()); } } catch (JsonIOException | JsonSyntaxException e) { e.printStackTrace(); } return values; }
Example #16
Source File: RecordingManager.java From openvidu with Apache License 2.0 | 6 votes |
public Recording getRecordingFromEntityFile(File file) { if (file.isFile() && file.getName().startsWith(RecordingManager.RECORDING_ENTITY_FILE)) { JsonObject json; try { json = jsonUtils.fromFileToJsonObject(file.getAbsolutePath()); } catch (JsonIOException | JsonSyntaxException | IOException e) { log.error("Error reading recording entity file {}: {}", file.getAbsolutePath(), (e.getMessage())); return null; } Recording recording = new Recording(json); if (io.openvidu.java.client.Recording.Status.ready.equals(recording.getStatus()) || io.openvidu.java.client.Recording.Status.failed.equals(recording.getStatus())) { recording.setUrl(getRecordingUrl(recording)); } return recording; } return null; }
Example #17
Source File: ResponseErrorListenerImpl.java From MVPArms with Apache License 2.0 | 6 votes |
@Override public void handleResponseError(Context context, Throwable t) { Timber.tag("Catch-Error").w(t); //这里不光只能打印错误, 还可以根据不同的错误做出不同的逻辑处理 //这里只是对几个常用错误进行简单的处理, 展示这个类的用法, 在实际开发中请您自行对更多错误进行更严谨的处理 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); }
Example #18
Source File: GsonDiskConverter.java From RxCache with Apache License 2.0 | 6 votes |
@Override public boolean writer(OutputStream sink, Object data) { try { String json = mGson.toJson(data); byte[] bytes = json.getBytes(); sink.write(bytes, 0, bytes.length); sink.flush(); return true; } catch (JsonIOException | IOException e) { LogUtils.log(e); } finally { Utils.close(sink); } return false; }
Example #19
Source File: GsonDecoder.java From feign with Apache License 2.0 | 6 votes |
@Override public Object decode(Response response, Type type) throws IOException { if (response.body() == null) return null; Reader reader = response.body().asReader(UTF_8); 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); } }
Example #20
Source File: JavaBindingsToJson.java From codemining-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Extract the bindings from the input folder to the output file, using the * bindingExtractor. * * @param inputFolder * @param outputFile * @param bindingExtractor * @throws IOException * @throws JsonIOException */ public static void extractBindings(final File inputFolder, final File outputFile, final AbstractJavaNameBindingsExtractor bindingExtractor) throws IOException, JsonIOException { final Collection<File> allFiles = FileUtils .listFiles(inputFolder, JavaTokenizer.javaCodeFileFilter, DirectoryFileFilter.DIRECTORY); final List<SerializableResolvedSourceCode> resolvedCode = allFiles .parallelStream() .map(f -> getResolvedCode(f, bindingExtractor)) .filter(r -> r != null) .map(r -> SerializableResolvedSourceCode .fromResolvedSourceCode(r)) .filter(s -> !s.boundVariables.isEmpty()) .collect(Collectors.toList()); final FileWriter writer = new FileWriter(outputFile); try { final Gson gson = new Gson(); gson.toJson(resolvedCode, writer); } finally { writer.close(); } }
Example #21
Source File: JavaBindingsToJson.java From tassal with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Extract the bindings from the input folder to the output file, using the * bindingExtractor. * * @param inputFolder * @param outputFile * @param bindingExtractor * @throws IOException * @throws JsonIOException */ public static void extractBindings(final File inputFolder, final File outputFile, final AbstractJavaNameBindingsExtractor bindingExtractor) throws IOException, JsonIOException { final Collection<File> allFiles = FileUtils .listFiles(inputFolder, JavaTokenizer.javaCodeFileFilter, DirectoryFileFilter.DIRECTORY); final List<SerializableResolvedSourceCode> resolvedCode = allFiles .parallelStream() .map(f -> getResolvedCode(f, bindingExtractor)) .filter(r -> r != null) .map(r -> SerializableResolvedSourceCode .fromResolvedSourceCode(r)) .filter(s -> !s.boundVariables.isEmpty()) .collect(Collectors.toList()); final FileWriter writer = new FileWriter(outputFile); try { final Gson gson = new Gson(); gson.toJson(resolvedCode, writer); } finally { writer.close(); } }
Example #22
Source File: JsonStorage.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private @Nullable Map<String, StorageEntry> readDatabase(File inputFile) { try { final Map<String, StorageEntry> inputMap = new ConcurrentHashMap<>(); FileReader reader = new FileReader(inputFile); Map<String, StorageEntry> loadedMap = internalMapper.fromJson(reader, map.getClass()); if (loadedMap != null && !loadedMap.isEmpty()) { inputMap.putAll(loadedMap); } return inputMap; } catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) { logger.error("Error reading JsonDB from {}. Cause {}.", inputFile.getPath(), e.getMessage()); return null; } }
Example #23
Source File: CityJSONReader.java From citygml4j with Apache License 2.0 | 6 votes |
public CityModel read() throws CityJSONReadException { // prepare builder builder.registerTypeAdapterFactory(new CityJSONTypeAdapterFactory() .withTypeFilter(typeFilter) .processUnknownExtensions(processUnknownExtensions)); CityJSON cityJSON; try { cityJSON = builder.create().fromJson(reader, CityJSON.class); } catch (JsonIOException | JsonSyntaxException e) { throw new CityJSONReadException("Caused by: ", e); } if (cityJSON != null) { metadata = cityJSON.getMetadata(); return unmarshaller.unmarshal(cityJSON); } return null; }
Example #24
Source File: GsonHttpMessageConverter.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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); } }
Example #25
Source File: RestAPI.java From movieapp-dialog with Apache License 2.0 | 6 votes |
/** * * @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; }
Example #26
Source File: TypeAdapters.java From gson with Apache License 2.0 | 5 votes |
@Override public URI read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } try { String nextString = in.nextString(); return "null".equals(nextString) ? null : new URI(nextString); } catch (URISyntaxException e) { throw new JsonIOException(e); } }
Example #27
Source File: JsonUtil.java From moon-api-gateway with MIT License | 5 votes |
public static <T> T readValue(final InputStream stream, Class<T> clazz) { try { return objectMapper.readValue(stream, clazz); } catch (IOException ex) { throw new JsonIOException(ex); } }
Example #28
Source File: ImportController.java From TinkerTime with GNU General Public License v3.0 | 5 votes |
private int importJsonList(Path sourcePath) throws JsonIOException, JsonSyntaxException, FileNotFoundException, MalformedURLException { int imported = 0; JsonArray mods = new JsonParser().parse(new FileReader(sourcePath.toFile())).getAsJsonArray(); for (JsonElement modEle : mods){ String url = modEle.getAsJsonObject().get("pageUrl").getAsString(); try { if (modManager.downloadNewMod(new URL(url))){ imported++; } } catch (SQLException | ModUpdateFailedException e) { e.printStackTrace(); // TODO send all exceptions to the user somehow } } return imported; }
Example #29
Source File: RenamingDatasetExtractor.java From naturalize with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * @param outputFilePrefix * @param outputFileSuffix * @param renamedVariablesDatapoints * @throws IOException * @throws JsonIOException */ public static void writeJson( final String outputFilePrefix, final String outputFileSuffix, final List<RenamedSerializableResolvedSourceCode> renamedVariablesDatapoints) throws IOException, JsonIOException { final File outputFile = new File(outputFilePrefix + outputFileSuffix); final FileWriter writer = new FileWriter(outputFile); try { final Gson gson = new Gson(); gson.toJson(renamedVariablesDatapoints, writer); } finally { writer.close(); } }
Example #30
Source File: GsonConverterFactory.java From ProjectX with Apache License 2.0 | 5 votes |
@Override public T convert(ResponseBody value) throws IOException { try { final JsonReader reader = mGson.newJsonReader(value.charStream()); T result = mGson.fromJson(reader, mType); if (reader.peek() != JsonToken.END_DOCUMENT) { throw new JsonIOException("JSON document was not fully consumed."); } return result; } finally { value.close(); } }