com.google.gson.JsonParser Java Examples
The following examples show how to use
com.google.gson.JsonParser.
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: PacmanUtils.java From pacbot with Apache License 2.0 | 7 votes |
public static Map<String, String> getAmazonEC2ReservedInstanceLeaseExpiration(String checkId, String id, String esUrl, String region, String accountId) throws Exception { JsonParser jsonParser = new JsonParser(); Map<String, String> data = new HashMap<>(); String resourceinfo = getQueryDataForCheckid(checkId, esUrl, id, region, accountId); if (resourceinfo != null) { JsonObject resourceinfoJson = (JsonObject) jsonParser.parse(resourceinfo); String reservedInstanceId = resourceinfoJson.get("Reserved Instance ID").getAsString(); if (!Strings.isNullOrEmpty(reservedInstanceId) && reservedInstanceId.equals(id)) { data.put(PacmanRuleConstants.EST_MONTHLY_SAVINGS, resourceinfoJson.get(PacmanRuleConstants.ESTIMATED_MONTHLY_SAVINGS).getAsString()); data.put(PacmanRuleConstants.REASON, resourceinfoJson.get(PacmanRuleConstants.ISSUE_REASON) .getAsString()); data.put("instanceCount", resourceinfoJson.get("Instance Count").getAsString()); data.put(PacmanRuleConstants.STATUS, resourceinfoJson.get(PacmanRuleConstants.STATUS_CAP).getAsString()); data.put("platform", resourceinfoJson.get("Platform").getAsString()); data.put("currentMonthlyCost", resourceinfoJson.get("Current Monthly Cost").getAsString()); data.put("expirationDate", resourceinfoJson.get("Expiration Date").getAsString()); data.put(PacmanRuleConstants.INSTANCETYPE, resourceinfoJson.get(PacmanRuleConstants.INSTANCE_TYPE_CAP) .getAsString()); data.put("zone", resourceinfoJson.get("Zone").getAsString()); } } return data; }
Example #2
Source File: JsonObjectFlattenerImplTest.java From datawave with Apache License 2.0 | 6 votes |
@Test public void testFlattenWithWhitelist() throws Exception { JsonObjectFlattener flattener = new JsonObjectFlattenerImpl.Builder() .mapKeyWhitelist(new HashSet<>(Arrays.asList("ROOTOBJECT.NUMBER2", "ROOTOBJECT.STRING2"))).pathDelimiter(".") .mapKeyValueNormalizer(toUpperCaseNormalizer).build(); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(json); Multimap<String,String> fieldMap = flattener.flatten(jsonElement.getAsJsonObject()); // printJson(json); // printMap(fieldMap); Assert.assertEquals(2, fieldMap.keySet().size()); Assert.assertEquals(2, fieldMap.values().size()); Assert.assertTrue(fieldMap.containsKey("ROOTOBJECT.NUMBER2") && fieldMap.containsKey("ROOTOBJECT.STRING2")); }
Example #3
Source File: ExportUtil.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * * @param worksheet * @param dvReportJson * @throws JumbuneException * @throws IOException */ public static void createDataQualityExcelReport(Worksheet worksheet, String dvReportJson) throws JumbuneException, IOException { Set<String> fileSet = new TreeSet<String>(); List<String> row = new ArrayList<String>(); // adding header to the rows String sheetName = UtilitiesConstants.DATA_VALIDATION_SHEET; addSheet(worksheet, sheetName); JsonElement jreportElement = new JsonParser().parse(dvReportJson); JsonObject dvReportObject = jreportElement.getAsJsonObject(); if(!dvReportObject.getAsJsonObject("DVSUMMARY").toString().equals("{}")){ row.add("TYPE"); row.add(UtilitiesConstants.TOTAL_VIOLATIONS); Set<String> setOfTotalFiles = getFilesList(dvReportJson, fileSet); for (String string : setOfTotalFiles) { row.add("file : " + string); } addHeader(worksheet, sheetName, null, row); writeStatsRowByRowToFile(dvReportJson, setOfTotalFiles, worksheet, sheetName); }else{ row.add("NO DATA VIOLATIONS FOUND"); addHeader(worksheet, sheetName, null , row); } }
Example #4
Source File: HypixelAPIResponse.java From The-5zig-Mod with GNU General Public License v3.0 | 6 votes |
public HypixelAPIResponse(String response) { if (response == null) { success = false; return; } this.raw = response; JsonParser parser = new JsonParser(); JsonElement element = parser.parse(response); if (!element.isJsonObject()) { throw new IllegalArgumentException(); } this.response = element.getAsJsonObject(); success = this.response.get("success").getAsBoolean(); if (!success) cause = this.response.get("cause").getAsString(); }
Example #5
Source File: OptionManager.java From openapi-style-validator with Apache License 2.0 | 6 votes |
ValidatorParameters getOptionalValidatorParametersOrDefault(CommandLine commandLine) { ValidatorParameters parameters = new ValidatorParameters(); if (commandLine.hasOption(OPTIONS_OPT_SHORT)) { try { String content = Utils.readFile(commandLine.getOptionValue(OPTIONS_OPT_SHORT), Charset.defaultCharset()); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(content); fixConventionRenaming(jsonElement, "path"); fixConventionRenaming(jsonElement, "parameter"); fixConventionRenaming(jsonElement, "property"); Gson gson = new GsonBuilder().create(); parameters = gson.fromJson(jsonElement, ValidatorParameters.class); } catch (Exception ignored) { System.out.println("Invalid path to option files, using default."); } } return parameters; }
Example #6
Source File: JsonDVReportGenerator.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * Generate data validation report. * * @param dvReport the dv report * @return the string */ public String generateDataValidationReport(String dvReport) { JsonDataValidationDashBoardReport boardReport = new JsonDataValidationDashBoardReport(); JsonElement jelement = new JsonParser().parse(dvReport); JsonObject jobject = jelement.getAsJsonObject(); setNullViolations(jobject, boardReport); setRegexViolations(jobject, boardReport); setDataTypeChecks(jobject, boardReport); setSchemaViolations(jobject, boardReport); setMissingViolations(jobject, boardReport); JsonElement jsonElement = new Gson().toJsonTree(boardReport, JsonDataValidationDashBoardReport.class); jobject.add("DVSUMMARY", jsonElement); return jobject.toString(); }
Example #7
Source File: HTTPClientTest.java From amadeus-java with MIT License | 6 votes |
@Test public void testPage() throws ResponseException { Response response = mock(Response.class); Request request = mock(Request.class); JsonObject jsonObject = new JsonParser().parse("{ \"meta\": { " + "\"links\" : {\"next\": \"http://foobar.com?page=10\" } } }").getAsJsonObject(); when(response.getResult()).thenReturn(jsonObject); when(response.getRequest()).thenReturn(request); when(request.getVerb()).thenReturn("GET"); when(request.getPath()).thenReturn("/foo"); when(request.getParams()).thenReturn(Params.with("foo", "bar")); when(client.request(anyString(), anyString(), any(Params.class), anyString())).thenReturn(response); client.accessToken = accessToken; when(accessToken.getBearerToken()).thenReturn("token"); when(client.page("next", response)).thenCallRealMethod(); Response nextResponse = client.page("next", response); assertNotNull(nextResponse); }
Example #8
Source File: KcaApiData.java From kcanotify_h5-master with GNU General Public License v3.0 | 6 votes |
public static JsonObject getExpeditionInfo(int mission_no, String locale) { JsonObject data = null; int mission_key = mission_no; String key = String.valueOf(mission_key); if (!kcExpeditionData.has(key)) { if (mission_no % 2 == 1) key = "203"; else key = "204"; } JsonObject rawdata = kcExpeditionData.getAsJsonObject(String.valueOf(mission_key)); data = new JsonParser().parse(rawdata.toString()).getAsJsonObject(); JsonObject name = data.getAsJsonObject("name"); if (name.has(locale)) { data.addProperty("name", name.get(locale).getAsString()); } else { data.addProperty("name", name.get("en").getAsString()); } return data; }
Example #9
Source File: MarketDataImportAction.java From java-trader with Apache License 2.0 | 6 votes |
/** * 加载producer.json文件, 检测producer类型 */ String detectProducerType(File producerDir) throws IOException { String result = MarketDataProducer.PROVIDER_CTP; File producerJson = new File(producerDir, "producer.json"); if (producerJson.exists()) { JsonObject json = (JsonObject) (new JsonParser()).parse(FileUtil.read(producerJson)); JsonElement typeElem = json.get("type"); if ( typeElem!=null ) { result = typeElem.getAsString(); } JsonElement providerElem = json.get("provider"); if ( providerElem!=null ) { result = providerElem.getAsString(); } } return result; }
Example #10
Source File: CrisisResource.java From AIDR with GNU Affero General Public License v3.0 | 6 votes |
@POST @Consumes( MediaType.APPLICATION_JSON ) @Produces( MediaType.APPLICATION_JSON ) @Path("/crises") public Response getCrisesByCodes(String codes) { try { ObjectMapper objectMapper = new ObjectMapper(); JsonParser jsonParser = new JsonParser(); JsonArray jsonArr = (JsonArray)jsonParser.parse(codes); ArrayList<String> jsonObjList = new Gson().fromJson(jsonArr, ArrayList.class); HashMap<String, Integer> classifiersNumbers = crisisLocalEJB.countClassifiersByCrisisCodes(jsonObjList); String rv = objectMapper.writeValueAsString(classifiersNumbers); return Response.ok(classifiersNumbers).build(); } catch (IOException e) { logger.error("Error while getting numbers of classifiers by crisis codes:", e); return Response.ok("Error while getting numbers of classifiers by crisis codes.").build(); } }
Example #11
Source File: ApiUtil.java From LibreTrivia with GNU General Public License v3.0 | 6 votes |
public static ArrayList<TriviaQuestion> jsonToQuestionArray(String json) throws NoTriviaResultsException { JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); if (jsonObject.get("response_code").getAsInt() == 1) { throw new NoTriviaResultsException(); } JsonArray jsonArray = jsonObject.getAsJsonArray("results"); ArrayList<TriviaQuestion> questions = new ArrayList<>(); for (JsonElement element : jsonArray) { JsonObject object = element.getAsJsonObject(); TriviaType type = TriviaType.get(object.get("type").getAsString()); if (type == TriviaType.MULTIPLE) { questions.add(TriviaQuestionMultiple.fromJson(object)); } else { questions.add(TriviaQuestionBoolean.fromJson(object)); } } return questions; }
Example #12
Source File: BlockServiceEosImpl.java From EosProxyServer with GNU Lesser General Public License v3.0 | 6 votes |
private NewDexTicker getNewDexTicker(String coinmarket_id) throws Exception { StringBuilder req_url = new StringBuilder(); String redis_key = Variables.redisKeyPrefixBlockchain+ Variables.redisKeyEosNewdexMid + coinmarket_id; NewDexTicker newDexTicker = redisService.get(redis_key, NewDexTicker.class); if(newDexTicker == null){ try{ req_url.append(Variables.NEWDEX_TICKER).append("?symbol=").append(coinmarket_id); String result = HttpClientUtils.ocGet(req_url.toString()); JsonElement data = new JsonParser().parse(result); if(data.isJsonObject()){ newDexTicker = new Gson().fromJson(data.getAsJsonObject().get("data").toString(), NewDexTicker.class); redisService.set(redis_key, newDexTicker, Variables.redisCacheTimeout); } } catch (Exception e) { //不再抛出错误,直接初始化为零 newDexTicker = new NewDexTicker(); // throw new ExceptionsChain(ErrorCodeEnumChain.unknown_new_dex_exception); } } return newDexTicker; }
Example #13
Source File: AkashiDetailActivity.java From kcanotify_h5-master with GNU General Public License v3.0 | 6 votes |
private JsonObject getItemCount(Set<String> equip_id) { JsonArray user_equipment_data = dbHelper.getItemData(); String filtcond = getStringPreferences(getApplicationContext(), PREF_EQUIPINFO_FILTCOND); JsonObject count_result = new JsonObject(); for (String e: equip_id) { count_result.addProperty(e, 0); } for (JsonElement data: user_equipment_data) { JsonObject equip = data.getAsJsonObject(); JsonObject value = new JsonParser().parse(equip.get("value").getAsString()).getAsJsonObject(); String slotitem_id = value.get("api_slotitem_id").getAsString(); int level = value.get("api_level").getAsInt(); if (level == 0 && equip_id.contains(slotitem_id)) { count_result.addProperty(slotitem_id, count_result.get(slotitem_id).getAsInt() + 1); } } return count_result; }
Example #14
Source File: KitsuRetriever.java From MantaroBot with GNU General Public License v3.0 | 6 votes |
public static List<AnimeData> searchAnime(String name) { try { Request request = new Request.Builder() .url(String.format("https://kitsu.io/api/edge/anime?filter[text]=%s", URLEncoder.encode(name, StandardCharsets.UTF_8))) .addHeader("User-Agent", MantaroInfo.USER_AGENT) .get() .build(); Response response = httpClient.newCall(request).execute(); String body = response.body().string(); response.close(); Type collectionType = new TypeToken<List<AnimeData>>() { }.getType(); JsonObject json = JsonParser.parseString(body).getAsJsonObject(); JsonArray jarr = json.getAsJsonObject().getAsJsonArray("data"); return gson.fromJson(jarr, collectionType); } catch (IOException e) { return new ArrayList<>(); } }
Example #15
Source File: AssetServiceImpl.java From pacbot with Apache License 2.0 | 6 votes |
@Override public ResponseWithFieldsByTargetType getEditFieldsByTargetType(String resourceType) { List<String> editableFieldsList = new ArrayList<>(); JsonParser jsonParser = new JsonParser(); String field = null; String dataTypeInfo = repository.getDataTypeInfoByTargetType(resourceType); if (dataTypeInfo != null) { JsonObject datatypeInfoJson = (JsonObject) jsonParser.parse(dataTypeInfo); JsonObject dataTypes = datatypeInfoJson.get("dataTypes_info").getAsJsonObject(); Iterator<String> it = dataTypes.keySet().iterator(); while (it.hasNext()) { field = it.next(); editableFieldsList.add(field); } } return new ResponseWithFieldsByTargetType(resourceType, editableFieldsList); }
Example #16
Source File: WxMpCardServiceImpl.java From weixin-java-tools with Apache License 2.0 | 6 votes |
/** * <pre> * 获得卡券api_ticket * 获得时会检查卡券apiToken是否过期,如果过期了,那么就刷新一下,否则就什么都不干 * * 详情请见:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD * .954-.E5.8D.A1.E5.88.B8.E6.89.A9.E5.B1.95.E5.AD.97.E6.AE.B5.E5.8F.8A.E7.AD.BE.E5.90.8D.E7.94 * .9F.E6.88.90.E7.AE.97.E6.B3.95 * </pre> * * @param forceRefresh 强制刷新 * @return 卡券api_ticket */ @Override public String getCardApiTicket(boolean forceRefresh) throws WxErrorException { Lock lock = getWxMpService().getWxMpConfigStorage().getCardApiTicketLock(); try { lock.lock(); if (forceRefresh) { this.getWxMpService().getWxMpConfigStorage().expireCardApiTicket(); } if (this.getWxMpService().getWxMpConfigStorage().isCardApiTicketExpired()) { String responseContent = this.wxMpService.execute(SimpleGetRequestExecutor.create(this.getWxMpService().getRequestHttp()), CARD_GET_TICKET, null); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String cardApiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); this.getWxMpService().getWxMpConfigStorage().updateCardApiTicket(cardApiTicket, expiresInSeconds); } } finally { lock.unlock(); } return this.getWxMpService().getWxMpConfigStorage().getCardApiTicket(); }
Example #17
Source File: VersionCheck.java From BungeePerms with GNU General Public License v3.0 | 6 votes |
public static void checkForUpdate() { try { //get current version int curVersion = BungeePerms.getInstance().getPlugin().getBuild(); URL url = new URL("https://ci.wea-ondara.net/job/BungeePerms/api/json"); URLConnection request = url.openConnection(); request.connect(); JsonParser jp = new JsonParser(); JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); JsonObject j = root.getAsJsonObject(); int remoteVersion = j.getAsJsonObject("lastSuccessfulBuild").get("number").getAsInt(); if (remoteVersion > curVersion) { BungeePerms.getInstance().getPlugin().getConsole().sendMessage("[BungeePerms] " + Lang.translate(Lang.MessageType.UPDATE_AVAILABLE)); } } catch (Exception e) { } }
Example #18
Source File: JsonIngestFlattenerTest.java From datawave with Apache License 2.0 | 6 votes |
@Test public void testFlattenGROUPED_AND_NORMAL() throws Exception { JsonObjectFlattener flattener = new JsonIngestFlattener.Builder().flattenMode(FlattenMode.GROUPED_AND_NORMAL).build(); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(json); Multimap<String,String> fieldMap = flattener.flatten(jsonElement.getAsJsonObject()); // printJson(json); // printMap(fieldMap); Assert.assertEquals(74, fieldMap.keySet().size()); Assert.assertEquals(74, fieldMap.values().size()); Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_0.CHARACTER_0.NAME_0").size()); Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_1.CHARACTER_0.NAME_0").size()); Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_2.CHARACTER_0.NAME_0").size()); Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_3.CHARACTER_0.NAME_0").size()); Assert.assertEquals("Jerry Seinfeld", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_0.CHARACTER_0.NAME_0").iterator().next()); Assert.assertEquals("Cosmo Kramer", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_1.CHARACTER_0.NAME_0").iterator().next()); Assert.assertEquals("George Louis Costanza", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_2.CHARACTER_0.NAME_0").iterator().next()); Assert.assertEquals("Elaine Marie Benes", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_3.CHARACTER_0.NAME_0").iterator().next()); }
Example #19
Source File: MessagePacker.java From AndroidRipper with GNU Affero General Public License v3.0 | 6 votes |
/** * UnPack Map from byte array * * @param b byte array * @return UnPacked Map */ @SuppressWarnings("unchecked") public static Map unpack(byte[] b) { if (b != null) { String s = new String(b); try { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonObject o = parser.parse(s).getAsJsonObject(); Map<String, Object> map = new HashMap<String, Object>(); map = (Map<String,Object>) gson.fromJson(o, map.getClass()); return map; } catch (Throwable t) { t.printStackTrace(); } } return null; }
Example #20
Source File: SpotifyManager.java From The-5zig-Mod with MIT License | 6 votes |
private void loadCsrfToken(final Runnable runnable) { makeRequest(getURL("/simplecsrf/token.json"), Collections.<String, String>emptyMap(), originHeader, new HttpResponseCallback() { @Override public void call(String response, int responseCode, Throwable throwable) { if (throwable != null) { The5zigMod.logger.error("Could not load Spotify Csrf-Token!", throwable); reconnect(); } else if (response != null) { JsonElement element = new JsonParser().parse(response); if (!parseError(element)) { if (element.isJsonObject() && element.getAsJsonObject().has("token") && element.getAsJsonObject().get("token").isJsonPrimitive()) { csrfToken = element.getAsJsonObject().get("token").getAsString(); runnable.run(); } else { The5zigMod.logger.error("Could not load Spotify Csrf-Token: " + response); reconnect(); } } } } }); }
Example #21
Source File: RunController.java From wings with Apache License 2.0 | 6 votes |
public String deleteRuns(String rjson, ServletContext context) { HashMap<String, Object> ret = new HashMap<String, Object>(); ret.put("success", false); JsonElement listel = new JsonParser().parse(rjson); if (listel == null) return json.toJson(ret); if(listel.isJsonObject()) { return this.deleteRun(rjson, context); } ExecutionMonitorAPI monitor = config.getDomainExecutionMonitor(); JsonArray list = listel.getAsJsonArray(); for(int i=0; i<list.size(); i++) { JsonElement el = list.get(i); String runid = el.getAsJsonObject().get("id").getAsString(); monitor.deleteRun(runid, config.isDeleteRunOutputs()); } ret.put("success", true); return json.toJson(ret); }
Example #22
Source File: HypixelAPIResponse.java From The-5zig-Mod with MIT License | 6 votes |
public HypixelAPIResponse(String response) { if (response == null) { success = false; return; } this.raw = response; JsonParser parser = new JsonParser(); JsonElement element = parser.parse(response); if (!element.isJsonObject()) { throw new IllegalArgumentException(); } this.response = element.getAsJsonObject(); success = this.response.get("success").getAsBoolean(); if (!success) cause = this.response.get("cause").getAsString(); }
Example #23
Source File: JsonMqttAdaptor.java From Groza with Apache License 2.0 | 5 votes |
public static JsonElement validateJsonPayload(SessionId sessionId, ByteBuf payloadData) throws AdaptorException { String payload = validatePayload(sessionId, payloadData); try { return new JsonParser().parse(payload); } catch (JsonSyntaxException ex) { throw new AdaptorException(ex); } }
Example #24
Source File: GitHubUtil.java From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License | 5 votes |
public int createPullReq(GHRepository origRepo, String branch, GHRepository forkRepo, String title, String body) throws InterruptedException { log.info("Creating Pull Request on {} from {}...", origRepo.getFullName(), forkRepo.getFullName()); //TODO: if no commits, pull request will fail, but this doesn't handle that. try { GHPullRequest pullRequest = origRepo.createPullRequest(title, forkRepo.getOwnerName() + ":" + branch, origRepo.getDefaultBranch(), body); // origRepo.createPullRequest("Update base image in Dockerfile", forkRepo.getOwnerName() + ":" + branch, // origRepo.getDefaultBranch(), "Automatic Dockerfile Image Updater. Please merge."); log.info("A pull request has been created at {}", pullRequest.getHtmlUrl()); return 0; } catch (IOException e) { log.warn("Handling error with pull request creation... {}", e.getMessage()); JsonElement root = JsonParser.parseString(e.getMessage()); JsonArray errorJson = root.getAsJsonObject().get("errors").getAsJsonArray(); String error = errorJson.get(0).getAsJsonObject().get("message").getAsString(); log.info("error: {}", error); if (error.startsWith("A pull request already exists")) { log.info("NOTE: {} New commits may have been added to the pull request.", error); return 0; } else if (error.startsWith("No commits between")) { log.warn("NOTE: {} Pull request was not created.", error); return 1; } else { // TODO: THIS WILL LOOP FOREVVEEEEEERRRR log.warn("An error occurred in pull request: {} Trying again...", error); waitFor(TimeUnit.SECONDS.toMillis(3)); return -1; } } }
Example #25
Source File: JsonMqttAdaptor.java From IOT-Technical-Guide with Apache License 2.0 | 5 votes |
private static void convertToUpdateAttributesRequest(MqttPublishMessage inbound) throws AdaptorException { String payload = validatePayload(inbound.payload()); try { Set<AttributeKvEntry> attributeKvEntrySet = JsonConverter.convertToAttributes(new JsonParser().parse(payload), inbound.variableHeader().messageId()).getAttributes(); for (AttributeKvEntry attributeKvEntry : attributeKvEntrySet){ System.out.println("属性名="+attributeKvEntry.getKey()+" 属性值="+attributeKvEntry.getValueAsString()); } } catch (IllegalStateException | JsonSyntaxException ex) { throw new AdaptorException(ex); } }
Example #26
Source File: VirtualFireAlarmTestCase.java From product-iots with Apache License 2.0 | 5 votes |
@Test(description = "This test case tests the virtual fire alarm enrollment") public void testEnrollment() throws Exception { // Time for deploying the carbon apps Thread.sleep(30000); RestClient client = new RestClient(backendHTTPSURL, Constants.APPLICATION_ZIP, accessTokenString); // Enroll an advanced agent and check whether that enrollment succeeds without issues. HttpResponse response = client.get(Constants.VirtualFireAlarmConstants.ENROLLMENT_ENDPOINT + "?deviceName=advanced&sketchType=virtual_firealarm_advanced"); Assert.assertEquals("Advance fire alarm advance agent enrollment failed", HttpStatus.SC_OK, response.getResponseCode()); // Enroll an simple agent and check whether that enrollment succeeds without issues. response = client.get(Constants.VirtualFireAlarmConstants.ENROLLMENT_ENDPOINT + "?deviceName=simple&sketchType=virtual_firealarm"); Assert.assertEquals("Advance fire alarm advance agent enrollment failed", HttpStatus.SC_OK, response.getResponseCode()); response = client.get(Constants.MobileDeviceManagement.GET_DEVICE_COUNT_ENDPOINT + "?type=virtual_firealarm"); JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonObject().getAsJsonArray("devices"); Assert.assertEquals("Virtual fire alarm enrollment failed ", 2, jsonArray.size()); if (userMode != TestUserMode.TENANT_ADMIN) { deviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); deviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); } else { tenantDeviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); tenantDeviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); } }
Example #27
Source File: TestUtils.java From jhipster-registry with Apache License 2.0 | 5 votes |
public static boolean isValid(String json) { try { JsonParser.parseString(json); return true; } catch (JsonSyntaxException jse) { return false; } }
Example #28
Source File: JsonParserTest.java From gson with Apache License 2.0 | 5 votes |
public void testChangingCustomTreeAndDeserializing() { StringReader json = new StringReader("{'stringValue':'no message','intValue':10,'longValue':20}"); JsonObject obj = (JsonObject) JsonParser.parseReader(json); obj.remove("stringValue"); obj.addProperty("stringValue", "fooBar"); BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class); assertEquals(10, target.intValue); assertEquals(20, target.longValue); assertEquals("fooBar", target.stringValue); }
Example #29
Source File: SpeechToTextWebSocketListener.java From java-sdk with Apache License 2.0 | 5 votes |
/** * Builds the start message. * * @param options the options * @return the request */ private String buildStartMessage(RecognizeOptions options) { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); JsonObject startMessage = new JsonParser().parse(gson.toJson(options)).getAsJsonObject(); startMessage.remove(MODEL); startMessage.remove(CUSTOMIZATION_ID); startMessage.remove(LANGUAGE_CUSTOMIZATION_ID); startMessage.remove(ACOUSTIC_CUSTOMIZATION_ID); startMessage.remove(VERSION); startMessage.addProperty(ACTION, START); return startMessage.toString(); }
Example #30
Source File: ArraySplitOperationTest.java From bender with Apache License 2.0 | 5 votes |
@Test public void testTimeMatch() throws JsonSyntaxException, UnsupportedEncodingException, IOException { JsonParser parser = new JsonParser(); TestContext t = new TestContext(); t.setFunctionName("foo"); LambdaContext lctx = new LambdaContext(t); JsonElement input = parser.parse(getResourceString("array_input.json")); GenericJsonEvent devent = new GenericJsonEvent(input.getAsJsonObject()); ArraySplitOperation operation = new ArraySplitOperation("$.arr"); InternalEvent ievent = new InternalEvent("", lctx, 123); ievent.setEventObj(devent); ievent.setEventTime(124); List<InternalEvent> events = operation.perform(ievent); assertEquals(ievent.getArrivalTime(), events.get(0).getArrivalTime()); assertEquals(ievent.getEventTime(), events.get(0).getEventTime()); assertEquals(ievent.getArrivalTime(), events.get(1).getArrivalTime()); assertEquals(ievent.getEventTime(), events.get(1).getEventTime()); assertEquals(ievent.getArrivalTime(), events.get(2).getArrivalTime()); assertEquals(ievent.getEventTime(), events.get(2).getEventTime()); }