Java Code Examples for com.google.gson.JsonParser#parse()
The following examples show how to use
com.google.gson.JsonParser#parse() .
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: ConfigManagerTest.java From pacbot with Apache License 2.0 | 6 votes |
@Test public void getConfigurationsMapTest() throws Exception { String str = "{\"name\":\"123\",\"profiles\":[\"123\"],\"label\":\"123\",\"version\":null,\"state\":null,\"propertySources\":[{\"name\":\"rule-stg\",\"source\":{\"test\":\"test\"}},{\"name\":\"application-stg\",\"source\":{\"test\":\"test\"}}]}"; JsonParser jsonParser = new JsonParser(); JsonObject jo = (JsonObject)jsonParser.parse(str); mockStatic(PacmanUtils.class); when(PacmanUtils.getEnvironmentVariable(anyString())).thenReturn("123"); when(PacmanUtils.getHeader(anyString())).thenReturn(new HashMap<String, String>()); when(PacmanUtils.getConfigurationsFromConfigApi(anyString(),anyObject())).thenReturn(jo); assertThat(configManager.getConfigurationsMap(), is(notNullValue())); when(PacmanUtils.getConfigurationsFromConfigApi(anyString(),anyObject())).thenReturn(jo); assertThat(configManager.getConfigurationsMap(), is(notNullValue())); when(PacmanUtils.getEnvironmentVariable(anyString())).thenReturn(null); assertThatThrownBy( () -> configManager.getConfigurationsMap()).isInstanceOf(InvalidInputException.class); }
Example 2
Source File: ObservationFromServer.java From malmo with MIT License | 6 votes |
@Override public void writeObservationsToJSON(JsonObject json, MissionInit missionInit) { String jsonstring = ""; synchronized (this.latestJsonStats) { jsonstring = this.latestJsonStats; } if (jsonstring.length() > 2) // "{}" is the empty JSON string. { // Parse the string into json: JsonParser parser = new JsonParser(); JsonElement root = parser.parse(jsonstring); // Now copy the children of root into the provided json object: if (root.isJsonObject()) { JsonObject rootObj = root.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : rootObj.entrySet()) { json.add(entry.getKey(), entry.getValue()); } } } }
Example 3
Source File: PostSetup.java From Slimefun4 with GNU General Public License v3.0 | 6 votes |
public static void setupWiki() { Slimefun.getLogger().log(Level.INFO, "Loading Wiki pages..."); JsonParser parser = new JsonParser(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(SlimefunPlugin.class.getResourceAsStream("/wiki.json"), StandardCharsets.UTF_8))) { JsonElement element = parser.parse(reader.lines().collect(Collectors.joining(""))); JsonObject json = element.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { SlimefunItem item = SlimefunItem.getByID(entry.getKey()); if (item != null) { item.addOficialWikipage(entry.getValue().getAsString()); } } } catch (IOException e) { Slimefun.getLogger().log(Level.SEVERE, "Failed to load wiki.json file", e); } }
Example 4
Source File: KeyNameReplacementOperationTest.java From bender with Apache License 2.0 | 6 votes |
@Test public void testDropKeys() throws JsonSyntaxException, IOException, OperationException { JsonParser parser = new JsonParser(); JsonElement input = parser.parse(getResourceString("basic_input_replacement_drop.json")); String expectedOutput = getResourceString("basic_output_replacement_drop.json"); DummpyEvent devent = new DummpyEvent(); devent.payload = input.getAsJsonObject(); Pattern p = Pattern.compile("[^a-z]"); KeyNameReplacementOperation operation = new KeyNameReplacementOperation(p, "", true); InternalEvent ievent = new InternalEvent("", null, 0); ievent.setEventObj(devent); operation.perform(ievent); assertEquals(parser.parse(expectedOutput), input); }
Example 5
Source File: S3PacbotUtils.java From pacbot with Apache License 2.0 | 5 votes |
private static JsonArray getPolicyArray(AmazonS3Client awsS3Client,String s3BucketName) { JsonParser jsonParser = new JsonParser(); JsonArray policyJsonArray = new JsonArray(); BucketPolicy bucketPolicy = awsS3Client.getBucketPolicy(s3BucketName); if (!com.amazonaws.util.StringUtils.isNullOrEmpty(bucketPolicy.getPolicyText())) { JsonObject resultJson = (JsonObject) jsonParser.parse(bucketPolicy.getPolicyText()); policyJsonArray = resultJson.get("Statement").getAsJsonArray(); } return policyJsonArray; }
Example 6
Source File: OptimizelyTest.java From java-sdk with Apache License 2.0 | 5 votes |
private boolean compareJsonStrings(String str1, String str2) { JsonParser parser = new JsonParser(); JsonElement j1 = parser.parse(str1); JsonElement j2 = parser.parse(str2); return j1.equals(j2); }
Example 7
Source File: Util.java From pacbot with Apache License 2.0 | 5 votes |
/** * Fetch data and scroll id. * * @param endPoint the end point * @param _data the data * @param payLoad the pay load * @return the string */ private static String fetchDataAndScrollId(String endPoint, List<Map<String, String>> _data, String payLoad) { try { Response response = ElasticSearchManager.invokeAPI("GET", endPoint, payLoad); String responseJson; responseJson = EntityUtils.toString(response.getEntity()); JsonParser jsonParser = new JsonParser(); JsonObject resultJson = (JsonObject) jsonParser.parse(responseJson); String scrollId = resultJson.get("_scroll_id").getAsString(); JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get("hits").toString()); JsonArray jsonArray = hitsJson.getAsJsonObject().get("hits").getAsJsonArray(); if (jsonArray.size() > 0) { for (int i = 0; i < jsonArray.size(); i++) { JsonObject obj = (JsonObject) jsonArray.get(i); JsonObject sourceJson = (JsonObject) obj.get(SOURCE); if (sourceJson != null) { Map<String, String> doc = new Gson().fromJson(sourceJson, new TypeToken<Map<String, String>>() { }.getType()); _data.add(doc); } } return scrollId; } else { return null; } } catch (ParseException | IOException e) { LOGGER.error("Error in fetchDataAndScrollId",e); } return null; }
Example 8
Source File: PacmanUtils.java From pacbot with Apache License 2.0 | 5 votes |
/** * Gets the security groups by resource id. * * @param resourceId the resourceId * @param esUrl the es url * @param resourceField the resource field * @param sgField the sgField * @param sgStatusField the sgStatusField * @return the security groups by resource id * @throws Exception the exception */ public static List<GroupIdentifier> getSecurityGroupsByResourceId(String resourceId, String esUrl,String resourceField,String sgField,String sgStatusField) throws Exception { List<GroupIdentifier> list = new ArrayList<>(); JsonParser jsonParser = new JsonParser(); Map<String, Object> mustFilter = new HashMap<>(); Map<String, Object> mustNotFilter = new HashMap<>(); HashMultimap<String, Object> shouldFilter = HashMultimap.create(); Map<String, Object> mustTermsFilter = new HashMap<>(); mustFilter.put(convertAttributetoKeyword(resourceField), resourceId); JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(esUrl, mustFilter, mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null,null); if (resultJson != null && resultJson.has(PacmanRuleConstants.HITS)) { JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get(PacmanRuleConstants.HITS).toString()); JsonArray hitsArray = hitsJson.getAsJsonArray(PacmanRuleConstants.HITS); for (int i = 0; i < hitsArray.size(); i++) { JsonObject source = hitsArray.get(i).getAsJsonObject().get(PacmanRuleConstants.SOURCE) .getAsJsonObject(); String securitygroupid = source.get(sgField).getAsString(); String vpcSecuritygroupStatus = source.get(sgStatusField).getAsString(); if("active".equals(vpcSecuritygroupStatus)){ GroupIdentifier groupIdentifier = new GroupIdentifier(); if (!com.amazonaws.util.StringUtils.isNullOrEmpty(securitygroupid)) { groupIdentifier.setGroupId(securitygroupid); list.add(groupIdentifier); } } } } return list; }
Example 9
Source File: JsonUtil.java From UltimateAndroid with Apache License 2.0 | 5 votes |
public static ArrayList getArrayListMapFromJson(String jsonString) { JsonParser jsonParser = new JsonParser(); Gson gson = new Gson(); JsonElement jsonElement = jsonParser.parse(jsonString); Logs.d(jsonElement.isJsonArray() + " " + jsonElement.isJsonObject()); ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>(); if (jsonElement.isJsonObject()) { arrayList.add(gson.fromJson(jsonElement, HashMap.class)); } else if (jsonElement.isJsonArray()) { arrayList = getListFromJson(jsonString, new TypeToken<ArrayList<HashMap<String, Object>>>() { }); } return arrayList; }
Example 10
Source File: ComplianceRepositoryImpl.java From pacbot with Apache License 2.0 | 5 votes |
private JsonObject getResopnse(String assetGroup, String apiType, String application, String environment, String resourceType) throws DataException { StringBuilder urlToQuery = formatURL(assetGroup, resourceType, apiType); String responseJson = ""; try { responseJson = PacHttpUtils.doHttpPost(urlToQuery.toString(), getQueryForQualys(apiType, application, environment, resourceType).toString()); } catch (Exception e) { logger.error(e.toString()); throw new DataException(e.getMessage()); } JsonParser jsonParser = new JsonParser(); return (JsonObject) jsonParser.parse(responseJson); }
Example 11
Source File: LeinNvdParser.java From sonar-clojure with MIT License | 5 votes |
public static List<Vulnerability> parseJson(String json){ List<Vulnerability> vulnerabilities = new ArrayList<>(); JsonParser parser = new JsonParser(); JsonElement jsonTree = parser.parse(json); JsonObject jsonObject = jsonTree.getAsJsonObject(); JsonArray dependencies = jsonObject.get("dependencies").getAsJsonArray(); for (JsonElement element: dependencies) { JsonObject dependency = element.getAsJsonObject(); if (dependency.has("vulnerabilities")){ LOG.debug("Found vulnerabilities in: " + dependency.getAsJsonPrimitive("fileName").getAsString()); JsonArray dependencyVulnerabilities = dependency.get("vulnerabilities").getAsJsonArray(); for (JsonElement dependencyVulnerability: dependencyVulnerabilities) { JsonObject dependencyVulnerabilityObject = dependencyVulnerability.getAsJsonObject(); JsonArray cwesArray = dependencyVulnerabilityObject.getAsJsonArray("cwes"); String[] cwes = new Gson().fromJson(cwesArray, String[].class); Vulnerability v = new Vulnerability() .setName(dependencyVulnerabilityObject.getAsJsonPrimitive("name").getAsString()) .setSeverity(dependencyVulnerabilityObject.getAsJsonPrimitive("severity").getAsString()) .setCwes(String.join(",", cwes)) .setDescription(dependencyVulnerabilityObject.getAsJsonPrimitive("description").getAsString()) .setFileName(dependency.getAsJsonPrimitive("fileName").getAsString()); vulnerabilities.add(v); } } } return vulnerabilities; }
Example 12
Source File: JsonUtil.java From UltimateAndroid with Apache License 2.0 | 5 votes |
public static ArrayList getArrayListMapFromJson(String jsonString) { JsonParser jsonParser = new JsonParser(); Gson gson = new Gson(); JsonElement jsonElement = jsonParser.parse(jsonString); Logs.d(jsonElement.isJsonArray() + " " + jsonElement.isJsonObject()); ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>(); if (jsonElement.isJsonObject()) { arrayList.add(gson.fromJson(jsonElement, HashMap.class)); } else if (jsonElement.isJsonArray()) { arrayList = getListFromJson(jsonString, new TypeToken<ArrayList<HashMap<String, Object>>>() { }); } return arrayList; }
Example 13
Source File: JsonUtil.java From telekom-workflow-engine with MIT License | 5 votes |
public static <T> Collection<T> deserializeCollection( String json, @SuppressWarnings("rawtypes") Class<? extends Collection> type, Class<T> elementType ){ if( json == null ){ return null; } JsonParser parser = new JsonParser(); JsonElement element = parser.parse( json ); @SuppressWarnings("unchecked") Collection<T> result = (Collection<T>)deconvertCollection( element, type, elementType ); return result; }
Example 14
Source File: AgentDataSubscriber.java From Insights with Apache License 2.0 | 4 votes |
private JsonObject applyDataTagging(JsonObject asJsonObject) { List<String> selectedBusinessMappingArray = new ArrayList<String>(0); Map<String, String> labelMappingMap = new TreeMap<String, String>(); for (BusinessMappingData businessMappingData : businessMappingList) { Map<String, String> map = businessMappingData.getPropertyMap(); int totalCount = businessMappingData.getPropertyMap().size(); int matchLabelcount = 0; for (Entry<String, String> mapValue : map.entrySet()) { if (asJsonObject.has(mapValue.getKey())) { String jsonValue = asJsonObject.get(mapValue.getKey()).getAsString(); if (jsonValue.equalsIgnoreCase(mapValue.getValue())) { matchLabelcount++; } } } if (totalCount == matchLabelcount) { selectedBusinessMappingArray.add(businessMappingData.getBusinessMappingLabel()); } } if (!selectedBusinessMappingArray.isEmpty()) { for (int i = 0; i < selectedBusinessMappingArray.size(); i++) { StringTokenizer sk = new StringTokenizer(selectedBusinessMappingArray.get(i), ":"); int level = 0; while (sk.hasMoreTokens()) { String token = sk.nextToken(); level++; String key = "orgLevel_" + level; if (!labelMappingMap.containsKey(key)) { labelMappingMap.put(key, token); } else { if (!labelMappingMap.get(key).contains(token)) { labelMappingMap.put(key, labelMappingMap.get(key).concat("," + token)); } } } } JsonParser jsonParser = new JsonParser(); Gson gson = new Gson(); for (Entry<String, String> entry : labelMappingMap.entrySet()) { List<String> items = Arrays.asList(entry.getValue().split("\\s*,\\s*")); JsonArray jsonArray = (JsonArray) jsonParser.parse(items.toString()); asJsonObject.add(entry.getKey(), jsonArray); } } return asJsonObject; }
Example 15
Source File: HubLogger.java From arcusplatform with Apache License 2.0 | 4 votes |
private JsonArray bytesToLogs(byte[] payload) { String spayload = new String(payload, StandardCharsets.UTF_8); JsonParser parser = new JsonParser(); JsonElement elem = parser.parse(spayload); return elem.getAsJsonArray(); }
Example 16
Source File: PacmanUtils.java From pacbot with Apache License 2.0 | 4 votes |
public static Map<String, String> getLowUtilizationEc2Details(String checkId, String id, String esUrl, String region, String accountId) throws Exception { String cpuUtilization = null; String day = null; String networkIO = null; 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 instanceId = resourceinfoJson.get("Instance ID").getAsString(); if (!Strings.isNullOrEmpty(instanceId) && instanceId.equals(id)) { String estimatedMonthlySavings = resourceinfoJson.get(PacmanRuleConstants.ESTIMATED_MONTHLY_SAVINGS) .getAsString(); String days = resourceinfoJson.get("Number of Days Low Utilization").getAsString(); int count = 1; if (!StringUtils.isEmpty(days) && "14 days".equals(days)) { for (int k = 1; k <= 14; k++) { day = resourceinfoJson.get("Day " + k).getAsString(); cpuUtilization = StringUtils.substringBefore(day, "%"); Double cpuUtilizationD = Double.parseDouble(cpuUtilization); networkIO = StringUtils.substringBetween(day, "%", "MB").trim(); Double networkUtilizationD = Double.parseDouble(networkIO); if (cpuUtilizationD <= 10 && networkUtilizationD <= 5) { if (count == 4) { data.put(PacmanRuleConstants.EST_MONTHLY_SAVINGS, estimatedMonthlySavings); data.put("noOfDaysLowUtilization", days); return data; } count++; } } } } } return data; }
Example 17
Source File: LDAPManager.java From pacbot with Apache License 2.0 | 4 votes |
/** * This method used to get the Kernel Version of an instance. * * @param instanceId * @return String, if kernel version available else null */ public static String getQueryfromLdapElasticSearch(String instanceId, String ldapApi) { JsonParser jsonParser = new JsonParser(); JsonArray jsonArray = new JsonArray(); try { HttpClient client = HttpClientBuilder.create().build(); URL url = new URL(ldapApi); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); // prepare Json pay load for GET query. JsonObject innerJson = new JsonObject(); JsonObject matchPhrase = new JsonObject(); JsonObject must = new JsonObject(); JsonObject bool = new JsonObject(); JsonObject query = new JsonObject(); innerJson.addProperty("instanceid", instanceId); matchPhrase.add("match_phrase", innerJson); must.add("must", matchPhrase); bool.add("bool", must); query.add("query", bool); StringEntity strjson = new StringEntity(query.toString()); // Qurying the ES HttpPost httpPost = new HttpPost(); httpPost.setURI(uri); httpPost.setEntity(strjson); httpPost.setHeader("Content-Type", "application/json"); HttpResponse response = client.execute(httpPost); String jsonString = EntityUtils.toString(response.getEntity()); JsonObject resultJson = (JsonObject) jsonParser.parse(jsonString); String hitsJsonString = resultJson.get("hits").toString(); JsonObject hitsJson = (JsonObject) jsonParser.parse(hitsJsonString); jsonArray = hitsJson.getAsJsonObject().get("hits").getAsJsonArray(); if (jsonArray.size() > 0) { JsonObject firstObject = (JsonObject) jsonArray.get(0); JsonObject sourceJson = (JsonObject) firstObject.get("_source"); if (sourceJson != null) { JsonElement osVersion = sourceJson.get("os_version"); if (osVersion != null) { return getKernelVersion(osVersion); } } } else { logger.info("no records found in ElasticSearch"); } } catch (MalformedURLException me) { logger.error(me.getMessage()); } catch (UnsupportedEncodingException ue) { logger.error(ue.getMessage()); } catch (ClientProtocolException ce) { logger.error(ce.getMessage()); } catch (IOException ioe) { logger.error(ioe.getMessage()); } catch (URISyntaxException use) { logger.error(use.getMessage()); } return null; }
Example 18
Source File: FakeGpsOutput.java From sensorhub with Mozilla Public License 2.0 | 4 votes |
private boolean generateRandomTrajectory() { FakeGpsConfig config = getParentModule().getConfiguration(); // used fixed start/end coordinates or generate random ones double startLat; double startLong; double endLat; double endLong; if (trajPoints.isEmpty()) { startLat = config.centerLatitude + (Math.random()-0.5) * config.areaSize; startLong = config.centerLongitude + (Math.random()-0.5) * config.areaSize; // if fixed start and end locations not given, pick random values within area if (config.startLatitude == null || config.startLongitude == null || config.stopLatitude == null || config.stopLongitude == null) { startLat = config.centerLatitude + (Math.random()-0.5) * config.areaSize; startLong = config.centerLongitude + (Math.random()-0.5) * config.areaSize; endLat = config.centerLatitude + (Math.random()-0.5) * config.areaSize; endLong = config.centerLongitude + (Math.random()-0.5) * config.areaSize; } // else use start/end locations provided in configuration else { startLat = config.startLatitude; startLong = config.startLongitude; endLat = config.stopLatitude; endLong = config.stopLongitude; } } else { // restart from end of previous track double[] lastPoint = trajPoints.get(trajPoints.size()-1); startLat = lastPoint[0]; startLong = lastPoint[1]; endLat = config.centerLatitude + (Math.random()-0.5) * config.areaSize; endLong = config.centerLongitude + (Math.random()-0.5) * config.areaSize; } try { // request directions using Google API URL dirRequest = new URL(config.googleApiUrl + "?origin=" + startLat + "," + startLong + "&destination=" + endLat + "," + endLong + ((config.walkingMode) ? "&mode=walking" : "")); log.debug("Google API request: " + dirRequest); InputStream is = new BufferedInputStream(dirRequest.openStream()); // parse JSON track JsonParser reader = new JsonParser(); JsonElement root = reader.parse(new InputStreamReader(is)); //System.out.println(root); JsonArray routes = root.getAsJsonObject().get("routes").getAsJsonArray(); if (routes.size() == 0) throw new Exception("No route available"); JsonElement polyline = routes.get(0).getAsJsonObject().get("overview_polyline"); String encodedData = polyline.getAsJsonObject().get("points").getAsString(); // decode polyline data decodePoly(encodedData); currentTrackPos = 0.0; return true; } catch (Exception e) { log.error("Error while retrieving Google directions", e); trajPoints.clear(); try { Thread.sleep(60000L); } catch (InterruptedException e1) {} return false; } }
Example 19
Source File: PacmanUtils.java From pacbot with Apache License 2.0 | 4 votes |
public static String getQueryDataForCheckid(String checkId, String esUrl, String id, String region, String accountId) throws Exception { JsonParser jsonParser = new JsonParser(); String resourceinfo = null; Map<String, Object> mustFilter = new HashMap<>(); Map<String, Object> mustNotFilter = new HashMap<>(); Map<String, List<String>> matchPhrasePrefix = new HashMap<>(); HashMultimap<String, Object> shouldFilter = HashMultimap.create(); Map<String, Object> mustTermsFilter = new HashMap<>(); mustFilter.put(PacmanRuleConstants.CHECK_ID_KEYWORD, checkId); mustFilter.put(PacmanRuleConstants.ACCOUNT_ID_KEYWORD, accountId); List<String> resourceInfoList = new ArrayList<>(); if (region != null) { resourceInfoList.add(region); } resourceInfoList.add(id); matchPhrasePrefix.put(PacmanRuleConstants.RESOURCE_INFO, resourceInfoList); JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(esUrl, mustFilter, mustNotFilter, shouldFilter, null, 0, mustTermsFilter, matchPhrasePrefix,null); if (resultJson != null && resultJson.has(PacmanRuleConstants.HITS)) { JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get(PacmanRuleConstants.HITS).toString()); JsonArray jsonArray = hitsJson.getAsJsonObject().get(PacmanRuleConstants.HITS).getAsJsonArray(); if (jsonArray.size() > 0) { for (int i = 0; i < jsonArray.size(); i++) { JsonObject firstObject = (JsonObject) jsonArray.get(i); JsonObject sourceJson = (JsonObject) firstObject.get(PacmanRuleConstants.SOURCE); if (sourceJson != null && sourceJson.has(PacmanRuleConstants.RESOURCE_INFO)) { if (sourceJson.get(PacmanRuleConstants.RESOURCE_INFO).isJsonObject()) { resourceinfo = sourceJson.get(PacmanRuleConstants.RESOURCE_INFO).getAsJsonObject() .toString(); } else { resourceinfo = sourceJson.get(PacmanRuleConstants.RESOURCE_INFO).getAsString(); } } } } } return resourceinfo; }
Example 20
Source File: SHPtoJson.java From ungentry with MIT License | 3 votes |
public static String prettyJson(String iJsonData){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(iJsonData); return gson.toJson(je); }