public static Event parseEvent(byte[] event) { //parse the event payload and remove the type attribute JsonReader jsonReader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(event))); JsonElement jsonElement = Streams.parse(jsonReader); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD); if (labelJsonElement == null) { throw new IllegalArgumentException("Event does not define a type field: " + new String(event)); } //convert json to POJO, based on the type attribute switch (labelJsonElement.getAsString()) { case "watermark": return gson.fromJson(jsonElement, WatermarkEvent.class); case "trip": return gson.fromJson(jsonElement, TripEvent.class); default: throw new IllegalArgumentException("Found unsupported event type: " + labelJsonElement.getAsString()); } }
public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException { boolean oldLenient = writer.isLenient(); writer.setLenient(true); boolean oldHtmlSafe = writer.isHtmlSafe(); writer.setHtmlSafe(this.htmlSafe); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setSerializeNulls(this.serializeNulls); try { Streams.write(jsonElement, writer); writer.setLenient(oldLenient); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } catch (Throwable e) { throw new JsonIOException(e); } catch (Throwable th) { writer.setLenient(oldLenient); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } }
/** * Writes the JSON for {@code jsonElement} to {@code writer}. * @throws JsonIOException if there was a problem writing to the writer */ public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException { boolean oldLenient = writer.isLenient(); writer.setLenient(true); boolean oldHtmlSafe = writer.isHtmlSafe(); writer.setHtmlSafe(htmlSafe); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setSerializeNulls(serializeNulls); try { Streams.write(jsonElement, writer); } catch (IOException e) { throw new JsonIOException(e); } finally { writer.setLenient(oldLenient); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } }
@Override public Type read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement typeValueJsonElement = jsonElement.getAsJsonObject().remove("type"); if (typeValueJsonElement == null || typeValueJsonElement.isJsonNull()) { throw new JsonParseException("cannot deserialize generator.standard.polymorphism.Type because the subtype field 'type' is either null or does not exist."); } java.lang.String value = typeValueJsonElement.getAsString(); TypeAdapter<? extends generator.standard.polymorphism.Type> delegate = typeAdaptersDelegatedByValueMap.get(value); if (delegate == null) { throw new GsonSubTypeFailureException("Failed to find subtype for value: " + value); } generator.standard.polymorphism.Type result = delegate.fromJsonTree(jsonElement); if (result == null) { throw new GsonSubTypeFailureException("Failed to deserailize subtype for object: " + jsonElement); } return result; }
@Override public Type read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement typeValueJsonElement = jsonElement.getAsJsonObject().remove("type"); if (typeValueJsonElement == null || typeValueJsonElement.isJsonNull()) { throw new JsonParseException("cannot deserialize generator.standard.polymorphism.Type because the subtype field 'type' is either null or does not exist."); } java.lang.String value = typeValueJsonElement.getAsString(); TypeAdapter<? extends generator.standard.polymorphism.Type> delegate = typeAdaptersDelegatedByValueMap.get(value); if (delegate == null) { // Use the default type adapter if the type is unknown. delegate = defaultTypeAdapterDelegate; } generator.standard.polymorphism.Type result = delegate.fromJsonTree(jsonElement); return result; }
@SuppressWarnings("unused") @OnMessage public void onMessage(ByteBuffer message, Session session) { HillviewLogger.instance.info("New message from client", "{0}", session.getId()); RpcRequest req; try { ByteArrayInputStream stream = new ByteArrayInputStream(message.array()); InflaterInputStream decompressed = new InflaterInputStream(stream); Reader reader = new InputStreamReader(decompressed); JsonReader jReader = new JsonReader(reader); JsonElement elem = Streams.parse(jReader); HillviewLogger.instance.info("Decoded message", "{0}", elem.toString()); req = new RpcRequest(elem); if (RpcObjectManager.instance.getTarget(session) != null) throw new RuntimeException("Session already associated with a request!"); } catch (Exception ex) { HillviewLogger.instance.error("Error processing json", ex); this.replyWithError(ex, session); return; } RpcRequestContext context = new RpcRequestContext(session); RpcServer.execute(req, context); }
public ITable load() { Schema schema = null; if (this.schemaPath != null) schema = Schema.readFromJsonFile(Paths.get(this.schemaPath)); Reader file = this.getFileReader(); JsonReader jReader = new JsonReader(file); JsonElement elem = Streams.parse(jReader); if (!elem.isJsonArray()) throw new RuntimeException("Expected a JSON array in file " + filename); JsonArray array = elem.getAsJsonArray(); if (array.size() == 0 && schema == null) throw new RuntimeException("Empty JSON array in file " + filename); if (schema == null) schema = this.guessSchema(filename, array); IAppendableColumn[] columns = schema.createAppendableColumns(); this.currentRow = 0; for (JsonElement e : array) this.append(columns, e); return new Table(columns); }
public final T read(JsonReader paramJsonReader) throws IOException { if (this.deserializer == null) { return delegate().read(paramJsonReader); } JsonElement localJsonElement = Streams.parse(paramJsonReader); if ((localJsonElement instanceof JsonNull)) { return null; } try { JsonDeserializer localJsonDeserializer = this.deserializer; Type localType = this.typeToken.type; Object localObject = localJsonDeserializer.deserialize$140ae884(localJsonElement, localType); return localObject; } catch (JsonParseException localJsonParseException) { throw localJsonParseException; } catch (Exception localException) { throw new JsonParseException(localException); } }
public final void write(JsonWriter paramJsonWriter, T paramT) throws IOException { if (this.serializer == null) { delegate().write(paramJsonWriter, paramT); return; } if (paramT == null) { paramJsonWriter.nullValue(); return; } JsonSerializer localJsonSerializer = this.serializer; Streams.write(localJsonSerializer.serialize$117eb95b(paramT), paramJsonWriter); }
public String toString() { try { StringWriter localStringWriter = new StringWriter(); JsonWriter localJsonWriter = new JsonWriter(localStringWriter); localJsonWriter.lenient = true; Streams.write(this, localJsonWriter); String str = localStringWriter.toString(); return str; } catch (IOException localIOException) { throw new AssertionError(localIOException); } }
public String toString() { String s; try { StringWriter stringwriter = new StringWriter(); JsonWriter jsonwriter = new JsonWriter(stringwriter); jsonwriter.setLenient(true); Streams.write(this, jsonwriter); s = stringwriter.toString(); } catch (IOException ioexception) { throw new AssertionError(ioexception); } return s; }
public void write(JsonWriter jsonwriter, Object obj) { if (a == null) { a().write(jsonwriter, obj); return; } if (obj == null) { jsonwriter.nullValue(); return; } else { Streams.write(a.serialize(obj, d.getType(), c.c), jsonwriter); return; } }
public String getJsapiTicket(boolean forceRefresh) throws WxErrorException { if (forceRefresh) { wxCpConfigStorage.expireJsapiTicket(); } if (wxCpConfigStorage.isJsapiTicketExpired()) { synchronized (globalJsapiTicketRefreshLock) { if (wxCpConfigStorage.isJsapiTicketExpired()) { String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket"; String responseContent = execute(new SimpleGetRequestExecutor(), url, null); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); wxCpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds); } } } return wxCpConfigStorage.getJsapiTicket(); }
@Override public List<WxCpUser> userList(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?department_id=" + departId; String params = ""; if (fetchChild != null) { params += "&fetch_child=" + (fetchChild ? "1" : "0"); } if (status != null) { params += "&status=" + status; } else { params += "&status=0"; } String responseContent = get(url, params); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("userlist"), new TypeToken<List<WxCpUser>>() { }.getType() ); }
@Override public List<WxCpUser> departGetUsers(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?department_id=" + departId; String params = ""; if (fetchChild != null) { params += "&fetch_child=" + (fetchChild ? "1" : "0"); } if (status != null) { params += "&status=" + status; } else { params += "&status=0"; } String responseContent = get(url, params); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("userlist"), new TypeToken<List<WxCpUser>>() { }.getType() ); }
public String getJsapiTicket(boolean forceRefresh) throws WxErrorException { if (forceRefresh) { wxMpConfigStorage.expireJsapiTicket(); } if (wxMpConfigStorage.isJsapiTicketExpired()) { synchronized (globalJsapiTicketRefreshLock) { if (wxMpConfigStorage.isJsapiTicketExpired()) { String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi"; String responseContent = execute(new SimpleGetRequestExecutor(), url, null); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); wxMpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds); } } } return wxMpConfigStorage.getJsapiTicket(); }
@Override public String getJsapiTicket(boolean forceRefresh, String mpTag) throws WxErrorException { if (forceRefresh) { wxMpConfigStorage.expireJsapiTicket(mpTag); } if (wxMpConfigStorage.isJsapiTicketExpired(mpTag)) { synchronized (globalJsapiTicketRefreshLock) { if (wxMpConfigStorage.isJsapiTicketExpired(mpTag)) { String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi"; String responseContent = null; if (StringUtils.isBlank(mpTag)){ responseContent = execute(new SimpleGetRequestExecutor(), url, null,mpTag); }else{ responseContent = execute(new SimpleGetRequestExecutor(), url, null); } JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); wxMpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds,mpTag); } } } return wxMpConfigStorage.getJsapiTicket(mpTag); }
@Override public R read(JsonReader in) throws IOException { JsonElement element = Streams.parse(in); if (element.isJsonNull()) { return readNull(); } JsonObject jsonObject = element.getAsJsonObject(); if (this.typeToken.getRawType() == Optional.class) { if (jsonObject.has(OBJECT_TYPE)) { return (R) Optional.of(readValue(jsonObject, null)); } else if (jsonObject.entrySet().isEmpty()) { return (R) Optional.absent(); } else { throw new IOException("No class found for Optional value."); } } return this.readValue(jsonObject, this.typeToken); }
public void testReadWriteTwoObjects() throws Exception { Gson gson = new Gson(); CharArrayWriter writer = new CharArrayWriter(); BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one"); writer.write(gson.toJson(expectedOne).toCharArray()); BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two"); writer.write(gson.toJson(expectedTwo).toCharArray()); CharArrayReader reader = new CharArrayReader(writer.toCharArray()); JsonReader parser = new JsonReader(reader); parser.setLenient(true); JsonElement element1 = Streams.parse(parser); JsonElement element2 = Streams.parse(parser); BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class); assertEquals("one", actualOne.stringValue); BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class); assertEquals("two", actualTwo.stringValue); }
@Override public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); try { String subclassName = baseType.getName() + "$" + label.replaceAll("\\s", ""); Class<?> subclass = Class.forName(subclassName); @SuppressWarnings("unchecked") TypeAdapter<R> delegate = (TypeAdapter<R>) gson.getDelegateAdapter( InnerClassTypeAdapterFactory.this, TypeToken.get(subclass)); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label); } return delegate.fromJsonTree(jsonElement); } catch (ClassNotFoundException e) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label); } } @Override public void write(JsonWriter out, R value) throws IOException { throw new NotImplementedException("Write not implemented for InnerClassTypeAdapter"); } }.nullSafe(); }
/** * Invokes a method from the Telegram API. * * @param method the method * @param <T> the return type * @return the object returned from the method invocation * @throws IOException when an I/O Exception occurs during the method * invocation * @throws TelegramException when the method invocation returns an error * @throws JsonParseException when the object returned is unknown */ public <T extends Serializable> T execute(TelegramMethod<T> method) throws IOException { Objects.requireNonNull(method, "method cannot be null!"); HttpPost httpPost = new HttpPost(API_URL + token + '/' + method.getName()); httpPost.setEntity(method.getHttpEntity()); try (CloseableHttpResponse response = httpClient.execute(httpPost); InputStreamReader reader = new InputStreamReader(response.getEntity().getContent()); BufferedReader bufferedReader = new BufferedReader(reader); JsonReader json = new JsonReader(bufferedReader)) { JsonElement src = Streams.parse(json); Type typeOfT = $Gson$Types.newParameterizedTypeWithOwner(null, Result.class, method.getReturnType(src)); Result<T> result = TelegramObject.gson.fromJson(src, typeOfT); if (!result.ok()) { throw result.toException(); } return result.get(); } catch (JsonParseException e) { throw new IOException(e); } }
public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException { try { toJson(src, typeOfSrc, newJsonWriter(Streams.writerForAppendable(writer))); } catch (Throwable e) { throw new JsonIOException(e); } }
public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException { try { toJson(jsonElement, newJsonWriter(Streams.writerForAppendable(writer))); } catch (IOException e) { throw new RuntimeException(e); } }