com.google.gson.JsonPrimitive Java Examples

The following examples show how to use com.google.gson.JsonPrimitive. 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: KcaBattle.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static int checkHeavyDamagedExist() {
    int status = HD_NONE;
    for (int i = 0; i < friendMaxHps.size(); i++) {
        if (!checkhdmgflag[i]) continue;
        if (friendNowHps.get(i).getAsInt() * 4 <= friendMaxHps.get(i).getAsInt()
                && !escapelist.contains(new JsonPrimitive(i + 1))) {
            if (dameconflag[i]) {
                status = Math.max(status, HD_DAMECON);
            } else {
                status = Math.max(status, HD_DANGER);
                if (status == HD_DANGER) {
                    return status;
                }
            }
        }
    }
    return status;
}
 
Example #2
Source File: PublicKeyCredentialDescriptor.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
/**
 * @return Encoded JsonObject representation of PublicKeyCredentialDescriptor
 */
public JsonObject getJsonObject() {
  JsonObject result = new JsonObject();
  result.addProperty("type", type.toString());

  result.addProperty("id", BaseEncoding.base64().encode(id));
  JsonArray transports = new JsonArray();
  if (this.transports != null) {
    for (AuthenticatorTransport t : this.transports) {
      JsonPrimitive element = new JsonPrimitive(t.toString());
      transports.add(element);
    }
    if (transports.size() > 0) {
      result.add("transports", transports);
    }
  }

  return result;
}
 
Example #3
Source File: OperationRequestGsonAdaptorRobotTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDeserialize() throws Exception {
  String operation = "{'id':'op1','method':'wavelet.setTitle','params':{" +
      "'waveId':'1','waveletId':'2','waveletTitle':'Title','unknown':'value'}}";
  JsonElement jsonElement = new JsonParser().parse(operation);

  JsonDeserializationContext mockContext = mock(JsonDeserializationContext.class);
  when(mockContext.deserialize(any(JsonElement.class), eq(String.class))).thenAnswer(
      new Answer<String>() {
        public String answer(InvocationOnMock invocation) {
          return ((JsonPrimitive) (invocation.getArguments()[0])).getAsString();
        }
      });

  OperationRequestGsonAdaptor adaptor = new OperationRequestGsonAdaptor();
  OperationRequest result = adaptor.deserialize(jsonElement, null, mockContext);
  assertEquals("op1", result.getId());
  assertEquals("wavelet.setTitle", result.getMethod());
  assertEquals("1", result.getWaveId());
  assertEquals("2", result.getWaveletId());
  assertNull(result.getBlipId());
  assertEquals(3, result.getParams().size());
  assertEquals("Title", result.getParameter(ParamsProperty.WAVELET_TITLE));
}
 
Example #4
Source File: Metrics.java    From bStats-Metrics with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, Integer> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        JsonArray categoryValues = new JsonArray();
        categoryValues.add(new JsonPrimitive(entry.getValue()));
        values.add(entry.getKey(), categoryValues);
    }
    data.add("values", values);
    return data;
}
 
Example #5
Source File: AndroidOperation.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
        description = "Test Android device lock operation for invalid device id.")
public void testLockWithInvalidDeviceId() throws Exception {
    JsonObject operationData = PayloadGenerator
            .getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
                    Constants.AndroidOperations.LOCK_OPERATION);
    JsonArray deviceIds = new JsonArray();
    JsonPrimitive deviceID = new JsonPrimitive(Constants.NUMBER_NOT_EQUAL_TO_DEVICE_ID);
    deviceIds.add(deviceID);
    operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);

    try {
        client.post(Constants.AndroidOperations.ANDROID_DEVICE_MGT_API + Constants.AndroidOperations.LOCK_ENDPOINT,
                operationData.toString());
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("HTTP response code: 400"));
    }
}
 
Example #6
Source File: VirtualChestPlaceholderManager.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String parseJavaScriptLiteral(String text, String functionIdentifier)
{
    StringBuilder builder = new StringBuilder();
    Matcher matcher = PLACEHOLDER_PATTERN.matcher(text);
    int lastIndex = 0;
    while (matcher.find())
    {
        String matched = new JsonPrimitive(text.substring(matcher.start() + 1, matcher.end() - 1)).toString();
        builder.append(text, lastIndex, matcher.start()).append(functionIdentifier);
        builder.append("(").append(matched).append(")");
        lastIndex = matcher.end();
    }
    if (lastIndex < text.length())
    {
        builder.append(text.substring(lastIndex));
    }
    return builder.toString();
}
 
Example #7
Source File: NumberValue.java    From ClientBase with MIT License 6 votes vote down vote up
@Override
public void fromJsonObject(@NotNull JsonObject obj) {
    if (obj.has(getName())) {
        JsonElement element = obj.get(getName());

        if (element instanceof JsonPrimitive && ((JsonPrimitive) element).isNumber()) {

            if (getObject() instanceof Integer) {
                setObject((T) Integer.valueOf(obj.get(getName()).getAsNumber().intValue()));
            }
            if (getObject() instanceof Long) {
                setObject((T) Long.valueOf(obj.get(getName()).getAsNumber().longValue()));
            }
            if (getObject() instanceof Float) {
                setObject((T) Float.valueOf(obj.get(getName()).getAsNumber().floatValue()));
            }
            if (getObject() instanceof Double) {
                setObject((T) Double.valueOf(obj.get(getName()).getAsNumber().doubleValue()));
            }
        } else {
            throw new IllegalArgumentException("Entry '" + getName() + "' is not valid");
        }
    } else {
        throw new IllegalArgumentException("Object does not have '" + getName() + "'");
    }
}
 
Example #8
Source File: ReplicatorDocument.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
private String getEndpointUrl(JsonElement element) {
    if (element == null) {
        return null;
    }
    JsonPrimitive urlString = null;
    if (element.isJsonPrimitive()) {
        urlString = element.getAsJsonPrimitive();
    } else {
        JsonObject replicatorEndpointObject = element.getAsJsonObject();
        urlString = replicatorEndpointObject.getAsJsonPrimitive("url");
    }
    if (urlString == null) {
        return null;
    }
    return urlString.getAsString();
}
 
Example #9
Source File: main.java    From graphify with Apache License 2.0 6 votes vote down vote up
private static void trainOnText(String[] text, String[] label) {
    List<String> labelSet = new ArrayList<>();
    List<String> textSet = new ArrayList<>();

    Collections.addAll(labelSet, label);
    Collections.addAll(textSet, text);

    JsonArray labelArray = new JsonArray();
    JsonArray textArray = new JsonArray();

    labelSet.forEach((s) -> labelArray.add(new JsonPrimitive(s)));
    textSet.forEach((s) -> textArray.add(new JsonPrimitive(s)));

    JsonObject jsonParam = new JsonObject();
    jsonParam.add("text", textArray);
    jsonParam.add("label", labelArray);
    jsonParam.add("focus", new JsonPrimitive(2));

    String jsonPayload = new Gson().toJson(jsonParam);

    System.out.println(executePost("http://localhost:7474/service/graphify/training", jsonPayload));
}
 
Example #10
Source File: Metrics2.java    From bStats-Metrics with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, Integer> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        JsonArray categoryValues = new JsonArray();
        categoryValues.add(new JsonPrimitive(entry.getValue()));
        values.add(entry.getKey(), categoryValues);
    }
    data.add("values", values);
    return data;
}
 
Example #11
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToConvertACommand() {
  SessionId sessionId = new SessionId("some id");
  String commandName = "some command";
  Map<String, Object> parameters = new HashMap<>();
  parameters.put("param1", "value1");
  parameters.put("param2", "value2");
  Command command = new Command(sessionId, commandName, parameters);

  String json = convert(command);

  JsonObject converted = new JsonParser().parse(json).getAsJsonObject();

  assertThat(converted.has("sessionId")).isTrue();
  JsonPrimitive sid = converted.get("sessionId").getAsJsonPrimitive();
  assertThat(sid.getAsString()).isEqualTo(sessionId.toString());

  assertThat(commandName).isEqualTo(converted.get("name").getAsString());

  assertThat(converted.has("parameters")).isTrue();
  JsonObject pars = converted.get("parameters").getAsJsonObject();
  assertThat(pars.entrySet()).hasSize(2);
  assertThat(pars.get("param1").getAsString()).isEqualTo(parameters.get("param1"));
  assertThat(pars.get("param2").getAsString()).isEqualTo(parameters.get("param2"));
}
 
Example #12
Source File: JsonAdapterAnnotationOnClassesTest.java    From gson with Apache License 2.0 6 votes vote down vote up
/**
 * The serializer overrides field adapter, but for deserializer the fieldAdapter is used.
 */
public void testRegisteredSerializerOverridesJsonAdapter() {
  JsonSerializer<A> serializer = new JsonSerializer<A>() {
    public JsonElement serialize(A src, Type typeOfSrc,
        JsonSerializationContext context) {
      return new JsonPrimitive("registeredSerializer");
    }
  };
  Gson gson = new GsonBuilder()
    .registerTypeAdapter(A.class, serializer)
    .create();
  String json = gson.toJson(new A("abcd"));
  assertEquals("\"registeredSerializer\"", json);
  A target = gson.fromJson("abcd", A.class);
  assertEquals("jsonAdapter", target.value);
}
 
Example #13
Source File: AndroidOperation.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
        description = "Test Android encrypt operation for invalid device id")
public void testEncryptWithInvalidDeviceId() throws Exception {
    JsonObject operationData = PayloadGenerator
            .getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
                    Constants.AndroidOperations.ENCRYPT_OPERATION);
    JsonArray deviceIds = new JsonArray();
    JsonPrimitive deviceID = new JsonPrimitive(Constants.NUMBER_NOT_EQUAL_TO_DEVICE_ID);
    deviceIds.add(deviceID);
    operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);
    try {
        client.post(
                Constants.AndroidOperations.ANDROID_DEVICE_MGT_API + Constants.AndroidOperations.ENCRYPT_ENDPOINT,
                operationData.toString());
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("HTTP response code: 400"));
    }
}
 
Example #14
Source File: AbstractPluginMessagingForwardingSink.java    From NuVotifier with GNU General Public License v3.0 6 votes vote down vote up
public void handlePluginMessage(byte[] message) {
    String strMessage = new String(message, StandardCharsets.UTF_8);
    try (CharArrayReader reader = new CharArrayReader(strMessage.toCharArray())) {
        JsonReader r = new JsonReader(reader);
        r.setLenient(true);
        while (r.peek() != JsonToken.END_DOCUMENT) {
            r.beginObject();
            JsonObject o = new JsonObject();

            while (r.hasNext()) {
                String name = r.nextName();
                if (r.peek() == JsonToken.NUMBER)
                    o.add(name, new JsonPrimitive(r.nextLong()));
                else
                    o.add(name, new JsonPrimitive(r.nextString()));
            }
            r.endObject();

            Vote v = new Vote(o);
            listener.onForward(v);
        }
    } catch (IOException e) {
        e.printStackTrace(); // Should never happen.
    }
}
 
Example #15
Source File: GsonTypeSerializer.java    From helper with MIT License 6 votes vote down vote up
@Override
public void serialize(TypeToken<?> type, JsonElement from, ConfigurationNode to) throws ObjectMappingException {
    if (from.isJsonPrimitive()) {
        JsonPrimitive primitive = from.getAsJsonPrimitive();
        to.setValue(GsonConverters.IMMUTABLE.unwarpPrimitive(primitive));
    } else if (from.isJsonNull()) {
        to.setValue(null);
    } else if (from.isJsonArray()) {
        JsonArray array = from.getAsJsonArray();
        // ensure 'to' is a list node
        to.setValue(ImmutableList.of());
        for (JsonElement element : array) {
            serialize(TYPE, element, to.getAppendedNode());
        }
    } else if (from.isJsonObject()) {
        JsonObject object = from.getAsJsonObject();
        // ensure 'to' is a map node
        to.setValue(ImmutableMap.of());
        for (Map.Entry<String, JsonElement> ent : object.entrySet()) {
            serialize(TYPE, ent.getValue(), to.getNode(ent.getKey()));
        }
    } else {
        throw new ObjectMappingException("Unknown element type: " + from.getClass());
    }
}
 
Example #16
Source File: JsonUtils.java    From StatsAgg with Apache License 2.0 6 votes vote down vote up
public static String getStringFieldFromJsonObject(JsonObject jsonObject, String fieldName) {
    
    if (jsonObject == null) {
        return null;
    }
    
    String returnString = null;
    
    try {
        JsonElement jsonElement = jsonObject.get(fieldName);
        
        if (jsonElement != null) {
            JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
            returnString = jsonPrimitive.getAsString();
        }
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));    
    }

    return returnString;
}
 
Example #17
Source File: SteamStorefront.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
public CompletableFuture<StoreAppDetails> getAppDetails(int appId, String countryCode, String language) {
    CompletableFuture<JsonObject> json = sendRequest(new GetAppDetails(VERSION_1, appId, countryCode, language));
    return json.thenApply(root -> {
        JsonObject appObject = root.getAsJsonObject(String.valueOf(appId));
        JsonPrimitive success = appObject.getAsJsonPrimitive("success");
        if (success != null && success.getAsBoolean()) {
            JsonObject appData = appObject.getAsJsonObject("data");
            return fromJson(appData, StoreAppDetails.class);
        }
        return null;
    });
}
 
Example #18
Source File: FileTest.java    From salt-netapi-client with MIT License 5 votes vote down vote up
@Test
public final void testCopy() {
    stubFor(any(urlMatching("/"))
            .willReturn(aResponse()
            .withStatus(HttpURLConnection.HTTP_OK)
            .withHeader("Content-Type", "application/json")
            .withBody(JSON_TRUE_RESPONSE)));

    LocalCall<Boolean> call = File.copy("/test1", "/test2", false, false);
    assertEquals("file.copy", call.getPayload().get("fun"));

    Map<String, Result<Boolean>> response = call.callSync(client,
            new MinionList("minion1"), AUTH).toCompletableFuture().join();
    assertTrue(response.get("minion1").result().get());

    stubFor(any(urlMatching("/"))
            .willReturn(aResponse()
            .withStatus(HttpURLConnection.HTTP_OK)
            .withHeader("Content-Type", "application/json")
            .withBody(JSON_COPY_EXCEPTION_RESPONSE)));

    response = call.callSync(client, new MinionList("minion1"), AUTH).toCompletableFuture().join();
    String errorMessage = "ERROR: Could not copy /test1 to /test2";
    assertEquals(new JsonPrimitive(errorMessage),
            ((JsonParsingError) response.get("minion1").error().get()).getJson());

}
 
Example #19
Source File: InstantTypeAdapter.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Instant deserialize ( final JsonElement json, final Type typeOfT, final JsonDeserializationContext context ) throws JsonParseException
{
    if ( ! ( json instanceof JsonPrimitive ) )
    {
        throw new JsonParseException ( "Timestamps should be encoded as JSON strings" );
    }

    return Instant.from ( this.formatter.parse ( json.getAsString () ) );
}
 
Example #20
Source File: PlacementInfo.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
private static JsonArray setToArray(Set<String> set) {
    JsonArray array = new JsonArray();
    for (String item : set)
        if (!item.isEmpty())
            array.add(new JsonPrimitive(item));
    return array;      
}
 
Example #21
Source File: JiraVelocityActionHandlerTest.java    From benten with MIT License 5 votes vote down vote up
@Test
public void testHandleRequest(){
    BentenMessage bentenMessage;

    JsonElement boardName = new JsonPrimitive("Combined_Services_Team_view");
    JsonElement noOfSprints = new JsonPrimitive("1");

    bentenMessage =
            MessageBuilder.constructBentenSprintMessage(boardName,noOfSprints);
    BentenHandlerResponse bentenHandlerResponse =
            jiraSprintVelocityActionHandler.handle(bentenMessage);

    Assert.assertNotNull(bentenHandlerResponse.getBentenHtmlResponse());
}
 
Example #22
Source File: CustomTypeAdaptersTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testCustomNestedSerializers() {
  Gson gson = new GsonBuilder().registerTypeAdapter(
      BagOfPrimitives.class, new JsonSerializer<BagOfPrimitives>() {
        @Override public JsonElement serialize(BagOfPrimitives src, Type typeOfSrc,
        JsonSerializationContext context) {
      return new JsonPrimitive(6);
    }
  }).create();
  ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
  assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target));
}
 
Example #23
Source File: GeoSource.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Query
public Place getPlace(@Key("text") String text) throws InterruptedException, ExecutionException, TimeoutException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q", "select * from geo.places where text='" + text + "'");
    JsonPrimitive jsonObj = jsonObject.getAsJsonObject("query").getAsJsonObject("results").getAsJsonObject("place")
            .getAsJsonPrimitive("woeid");
    return new Place(text, jsonObj.getAsString());
}
 
Example #24
Source File: NumberRangeQueryBuilderTest.java    From flummi with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddGteAndLtFieldToQuery() throws Exception {
    // given
    // when
    NumberRangeQueryBuilder rangeQueryBuilder = new NumberRangeQueryBuilder("someField").gte(100).lt(200);
    //then
    JsonObject fieldObject = new JsonObject();
    fieldObject.add("gte", new JsonPrimitive(100));
    fieldObject.add("lt", new JsonPrimitive(200));
    assertThat(rangeQueryBuilder.build(), is(object("range", object("someField", fieldObject))));
}
 
Example #25
Source File: BoolQueryBuilderTest.java    From flummi with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBuildMustNotBoolQuery() throws Exception {
    // given

    // when
    testee.mustNot(new TermQueryBuilder("someName", new JsonPrimitive("someValue")).build());

    //then
    assertThat(testee.build(), is(
            object("bool",
                    object("must_not",
                            object("term",
                                    object("someName", "someValue"))))));
}
 
Example #26
Source File: EnumAdapter.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
/**
 * Method deserialize.
 * @param json JsonElement
 * @param typeOfT Type
 * @param context JsonDeserializationContext
 * @return E
 * @throws JsonParseException
 * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)
 */
public E deserialize(
  JsonElement json, 
  Type typeOfT,
  JsonDeserializationContext context) 
    throws JsonParseException {
  checkArgument(json.isJsonPrimitive());
  JsonPrimitive jp = json.getAsJsonPrimitive();
  checkArgument(jp.isString());
  return des.convert(jp.getAsString());
}
 
Example #27
Source File: MetricsHandlerTest.java    From vi with Apache License 2.0 5 votes vote down vote up
public Map<String,Object>loadParasFromJsonString(String str,boolean isPrimitive){
    Map<String,Object> params =null;

    Gson gson = new Gson();
    Type paraMap;
    if(isPrimitive){
        paraMap= new TypeToken<Map<String, JsonPrimitive>>(){}.getType();
    }else{

        paraMap= new TypeToken<Map<String, JsonArray>>(){}.getType();
    }
    params = gson.fromJson(str,paraMap);
    return params;
}
 
Example #28
Source File: Config.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
private JsonElement serialize(Object value, JsonSerializationContext context) {
  if (value instanceof ImmutableSet) {
    JsonArray array = new JsonArray();
    for (Object element : ((ImmutableSet<?>) value)) {
      array.add(serialize(element, context));
    }
    return array;
  } else if (value instanceof Path || value instanceof Pattern) {
    return new JsonPrimitive(value.toString());
  }
  return context.serialize(value);
}
 
Example #29
Source File: MobileServiceTableBase.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the JsonObject to have an id property
 *
 * @param json the element to evaluate
 */
protected void updateIdProperty(final JsonObject json) throws IllegalArgumentException {
    for (Entry<String, JsonElement> entry : json.entrySet()) {
        String key = entry.getKey();

        if (key.equalsIgnoreCase("id")) {
            JsonElement element = entry.getValue();

            if (isValidTypeId(element)) {
                if (!key.equals("id")) {
                    // force the id name to 'id', no matter the casing
                    json.remove(key);
                    // Create a new id property using the given property
                    // name

                    JsonPrimitive value = entry.getValue().getAsJsonPrimitive();
                    if (value.isNumber()) {
                        json.addProperty("id", value.getAsLong());
                    } else {
                        json.addProperty("id", value.getAsString());
                    }
                }

                return;
            } else {
                throw new IllegalArgumentException("The id must be numeric or string");
            }
        }
    }
}
 
Example #30
Source File: RedditObjectDeserializer.java    From redgram-for-reddit with GNU General Public License v3.0 5 votes vote down vote up
private void modifyUserListChildren(JsonArray children) {
    for(int i = 0 ; i < children.size() ; i++){
        JsonElement child = children.get(i);
        if(child.isJsonObject()){
            JsonObject obj = new JsonObject();
            obj.add(KIND, new JsonPrimitive(RedditType.User.toString()));
            obj.add(DATA, child);
            children.set(i, obj);
        }
    }
}