List of usage examples for com.google.gson JsonElement getAsString
public String getAsString()
From source file:com.google.security.wycheproof.JsonUtil.java
License:Apache License
/** * Converts a JsonElement into a byte array. * @param element a JsonElement containing an encoded byte array. * Wycheproof represents byte arrays as hexadeciamal strings. * @throws ClassCastException if element is not a valid string value. * @throws IllegalStateException - if element contains an array. *//* w w w.j a v a 2 s. c o m*/ public static byte[] asByteArray(JsonElement element) { String hex = element.getAsString(); return TestUtil.hexToBytes(hex); }
From source file:com.google.security.wycheproof.JsonUtil.java
License:Apache License
/** * Converts a JsonElement into a BigInteger. * @param element a JsonElement containing a BigInteger. * Wycheproof represents BigIntegers as hexadecimal strings using * twos complement representation.//from ww w . ja va 2 s . c o m * <p> E.g., 31 is represented as "1f", -1 is represented as "f", and * 255 is represented as "0ff". * @throws ClassCastException if element is not a valid string value. * @throws IllegalStateException if element contains an array. * @throws NumberFormatException if representation of the BigInteger is invalid. */ public static BigInteger asBigInteger(JsonElement element) { String hex = element.getAsString(); // TODO(bleichen): Consider to change the representation of BigIntegers in // Wycheproof as hexadecimal string with a sign. if (hex.length() % 2 == 1) { if (hex.charAt(0) >= '0' && hex.charAt(0) <= '7') { hex = "0" + hex; } else { hex = "f" + hex; } } return new BigInteger(TestUtil.hexToBytes(hex)); }
From source file:com.google.wave.api.event.EventSerializer.java
License:Apache License
/** * Deserializes the given {@link JsonObject} into an {@link Event}, and * assign the given {@link Wavelet} to the {@link Event}. * * @param wavelet the wavelet where the event occurred. * @param json the JSON representation of {@link Event}. * @param context the deserialization context. * @return an instance of {@link Event}. * * @throw {@link EventSerializationException} if there is a problem * deserializing the event JSON.// w ww . j av a2 s .co m */ public static Event deserialize(Wavelet wavelet, EventMessageBundle bundle, JsonObject json, JsonDeserializationContext context) throws EventSerializationException { // Construct the event object. String eventTypeString = json.get(TYPE).getAsString(); EventType type = EventType.valueOfIgnoreCase(eventTypeString); if (type == EventType.UNKNOWN) { throw new EventSerializationException( "Trying to deserialize event JSON with unknown " + "type: " + json, json); } // Parse the generic parameters. String modifiedBy = json.get(MODIFIED_BY).getAsString(); Long timestamp = json.get(TIMESTAMP).getAsLong(); // Construct the event object. Class<? extends Event> clazz = type.getClazz(); Constructor<? extends Event> ctor; try { ctor = clazz.getDeclaredConstructor(); ctor.setAccessible(true); Event event = ctor.newInstance(); // Set the default fields from AbstractEvent. Class<?> rootClass = AbstractEvent.class; setField(event, rootClass.getDeclaredField(WAVELET), wavelet); setField(event, rootClass.getDeclaredField(MODIFIED_BY), modifiedBy); setField(event, rootClass.getDeclaredField(TIMESTAMP), timestamp); setField(event, rootClass.getDeclaredField(TYPE), type); setField(event, rootClass.getDeclaredField(BUNDLE), bundle); JsonObject properties = json.get(PROPERTIES).getAsJsonObject(); // Set the blip id field, that can be null for certain events, such as // OPERATION_ERROR. JsonElement blipId = properties.get(BLIP_ID); if (blipId != null && !(blipId instanceof JsonNull)) { setField(event, rootClass.getDeclaredField(BLIP_ID), blipId.getAsString()); } // Set the additional fields. for (Field field : clazz.getDeclaredFields()) { String fieldName = field.getName(); if (properties.has(fieldName)) { setField(event, field, context.deserialize(properties.get(fieldName), field.getGenericType())); } } return event; } catch (NoSuchMethodException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (NoSuchFieldException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (InstantiationException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (IllegalAccessException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (InvocationTargetException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (JsonParseException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } }
From source file:com.google.wave.api.impl.OperationRequestGsonAdaptor.java
License:Apache License
/** * Returns a property of {@code JsonObject} as a {@link String}, then remove * that property./* ww w . j a v a 2 s .co m*/ * * @param jsonObject the {@code JsonObject} to get the property from. * @param key the key of the property. * @return the property as {@link String}, or {@code null} if not found. */ private static String getPropertyAsStringThenRemove(JsonObject jsonObject, ParamsProperty key) { JsonElement property = jsonObject.get(key.key()); if (property != null) { jsonObject.remove(key.key()); if (property.isJsonNull()) { return null; } return property.getAsString(); } return null; }
From source file:com.google.wave.api.RobotSerializer.java
License:Apache License
/** * Determines the protocol version of a given operation bundle JSON by * inspecting the first operation in the bundle. If it is a * {@code robot.notify} operation, and contains {@code protocolVersion} * parameter, then this method will return the value of that parameter. * Otherwise, this method will return the default version. * * @param operationBundle the operation bundle to check. * @return the wire protocol version of the given operation bundle. *//*from w w w. ja va2 s . c o m*/ private ProtocolVersion determineProtocolVersion(JsonArray operationBundle) { if (operationBundle.size() == 0 || !operationBundle.get(0).isJsonObject()) { return defaultProtocolVersion; } JsonObject firstOperation = operationBundle.get(0).getAsJsonObject(); if (!firstOperation.has(RequestProperty.METHOD.key())) { return defaultProtocolVersion; } String method = firstOperation.get(RequestProperty.METHOD.key()).getAsString(); if (isRobotNotifyOperationMethod(method)) { JsonObject params = firstOperation.get(RequestProperty.PARAMS.key()).getAsJsonObject(); if (params.has(ParamsProperty.PROTOCOL_VERSION.key())) { JsonElement protocolVersionElement = params.get(ParamsProperty.PROTOCOL_VERSION.key()); if (!protocolVersionElement.isJsonNull()) { return ProtocolVersion.fromVersionString(protocolVersionElement.getAsString()); } } } return defaultProtocolVersion; }
From source file:com.google.wave.splash.data.serialize.JsonSerializer.java
License:Apache License
/** * Parses a string of json from a wave.robot.fetchWave into a result. * * @param json the json to parse./*w w w. ja va2 s . c o m*/ * @return the result object, which may not contain a wavelet. */ @Timed public FetchWaveletResult parseFetchWaveletResult(String json) { JsonObject dataObject = getDataObject(json); if (dataObject == null || !dataObject.has("waveletData")) { LOG.warning("Fetch returned empty result."); return FetchWaveletResult.emptyResult(); } JsonObject waveletDataJson = dataObject.getAsJsonObject("waveletData"); OperationQueue operationQueue = new OperationQueue(); WaveletData waveletData = gson.fromJson(waveletDataJson, WaveletData.class); Map<String, Blip> blips = Maps.newHashMap(); HashMap<String, BlipThread> threads = Maps.newHashMap(); Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData); JsonObject threadMap = dataObject.getAsJsonObject("threads"); if (null != threadMap) { for (Map.Entry<String, JsonElement> entries : threadMap.entrySet()) { JsonObject threadElement = entries.getValue().getAsJsonObject(); int location = threadElement.get("location").getAsInt(); List<String> blipIds = Lists.newArrayList(); for (JsonElement blipId : threadElement.get("blipIds").getAsJsonArray()) { blipIds.add(blipId.getAsString()); } BlipThread thread = new BlipThread(entries.getKey(), location, blipIds, blips); threads.put(thread.getId(), thread); } } JsonObject blipMap = dataObject.getAsJsonObject("blips"); for (Map.Entry<String, JsonElement> entries : blipMap.entrySet()) { BlipData blipData = gson.fromJson(entries.getValue(), BlipData.class); Blip blip = Blip.deserialize(operationQueue, wavelet, blipData); blips.put(blipData.getBlipId(), blip); } return new FetchWaveletResult(wavelet); }
From source file:com.googleapis.ajax.services.impl.BaseGoogleSearchApiQuery.java
License:Apache License
/** * Gets the gson builder.//from w ww. jav a 2 s. c om * * @return the gson builder */ protected GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat(ApplicationConstants.RFC822DATEFORMAT); builder.registerTypeAdapter(ListingType.class, new JsonDeserializer<ListingType>() { @Override public ListingType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return ListingType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(PatentStatus.class, new JsonDeserializer<PatentStatus>() { @Override public PatentStatus deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return PatentStatus.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(VideoType.class, new JsonDeserializer<VideoType>() { @Override public VideoType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return VideoType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(ViewPortMode.class, new JsonDeserializer<ViewPortMode>() { @Override public ViewPortMode deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return ViewPortMode.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(GsearchResultClass.class, new JsonDeserializer<GsearchResultClass>() { @Override public GsearchResultClass deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return GsearchResultClass.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(PhoneNumberType.class, new JsonDeserializer<PhoneNumberType>() { @Override public PhoneNumberType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return PhoneNumberType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(Language.class, new JsonDeserializer<Language>() { @Override public Language deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return Language.fromValue(arg0.getAsString()); } }); return builder; }
From source file:com.googleapis.maps.services.impl.BaseGoogleMapsApiQuery.java
License:Apache License
/** * Gets the gson builder.//from w ww. j av a 2s. c om * * @return the gson builder */ protected GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat(ApplicationConstants.RFC822DATEFORMAT); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); builder.registerTypeAdapter(LocationType.class, new JsonDeserializer<LocationType>() { @Override public LocationType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return LocationType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(AddressComponentType.class, new JsonDeserializer<AddressComponentType>() { @Override public AddressComponentType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return AddressComponentType.fromValue(arg0.getAsString()); } }); // builder.registerTypeAdapter(TravelMode.class, new JsonDeserializer<TravelMode>() { // @Override // public TravelMode deserialize(JsonElement arg0, Type arg1, // JsonDeserializationContext arg2) throws JsonParseException { // return TravelMode.fromValue(arg0.getAsString()); // } // }); return builder; }
From source file:com.googlesource.gerrit.plugins.events.BranchHelper.java
License:Apache License
protected static String asString(JsonElement el) { if (el != null) { try {// w w w . ja v a 2s . com return el.getAsString(); } catch (RuntimeException e) { } } return null; }
From source file:com.googlesource.gerrit.plugins.oauth.AirVantageOAuthService.java
License:Apache License
@Override public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException { OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); Token t = new Token(token.getToken(), token.getSecret(), token.getRaw()); service.signRequest(t, request);//w ww . ja v a2s . c om Response response = request.send(); if (response.getCode() != SC_OK) { throw new IOException(String.format("Status %s (%s) for request %s", response.getCode(), response.getBody(), request.getUrl())); } JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class); if (log.isDebugEnabled()) { log.debug("User info response: {}", response.getBody()); } if (userJson.isJsonObject()) { JsonObject jsonObject = userJson.getAsJsonObject(); JsonElement id = jsonObject.get("uid"); if (id == null || id.isJsonNull()) { throw new IOException("Response doesn't contain uid field"); } JsonElement email = jsonObject.get("email"); JsonElement name = jsonObject.get("name"); return new OAuthUserInfo(AV_PROVIDER_PREFIX + id.getAsString(), null, email.getAsString(), name.getAsString(), id.getAsString()); } throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson)); }