下面列出了怎么用com.google.gson.JsonIOException的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@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);
}
@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;
}
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();
}
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
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);
}
}
@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);
}
}
@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);
}
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;
}
@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));
}
@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;
}
@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);
}
}
/**
* 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();
}
}
/**
* 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();
}
}
@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;
}
}
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;
}
/**
* 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);
}
/**
*
* @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;
}
/**
* 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;
}
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;
}
/**
*
* @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;
}
/**
* 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();
}
}
/**
* @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);
}
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());
}
}
/**
* @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);
}
@Override
public Iterator<ResourceRecordSet<?>> build(JsonReader reader) throws IOException {
JsonElement data;
try {
data = new JsonParser().parse(reader);
} catch (JsonIOException e) {
if (e.getCause() != null && e.getCause() instanceof IOException) {
throw IOException.class.cast(e.getCause());
}
throw e;
}
// there are 2 forms for record responses: an array of same type, or a
// map per type.
if (data.isJsonArray()) {
return new GroupByRecordNameAndTypeIterator(data.getAsJsonArray().iterator());
} else if (data.isJsonObject()) {
List<JsonElement> elements = new ArrayList<JsonElement>();
for (Entry<String, JsonElement> entry : data.getAsJsonObject().entrySet()) {
if (entry.getValue() instanceof JsonArray) {
for (JsonElement element : entry.getValue().getAsJsonArray()) {
elements.add(element);
}
}
}
return new GroupByRecordNameAndTypeIterator(elements.iterator());
} else {
throw new IllegalStateException("unknown format: " + data);
}
}
@Test
public void fromJson() throws URISyntaxException, JsonIOException, JsonSyntaxException, IOException, TranscoderException, InstantiationException, IllegalAccessException {
try (final Reader reader = new InputStreamReader(new FileInputStream(PATH_IN + ninePatchConfig))) {
Type t = new TypeToken<Set<NinePatch>>() {}.getType();
Set<NinePatch> ninePatchSet = new GsonBuilder().create().fromJson(reader, t);
NinePatchMap ninePatchMap = NinePatch.init(ninePatchSet);
QualifiedResource svg = qualifiedSVGResourceFactory.fromSVGFile(new File(PATH_IN + resourceName));
NinePatch ninePatch = ninePatchMap.getBestMatch(svg);
assertNotNull(ninePatch);
final String name = svg.getName();
Reflect.on(svg).set("name", name + "_" + targetDensity.name());
plugin.transcode(svg, targetDensity, new File(PATH_OUT), ninePatch);
final File ninePatchFile = new File(PATH_OUT, svg.getName() + ".9." + OUTPUT_FORMAT.name().toLowerCase());
final File nonNinePatchFile = new File(PATH_OUT, svg.getName() + "." + OUTPUT_FORMAT.name().toLowerCase());
if (OUTPUT_FORMAT.hasNinePatchSupport()) {
assertTrue(FilenameUtils.getName(ninePatchFile.getAbsolutePath()) + " does not exists although the output format supports nine patch", ninePatchFile.exists());
assertTrue(FilenameUtils.getName(nonNinePatchFile.getAbsolutePath()) + " file does not exists although the output format supports nine patch", !nonNinePatchFile.exists());
BufferedImage image = ImageIO.read(new FileInputStream(ninePatchFile));
tester.test(image);
// test corner pixels
int w = image.getWidth();
int h = image.getHeight();
new PixelTester(new int[][] {}, new int[][] {
{0, 0},
{0, h - 1},
{w - 1, 0},
{w - 1, h - 1}
}).test(image);
} else {
assertTrue(FilenameUtils.getName(ninePatchFile.getAbsolutePath()) + " exists although the output format does not support nine patch", !ninePatchFile.exists());
assertTrue(FilenameUtils.getName(nonNinePatchFile.getAbsolutePath()) + " does not exists although the output format does not support nine patch", nonNinePatchFile.exists());
}
}
}
public static Response load(InputStream is) throws JSONStructureException {
try {
GsonJsonResponse jsonResponse = gson.fromJson(new InputStreamReader(is, StandardCharsets.UTF_8), GsonJsonResponse.class);
jsonResponse.postFromJsonSerialization();
return jsonResponse.toXacmlResponse();
} catch (JsonSyntaxException | JsonIOException e) {
throw new JSONStructureException("Failed to load json stream", e);
}
}
public static String exceptionHandler(Throwable throwable){
String errorMsg="未知异常";
if(throwable instanceof UnknownHostException){
errorMsg="网络不可用";
}else if(throwable instanceof SocketTimeoutException){
errorMsg="网络连接超时";
}else if(throwable instanceof HttpException){
HttpException httpException= (HttpException) throwable;
errorMsg=convertStatusCode(httpException);
}else if(throwable instanceof ParseException || throwable instanceof JSONException
|| throwable instanceof JsonIOException){
errorMsg = "数据解析错误";
}
return errorMsg;
}
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);
}
}