Java Code Examples for com.google.gson.JsonObject#addProperty()

The following examples show how to use com.google.gson.JsonObject#addProperty() . 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: Starling.java    From jarling with MIT License 8 votes vote down vote up
@Override
public Payment makeLocalPayment(String destinationAccountUid, String reference, BigDecimal amount) throws StarlingBankRequestException {
    JsonObject localPayment = new JsonObject();
    JsonObject paymentDetail = new JsonObject();

    localPayment.addProperty("destinationAccountUid", destinationAccountUid);
    localPayment.addProperty("reference", reference);
    localPayment.add("payment", paymentDetail);

    paymentDetail.addProperty("amount", amount);
    paymentDetail.addProperty("currency", "GBP");

    HttpResponse makePaymentResponse = apiService.post("/payments/local", null, null, localPayment.toString());
    final String paymentId = apiService.getLocationHeader(makePaymentResponse).replace("/payments/local/", "");

    return listPayments().stream().filter(payment -> payment.getPaymentOrderId().equals(paymentId)).findFirst().orElse(null);
}
 
Example 2
Source File: AgentStatusReportRequestTest.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 7 votes vote down vote up
@Test
public void shouldDeserializeFromJSONWithClusterProfile() {
    JsonObject jobIdentifierJson = JobIdentifierMother.getJson();
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("elastic_agent_id", "some-id");
    jsonObject.add("job_identifier", jobIdentifierJson);
    JsonObject clusterJSON = new JsonObject();
    clusterJSON.addProperty("go_server_url", "https://foo.com/go");
    clusterJSON.addProperty("docker_uri", "unix:///var/run/docker.sock");
    jsonObject.add("cluster_profile_properties", clusterJSON);

    AgentStatusReportRequest agentStatusReportRequest = AgentStatusReportRequest.fromJSON(jsonObject.toString());

    Map<String, String> expectedClusterProfile = new HashMap<>();
    expectedClusterProfile.put("go_server_url", "https://foo.com/go");
    expectedClusterProfile.put("docker_uri", "unix:///var/run/docker.sock");

    AgentStatusReportRequest expected = new AgentStatusReportRequest("some-id", JobIdentifierMother.get(), expectedClusterProfile);
    assertThat(agentStatusReportRequest, is(expected));
}
 
Example 3
Source File: ImageArchiveManifestEntryAdapterTest.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createFromValidJsonObject() {
    JsonObject entryJson = new JsonObject();
    entryJson.addProperty(ImageArchiveManifestEntryAdapter.CONFIG, "image-id-sha256.json");

    JsonArray repoTagsJson = new JsonArray();
    repoTagsJson.add("test/image:latest");
    entryJson.add(ImageArchiveManifestEntryAdapter.REPO_TAGS, repoTagsJson);

    JsonArray layersJson = new JsonArray();
    layersJson.add("layer-id-sha256/layer.tar");
    entryJson.add(ImageArchiveManifestEntryAdapter.LAYERS, layersJson);

    ImageArchiveManifestEntryAdapter entry = new ImageArchiveManifestEntryAdapter(entryJson);

    Assert.assertNotNull(entry);
    Assert.assertEquals("image-id-sha256.json", entry.getConfig());
    Assert.assertEquals("image-id-sha256", entry.getId());
    Assert.assertNotNull(entry.getRepoTags());
    Assert.assertEquals(Collections.singletonList("test/image:latest"), entry.getRepoTags());
    Assert.assertNotNull(entry.getLayers());
    Assert.assertEquals(Collections.singletonList("layer-id-sha256/layer.tar"), entry.getLayers());
}
 
Example 4
Source File: Room.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public void sendParticipantNames(RoomParticipant user) {

    checkClosed();

    log.debug("PARTICIPANT {}: sending a list of participants", user.getName());

    final JsonArray participantsArray = new JsonArray();
    for (final RoomParticipant participant : this.getParticipants()) {
      log.debug("PARTICIPANT {}: visiting participant", user.getName(), participant.getName());
      if (!participant.equals(user)) {
        final JsonElement participantName = new JsonPrimitive(participant.getName());
        participantsArray.add(participantName);
      }
    }

    final JsonObject existingParticipantsMsg = new JsonObject();
    existingParticipantsMsg.addProperty("id", "existingParticipants");
    existingParticipantsMsg.add("data", participantsArray);
    log.debug("PARTICIPANT {}: sending a list of {} participants", user.getName(),
        participantsArray.size());
    user.sendMessage(existingParticipantsMsg);
  }
 
Example 5
Source File: SubmissionParameterFactory.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
public static JsonObject asJSON(SubmissionParameter<?> param) {
    // meet the requirements of BOperatorInvocation.setParameter()
    // and OperatorGenerator.parameterValue()
    /*
     * The SubmissionParameter parameter value json is: 
     * <pre><code>
     * object {
     *   type : "submissionParameter"
     *   value : object {
     *     name : string. submission parameter name
     *     metaType : operator.Type.MetaType.name() string
     *     defaultValue : any. may be null. type appropriate for metaType.
     *   }
     * }
     * </code></pre>
     */
    JsonObject jo = new JsonObject();
    JsonObject jv = new JsonObject();
    jo.addProperty("type", TYPE_SUBMISSION_PARAMETER);
    jo.add("value", jv);
    jv.addProperty("name", param.getName());
    jv.addProperty("metaType", param.getMetaType());
    if (param.getDefaultValue() != null)
        GsonUtilities.addToObject(jv, "defaultValue", param.getDefaultValue());
    return jo;
}
 
Example 6
Source File: VerigreenNeededLogic.java    From verigreen with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns Json Object or fields params in hash map based on Jenkins Mode
 * 
 * @param commitItem
 * @return
 * @throws JSONException
 */
public static Map<String, String> checkJenkinsMode(CommitItem commitItem) {	
	
	Map<String, String> resultMap = new HashMap<>();
	Map<String, String> paramMap = commitItemAsParameterMap(commitItem);

	if(jenkinsParams.get("jenkinsparam.mode") != null && jenkinsParams.get("jenkinsparam.mode").equals("json")){
		JsonObject json = new JsonObject();
		for(String key : paramMap.keySet()){
			json.addProperty(key, paramMap.get(key));
		}
		resultMap.put("json",json.toString());
	}
	else {
		return paramMap;
	}
	return resultMap;
}
 
Example 7
Source File: ReflexDB.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static JsonObject convertZz(ReflexMatchZigbeeIasZoneStatus zz, JsonSerializationContext context) {
   try {
      JsonObject json = new JsonObject();
      json.addProperty("t", "ZZ");
      json.addProperty("r", zz.getType().name());
      json.addProperty("p", zz.getProfile());
      json.addProperty("e", zz.getEndpoint());
      json.addProperty("c", zz.getCluster());
      json.addProperty("s", zz.getSetMask());
      json.addProperty("u", zz.getClrMask());
      json.addProperty("m", zz.getMaxChangeDelay());

      return json;
   } catch (Exception ex) {
      throw new RuntimeException(ex);
   }
}
 
Example 8
Source File: BsonDecimal128Test.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Test
public void write() throws Exception {
  JsonObject obj = new JsonObject();
  BigInteger bigInteger = new BigInteger(Long.toString(Long.MAX_VALUE)).multiply(new BigInteger("128"));
  obj.addProperty("bigInteger", bigInteger);

  BigDecimal bigDecimal = new BigDecimal(Long.MAX_VALUE).multiply(new BigDecimal(1024));
  obj.addProperty("bigDecimal", bigDecimal);

  BsonDocument doc = Jsons.toBson(obj);

  check(doc.get("bigInteger").getBsonType()).is(BsonType.DECIMAL128);
  check(doc.get("bigInteger").asDecimal128().decimal128Value().bigDecimalValue().toBigInteger()).is(bigInteger);

  check(doc.get("bigDecimal").getBsonType()).is(BsonType.DECIMAL128);
  check(doc.get("bigDecimal").asDecimal128().decimal128Value().bigDecimalValue()).is(bigDecimal);
}
 
Example 9
Source File: MessageClientTest.java    From jmessage-api-java-client with MIT License 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testSendMessage_FromTypeNull() {
	MessageBody messageBody = MessageBody.newBuilder()
            .setText("Test api send Message")
            .build();

    JsonObject bodyObj = new JsonObject();
    bodyObj.addProperty("text", "Test api send Message");

    assertEquals(bodyObj, messageBody.toJSON());

    MessagePayload payload = MessagePayload.newBuilder()
            .setVersion(1)
            .setTargetType("single")
            .setTargetId(JUNIT_USER)
            .setFromId("junit_admin")
            .setMessageType(MessageType.TEXT)
            .setMessageBody(messageBody)
            .build();
}
 
Example 10
Source File: SessionTpidBindHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    BindRequest bindReq = new BindRequest();
    bindReq.setSid(getQueryParameter(exchange, BindRequest.Keys.SessionID));
    bindReq.setSecret(getQueryParameter(exchange, BindRequest.Keys.Secret));
    bindReq.setUserId(getQueryParameter(exchange, BindRequest.Keys.UserID));

    String reqContentType = getContentType(exchange).orElse("application/octet-stream");
    if (StringUtils.equals("application/x-www-form-urlencoded", reqContentType)) {
        String body = getBodyUtf8(exchange);
        Map<String, Deque<String>> parms = QueryParameterUtils.parseQueryString(body, StandardCharsets.UTF_8.name());
        bindReq.setSid(getQueryParameter(parms, BindRequest.Keys.SessionID));
        bindReq.setSecret(getQueryParameter(parms, BindRequest.Keys.Secret));
        bindReq.setUserId(getQueryParameter(parms, BindRequest.Keys.UserID));
    } else if (StringUtils.equals("application/json", reqContentType)) {
        bindReq = parseJsonTo(exchange, BindRequest.class);
    } else {
        log.warn("Unknown encoding in 3PID session bind: {}", reqContentType);
        log.warn("The request will most likely fail");
    }

    try {
        SingleLookupReply lookup = mgr.bind(bindReq.getSid(), bindReq.getSecret(), bindReq.getUserId());
        JsonObject response = signMgr.signMessageGson(GsonUtil.makeObj(new SingeLookupReplyJson(lookup)));
        respond(exchange, response);
    } catch (BadRequestException e) {
        log.info("requested session was not validated");

        JsonObject obj = new JsonObject();
        obj.addProperty("errcode", "M_SESSION_NOT_VALIDATED");
        obj.addProperty("error", e.getMessage());
        respond(exchange, HttpStatus.SC_BAD_REQUEST, obj);
    } finally {
        // If a user registers, there is no standard login event. Instead, this is the only way to trigger
        // resolution at an appropriate time. Meh at synapse/Riot!
        invMgr.lookupMappingsForInvites();
    }
}
 
Example 11
Source File: BitcoinNodeManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private static JsonObject getMainJsonParam(String method) {
    JsonObject json = new JsonObject();
    json.addProperty("jsonrpc", "2.0");
    json.addProperty("method", method);
    json.addProperty("id", 1);

    return json;
}
 
Example 12
Source File: AgentProfileTest.java    From jxapi with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	agent = new Agent(NAME, MBOX);
	agentProfile = new AgentProfile(agent, PROFILE_ID);
	JsonObject p = new JsonObject();
	p.addProperty("AgentProfile", "Unit Test");
	agentProfile.setProfile(p);
}
 
Example 13
Source File: VmService.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * The [addBreakpoint] RPC is used to add a breakpoint at a specific line of some script. This
 * RPC is useful when a script has not yet been assigned an id, for example, if a script is in a
 * deferred library which has not yet been loaded.
 * @param column This parameter is optional and may be null.
 */
public void addBreakpointWithScriptUri(String isolateId, String scriptUri, int line, Integer column, BreakpointConsumer consumer) {
  final JsonObject params = new JsonObject();
  params.addProperty("isolateId", isolateId);
  params.addProperty("scriptUri", scriptUri);
  params.addProperty("line", line);
  if (column != null) params.addProperty("column", column);
  request("addBreakpointWithScriptUri", params, consumer);
}
 
Example 14
Source File: WxCpServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String replaceParty(String mediaId) throws WxErrorException {
 String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceparty";
 JsonObject jsonObject = new JsonObject();
 jsonObject.addProperty("media_id", mediaId);
 return post(url, jsonObject.toString());
}
 
Example 15
Source File: RectangularTextContainerSerializer.java    From tabula-java with MIT License 5 votes vote down vote up
@Override
public JsonElement serialize(RectangularTextContainer<?> src, Type typeOfSrc, JsonSerializationContext context) {
	JsonObject result = new JsonObject();
	result.addProperty("top",    src.getTop());
	result.addProperty("left",   src.getLeft());
	result.addProperty("width",  src.getWidth());
	result.addProperty("height", src.getHeight());
	result.addProperty("text",   src.getText());
	return result;
}
 
Example 16
Source File: ReflexJson.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static JsonObject convertAl(ReflexMatchAlertmeLifesign al, JsonSerializationContext context) {
   try {
      JsonObject json = new JsonObject();
      json.addProperty("t", "AL");
      json.addProperty("p", al.getProfile());
      json.addProperty("e", al.getEndpoint());
      json.addProperty("c", al.getCluster());
      json.addProperty("s", al.getSetMask());
      json.addProperty("u", al.getClrMask());

      return json;
   } catch (Exception ex) {
      throw new RuntimeException(ex);
   }
}
 
Example 17
Source File: WxOpenComponentServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getPreAuthUrl(String redirectURI) throws WxErrorException {

  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty("component_appid", getWxOpenConfigStorage().getComponentAppId());
  String responseContent = post(API_CREATE_PREAUTHCODE_URL, jsonObject.toString());
  jsonObject = WxGsonBuilder.create().fromJson(responseContent, JsonObject.class);
  return String.format(COMPONENT_LOGIN_PAGE_URL, getWxOpenConfigStorage().getComponentAppId(), jsonObject.get("pre_auth_code").getAsString(), URIUtil.encodeURIComponent(redirectURI));
}
 
Example 18
Source File: AccessGroupManagement.java    From Insights with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/assignUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody JsonObject assignUser(@RequestBody String reqassignUserdata) {
	String message = " ";
	try {
		
		String assignUserdata = ValidationUtils.validateRequestBody(reqassignUserdata);
		JsonParser parser = new JsonParser();
		JsonElement updateAgentJson = parser.parse(assignUserdata);
		Map<String, String> grafanaHeader = PlatformServiceUtil.prepareGrafanaHeader(httpRequest);
		if (updateAgentJson.isJsonArray()) {
			JsonArray arrayOfOrg = updateAgentJson.getAsJsonArray();
			int size = arrayOfOrg.size();
			// log.debug(size);
			for (int i = 0; i < size; i++) {
				JsonElement aorg = arrayOfOrg.get(i);
				// log.debug(aorg);

				int orgId = aorg.getAsJsonObject().get("orgId").getAsInt();
				String userName = aorg.getAsJsonObject().get("userName").getAsString();
				String orgName = aorg.getAsJsonObject().get("orgName").getAsString();
				String role = aorg.getAsJsonObject().get("roleName").getAsString();
				String apiUrlName = PlatformServiceUtil.getGrafanaURL("/api/users/lookup?loginOrEmail=" + userName);
				// log.debug(userName);
				ClientResponse responsename = callgrafana(apiUrlName, null, RequestMethod.GET.toString(),grafanaHeader);
				JsonObject jsonResponseName = new JsonParser().parse(responsename.getEntity(String.class))
						.getAsJsonObject();
				if (jsonResponseName.get("id") == null) {
					message = "User does not exsist.";
				} else {

					String apiUrlorg = PlatformServiceUtil.getGrafanaURL("/api/orgs/" + orgId + "/users");
					JsonObject requestOrg = new JsonObject();
					requestOrg.addProperty("loginOrEmail", userName);
					requestOrg.addProperty("role", role);
					ClientResponse responseorg = callgrafana(apiUrlorg, requestOrg, RequestMethod.POST.toString(),grafanaHeader);
					message = message + "Org" + ": " + orgName + " " + responseorg.getEntity(String.class);
				}
			}
		}
		return PlatformServiceUtil.buildSuccessResponseWithData(message);
	} catch (Exception e) {
		return PlatformServiceUtil.buildFailureResponse(e.toString());
	}
}
 
Example 19
Source File: SlackSlashCommand.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Format the Knowledge Graph API response into a richly formatted Slack message.
 * @param kgResponse The response from the Knowledge Graph API as a {@link JsonObject}.
 * @param query The user's search query.
 * @return The formatted Slack message as a JSON string.
 */
String formatSlackMessage(JsonObject kgResponse, String query) {
  JsonObject attachmentJson = new JsonObject();

  JsonObject responseJson = new JsonObject();
  responseJson.addProperty("response_type", "in_channel");
  responseJson.addProperty("text", String.format("Query: %s", query));

  JsonArray entityList = kgResponse.getAsJsonArray("itemListElement");

  // Extract the first entity from the result list, if any
  if (entityList.size() == 0) {
    attachmentJson.addProperty("text","No results match your query...");
    responseJson.add("attachments", attachmentJson);

    return gson.toJson(responseJson);
  }

  JsonObject entity = entityList.get(0).getAsJsonObject().getAsJsonObject("result");

  // Construct Knowledge Graph response attachment
  String title = entity.get("name").getAsString();
  if (entity.has("description")) {
    title = String.format("%s: %s", title, entity.get("description").getAsString());
  }
  attachmentJson.addProperty("title", title);

  if (entity.has("detailedDescription")) {
    JsonObject detailedDescJson = entity.getAsJsonObject("detailedDescription");
    addPropertyIfPresent(attachmentJson, "title_link", detailedDescJson, "url");
    addPropertyIfPresent(attachmentJson, "text", detailedDescJson, "articleBody");
  }

  if (entity.has("image")) {
    JsonObject imageJson = entity.getAsJsonObject("image");
    addPropertyIfPresent(attachmentJson, "image_url", imageJson, "contentUrl");
  }

  responseJson.add("attachments", attachmentJson);

  return gson.toJson(responseJson);
}
 
Example 20
Source File: TradeConstants.java    From java-trader with Apache License 2.0 4 votes vote down vote up
public static JsonObject posVolume2json(int[] volumes) {
    JsonObject volumeJson = new JsonObject();
    for(PosVolume posVol:PosVolume.values()) {
        volumeJson.addProperty(posVol.name(), volumes[posVol.ordinal()]);
    }
    return volumeJson;
}