com.google.gson.stream.MalformedJsonException Java Examples

The following examples show how to use com.google.gson.stream.MalformedJsonException. 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: MapStore.java    From FXMaps with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Called to load the serialized {@link Routes} into this store.
 * 
 * @return  a {@code RouteStore} containing previously serialized {@link Route}s
 * or an empty store if there were no Routes previously persisted.
 * 
 * @param path  the path to the persistent store json file
 */
public static MapStore load(String path) {
    path = path == null ? DEFAULT_STORE_PATH : path;
    
    try {
        Gson gson = new Gson();
        MapStore mapStore = gson.fromJson(
            Files.newBufferedReader(FileSystems.getDefault().getPath(path)), MapStore.class);
        
        for(String mapName : mapStore.getMaps().keySet()) {
            mapStore.selectMap(mapName);
            mapStore.postDeserialize();
        }
       
        mapStore.storePath = path;
        
        return mapStore;
    }catch(MalformedJsonException m) {
        System.out.println(m.getMessage());
        File f = new File(path);
        f.delete();
    }catch(Exception e) {
        System.out.println("No map store found, creating new map store.");
    }
    return new MapStore();
}
 
Example #2
Source File: JsonParser.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public JsonElement parse(Reader reader)
{
    JsonElement jsonelement;
    try
    {
        JsonReader jsonreader = new JsonReader(reader);
        jsonelement = parse(jsonreader);
        if (!jsonelement.isJsonNull() && jsonreader.peek() != JsonToken.END_DOCUMENT)
        {
            throw new JsonSyntaxException("Did not consume the entire document.");
        }
    }
    catch (MalformedJsonException malformedjsonexception)
    {
        throw new JsonSyntaxException(malformedjsonexception);
    }
    catch (IOException ioexception)
    {
        throw new JsonIOException(ioexception);
    }
    catch (NumberFormatException numberformatexception)
    {
        throw new JsonSyntaxException(numberformatexception);
    }
    return jsonelement;
}
 
Example #3
Source File: Gson.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
private static void a(Object obj, JsonReader jsonreader)
{
    if (obj != null)
    {
        try
        {
            if (jsonreader.peek() != JsonToken.END_DOCUMENT)
            {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
        }
        catch (MalformedJsonException malformedjsonexception)
        {
            throw new JsonSyntaxException(malformedjsonexception);
        }
        catch (IOException ioexception)
        {
            throw new JsonIOException(ioexception);
        }
    }
}
 
Example #4
Source File: IpcdJsonReader.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link com.google.gson.stream.JsonToken#NUMBER double} value
 * of the next token, consuming it. If the next token is a string, this
 * method will attempt to parse it as a double using
 * {@link Double#parseDouble(String)}.
 *
 * @throws IllegalStateException
 *            if the next token is not a literal value.
 * @throws NumberFormatException
 *            if the next literal value cannot be parsed as a double, or is
 *            non-finite.
 */
public double nextDouble() throws IOException {
   int p = peeked;
   if (p == PEEKED_NONE) {
      p = doPeek();
   }

   if (p == PEEKED_LONG) {
      peeked = PEEKED_NONE;
      pathIndices[stackSize - 1]++;
      return (double) peekedLong;
   }

   if (p == PEEKED_NUMBER) {
      peekedString = new String(buffer, pos, peekedNumberLength);
      pos += peekedNumberLength;
   } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED) {
      peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '"');
   } else if (p == PEEKED_UNQUOTED) {
      peekedString = nextUnquotedValue();
   } else if (p != PEEKED_BUFFERED) {
      throw new IllegalStateException("Expected a double but was " + peek() + " at line " + getLineNumber() + " column " + getColumnNumber() + " path " + getPath());
   }

   peeked = PEEKED_BUFFERED;
   double result = Double.parseDouble(peekedString); // don't catch this NumberFormatException.
   if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) {
      throw new MalformedJsonException("JSON forbids NaN and infinities: " + result + " at line " + getLineNumber() + " column " + getColumnNumber() + " path " + getPath());
   }
   peekedString = null;
   peeked = PEEKED_NONE;
   pathIndices[stackSize - 1]++;
   return result;
}
 
Example #5
Source File: ResponseErrorHandle.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
static ResponseError handleError(Throwable e) {
    ResponseError error;
    if (e instanceof HttpException) {
        HttpException exception = (HttpException) e;
        return handleHttpError(exception);
    } else if (e instanceof JsonParseException
            || e instanceof JSONException
            || e instanceof ParseException || e instanceof MalformedJsonException) {
        error = new ResponseError(e, ERROR.PARSE_ERROR);
        error.message = "解析响应数据错误";
        return error;
    } else if (e instanceof ConnectException) {
        error = new ResponseError(e, ERROR.NETWORK_ERROR);
        error.message = "连接失败,请重试";
        return error;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        error = new ResponseError(e, ERROR.SSL_ERROR);
        error.message = "证书验证失败";
        return error;
    } else if (e instanceof ConnectTimeoutException) {
        error = new ResponseError(e, ERROR.TIMEOUT_ERROR);
        error.message = "连接超时,请重试";
        return error;
    } else if (e instanceof java.net.SocketTimeoutException) {
        error = new ResponseError(e, ERROR.TIMEOUT_ERROR);
        error.message = "请求超时,请重试";
        return error;
    } else {
        error = new ResponseError(e, ERROR.UNKNOWN);
        error.message = e.getMessage();
        return error;
    }
}
 
Example #6
Source File: AlwaysListTypeAdapterFactory.java    From homeassist with Apache License 2.0 5 votes vote down vote up
@Override
public List<E> read(final JsonReader in) throws IOException {
    // This is where we detect the list "type"
    final List<E> list = new ArrayList<>();
    final JsonToken token = in.peek();
    switch (token) {
        case BEGIN_ARRAY:
            // If it's a regular list, just consume [, <all elements>, and ]
            in.beginArray();
            while (in.hasNext()) {
                list.add(elementTypeAdapter.read(in));
            }
            in.endArray();
            break;
        case BEGIN_OBJECT:
        case STRING:
        case NUMBER:
        case BOOLEAN:
            // An object or a primitive? Just add the current value to the result list
            list.add(elementTypeAdapter.read(in));
            break;
        case NULL:
            throw new AssertionError("Must never happen: check if the type adapter configured with .nullSafe()");
        case NAME:
        case END_ARRAY:
        case END_OBJECT:
        case END_DOCUMENT:
            throw new MalformedJsonException("Unexpected token: " + token);
        default:
            throw new AssertionError("Must never happen: " + token);
    }
    return list;
}
 
Example #7
Source File: Route.java    From FXMaps with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Called following deserialization to load the observable list. The observable
 * list cannot be serialized using the current method, so we use a simple list
 * for serialization and then copy the data over, after deserialization.
 */
public void postDeserialize() throws MalformedJsonException {
    observableDelegate = FXCollections.observableArrayList(delegate);
    delegate.clear();
    
    try {
        createUnderlying();
    }catch(NullPointerException npe) {
        throw new MalformedJsonException(npe.getMessage());
    }
}
 
Example #8
Source File: ElasticsearchDependenciesJob.java    From zipkin-dependencies with Apache License 2.0 5 votes vote down vote up
/** returns the lower 64 bits of the trace ID */
@Override public String call(Tuple2<String, String> pair) throws IOException {
  JsonReader reader = new JsonReader(new StringReader(pair._2));
  reader.beginObject();
  while (reader.hasNext()) {
    String nextName = reader.nextName();
    if (nextName.equals("traceId")) {
      String traceId = reader.nextString();
      return traceId.length() > 16 ? traceId.substring(traceId.length() - 16) : traceId;
    } else {
      reader.skipValue();
    }
  }
  throw new MalformedJsonException("no traceId in " + pair);
}
 
Example #9
Source File: MessageTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Message read(JsonReader in) throws IOException, JsonIOException, JsonSyntaxException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	
	in.beginObject();
	String jsonrpc = null, method = null;
	Either<String, Number> id = null;
	Object rawParams = null;
	Object rawResult = null;
	ResponseError responseError = null;
	try {
		
		while (in.hasNext()) {
			String name = in.nextName();
			switch (name) {
			case "jsonrpc": {
				jsonrpc = in.nextString();
				break;
			}
			case "id": {
				if (in.peek() == JsonToken.NUMBER)
					id = Either.forRight(in.nextInt());
				else
					id = Either.forLeft(in.nextString());
				break;
			}
			case "method": {
				method = in.nextString();
				break;
			}
			case "params": {
				rawParams = parseParams(in, method);
				break;
			}
			case "result": {
				rawResult = parseResult(in, id != null ? id.get().toString() : null);
				break;
			}
			case "error": {
				responseError = gson.fromJson(in, ResponseError.class);
				break;
			}
			default:
				in.skipValue();
			}
		}
		Object params = parseParams(rawParams, method);
		Object result = parseResult(rawResult, id != null ? id.get().toString() : null);
		
		in.endObject();
		return createMessage(jsonrpc, id, method, params, result, responseError);
		
	} catch (JsonSyntaxException | MalformedJsonException | EOFException exception) {
		if (id != null || method != null) {
			// Create a message and bundle it to an exception with an issue that wraps the original exception
			Message message = createMessage(jsonrpc, id, method, rawParams, rawResult, responseError);
			MessageIssue issue = new MessageIssue("Message could not be parsed.", ResponseErrorCode.ParseError.getValue(), exception);
			throw new MessageIssueException(message, issue);
		} else {
			throw exception;
		}
	}
}
 
Example #10
Source File: JsonParserTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void objectNoName() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("{: 1");
}
 
Example #11
Source File: JsonParserTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void objectMissingElement() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("{1: ");
}
 
Example #12
Source File: JsonParserTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void arrayMissingElement() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("[1, 2, ]");
}
 
Example #13
Source File: JsonParserTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void objectEarlyEnd() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("{foo:}");
}
 
Example #14
Source File: JsonParserTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void nanFails() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("NaN");
}
 
Example #15
Source File: MapStore.java    From FXMaps with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Called following deserialization to load the observable list. The observable
 * list cannot be serialized using the current method, so we use a simple list
 * for serialization and then copy the data over, after deserialization.
 */
public void postDeserialize() throws MalformedJsonException {
    for(Route r : maps.get(selectedMap).getRoutes()) {
        r.postDeserialize();
    }
}
 
Example #16
Source File: JsonParserTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void nanFails() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("NaN");
}
 
Example #17
Source File: ErrorWrapper.java    From android with Apache License 2.0 4 votes vote down vote up
static Throwable wrapError(Retrofit retrofit, Throwable e) {
    if (e instanceof HttpException) {
        HttpException he = (HttpException) e;

        ErrorResponse r = parseError(retrofit, he.response());

        if (r != null && r.message != null) {
            if (r.message.contains("No provider support found for coordinate")) {
                UnsupportedCoordinatesException uce = new UnsupportedCoordinatesException(r.message, e);
                uce.setProviderName(r.provider);

                return uce;
            }

            if (r.message.contains("Unknown place code")) {
                UnknownPlaceCodeException upce = new UnknownPlaceCodeException(r.message, e);
                upce.setProviderName(r.provider);

                return upce;
            }

            if (r.message.contains("Data format at e-solat") || r.message.contains("Error connecting to")) {
                PrayerProviderException ppe = new PrayerProviderException(r.message, e);

                if (!r.hasProviderName()) {
                    ppe.setProviderName("JAKIM");
                } else {
                    ppe.setProviderName(r.provider);
                }

                return ppe;
            }
        }

        return new ServerException("Server error " + he.code(), he);
    }

    if (e instanceof MalformedJsonException) {
        return new ServerException("Malformed JSON", e);
    }

    return e;
}
 
Example #18
Source File: RxHelper.java    From RetrofitGO with Apache License 2.0 4 votes vote down vote up
public static Flowable<Error> handleError(final Throwable e) {
        return Flowable.create(emitter -> {
            e.printStackTrace();
            if (e instanceof ConnectException || e instanceof UnknownHostException) {
                emitter.onNext(ErrorHelper.netError());
            } else if (e instanceof HttpException) {
                emitter.onNext(ErrorHelper.httpError());
                //eos的接口查询失败竟然是500
//                Request request = Objects.requireNonNull(((HttpException) e).response().raw().networkResponse()).request();
//                if(request!=null){
//                    HttpUrl url = request.url();
//                    URI uri = url.uri();
//                    String host = uri.getHost();
//                    if(host.equals(getEosApiHost())){
//                        emitter.onNext(new Error(EOS_ERROR,e.getMessage()));
//                    }else{
//                        emitter.onNext(ErrorHelper.httpError());
//                    }
//                }
            } else if (e instanceof SocketTimeoutException) {
                emitter.onNext(ErrorHelper.timeout());
            } else if (e instanceof SSLException) {
                emitter.onNext(ErrorHelper.sslError());
            } else if (e instanceof MalformedJsonException || e instanceof JSONException ||
                    e instanceof JsonParseException) {
                emitter.onNext(ErrorHelper.parseError());
            } else if (e instanceof ClassCastException) {
                emitter.onNext(ErrorHelper.castError());
            } else if (e instanceof ApiException) {
                // 接口请求失败
                ApiException apiException = (ApiException) e;
                if (apiException.getError() == ErrorHelper.TOKEN_EXPIRED
                        && RetrofitClient.get().getAuthCallback() != null) {
                    RetrofitClient.get().getAuthCallback().onTokenExpired(apiException.getMsg());
                } else {
                    emitter.onNext(ErrorHelper.apiError(apiException.getError(), apiException.getMsg()));
                }
            } else if (e instanceof IOException) {
                emitter.onNext(ErrorHelper.parseError());
            } else {
                // 未知错误
                emitter.onNext(ErrorHelper.parseError());
            }
        }, BackpressureStrategy.BUFFER);
    }
 
Example #19
Source File: ExceptionHandle.java    From TikTok with Apache License 2.0 4 votes vote down vote up
public static ResponseThrowable handleException(Throwable e) {
    ResponseThrowable ex;
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ResponseThrowable(e, ERROR.HTTP_ERROR);
        switch (httpException.code()) {
            case UNAUTHORIZED:
                ex.message = "操作未授权";
                break;
            case FORBIDDEN:
                ex.message = "请求被拒绝";
                break;
            case NOT_FOUND:
                ex.message = "资源不存在";
                break;
            case REQUEST_TIMEOUT:
                ex.message = "服务器执行超时";
                break;
            case INTERNAL_SERVER_ERROR:
                ex.message = "服务器内部错误";
                break;
            case SERVICE_UNAVAILABLE:
                ex.message = "服务器不可用";
                break;
            default:
                ex.message = "网络错误";
                break;
        }
        return ex;
    } else if (e instanceof JsonParseException
            || e instanceof JSONException
            || e instanceof ParseException || e instanceof MalformedJsonException) {
        ex = new ResponseThrowable(e, ERROR.PARSE_ERROR);
        ex.message = "解析错误";
        return ex;
    } else if (e instanceof ConnectException) {
        ex = new ResponseThrowable(e, ERROR.NETWORD_ERROR);
        ex.message = "连接失败";
        return ex;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        ex = new ResponseThrowable(e, ERROR.SSL_ERROR);
        ex.message = "证书验证失败";
        return ex;
    } else if (e instanceof ConnectTimeoutException) {
        ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else if (e instanceof java.net.SocketTimeoutException) {
        ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else {
        ex = new ResponseThrowable(e, ERROR.UNKNOWN);
        ex.message = "未知错误";
        return ex;
    }
}
 
Example #20
Source File: JsonParserTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void objectNoName() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("{: 1");
}
 
Example #21
Source File: JsonParserTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void objectMissingElement() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("{1: ");
}
 
Example #22
Source File: JsonParserTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void arrayMissingElement() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("[1, 2, ]");
}
 
Example #23
Source File: JsonParserTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void objectEarlyEnd() throws IOException {
  thrown.expect(MalformedJsonException.class);

  JsonParser.parse("{foo:}");
}
 
Example #24
Source File: IpcdJsonReader.java    From arcusplatform with Apache License 2.0 2 votes vote down vote up
/**
 * Throws a new IO exception with the given message and a context snippet
 * with this reader's content.
 */
private IOException syntaxError(String message) throws IOException {
   throw new MalformedJsonException(message + " at line " + getLineNumber() + " column " + getColumnNumber() + " path " + getPath());
}