@Override public void delete(String url) throws IOException { try { JSONObject doc_builder = new JSONObject(); doc_builder.put("type", "delete"); // generate the id from the url String ID = CloudSearchUtils.getID(url); doc_builder.put("id", ID); // add to the batch addToBatch(doc_builder.toString(2), url); } catch (JSONException e) { LOG.error("Exception caught while building JSON object", e); } }
private void createIntegrationResponses(Integration integration, JSONObject responses) { if (responses == null) { return; } final Iterator<String> keysIterator = responses.keys(); while (keysIterator.hasNext()) { String key = keysIterator.next(); try { String pattern = key.equals("default") ? null : key; JSONObject response = responses.getJSONObject(key); String status = (String) response.get("statusCode"); PutIntegrationResponseInput input = new PutIntegrationResponseInput() .withResponseParameters(jsonObjectToHashMapString(response.optJSONObject("responseParameters"))) .withResponseTemplates(jsonObjectToHashMapString(response.optJSONObject("responseTemplates"))) .withSelectionPattern(pattern); integration.putIntegrationResponse(input, status); } catch (JSONException e) { } } }
private Map<String, String> jsonObjectToHashMapString (JSONObject json) { if (json == null) { return null; } final Map<String, String> map = new HashMap<>(); final Iterator<String> keysIterator = json.keys(); while (keysIterator.hasNext()) { String key = keysIterator.next(); try { map.put(key, json.getString(key)); } catch (JSONException e) {} } return map; }
private void validateProvisioning() throws JSONException, InterruptedException, SQLException { // Because the provision is async we have to give it some time // to happen. We poll here and check it's state. givenTheBroker().get("/v2/service_instances/1234").then() .body("last_operation.state", equalTo("in progress")).and() .statusCode(200); waitForProvisionCompletion(); givenTheBroker().get("/api/instances").then() .body("[0].source", equalTo(sourceInstanceId)).and() .body("[0].copy", notNullValue()).and().body("$", hasSize(1)); givenTheBroker().get("/v2/service_instances/1234").then() .body("last_operation.state", equalTo("succeeded")).and() .statusCode(200); }
/** * Insert or replace a list of documents * @param documents * @return * @throws JSONException * @throws IOException */ public UploadDocumentsResult upsert(List<Matchmaker> documents) throws JSONException, IOException { UploadDocumentsRequest uploadDocumentsRequest = new UploadDocumentsRequest(); InputStream inputStream = null; UploadDocumentsResult result = null; try { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String jsonDocuments = ow.writeValueAsString(documents); inputStream = new ByteArrayInputStream(jsonDocuments.getBytes(StandardCharsets.UTF_8)); uploadDocumentsRequest .withDocuments(inputStream) .withContentLength((long) jsonDocuments.length()) .withContentType(ContentType.Applicationjson); result = domain.uploadDocuments(uploadDocumentsRequest); } catch (Exception e) { logger.error("", e); } finally { inputStream.close(); } return result; }
@Override public void processRecords(List<Record> arg0, IRecordProcessorCheckpointer arg1) { counter += arg0.size(); if (counter > target) { System.out.println("Received : " + counter + " records"); target += target; } Record rec; for(int i = 0; i < arg0.size(); i++) { rec = arg0.get(i); try { verifyRecord(rec.getData()); } catch (JSONException | UnsupportedEncodingException e) { e.printStackTrace(); } } }
private boolean verifyRecord(ByteBuffer buffer) throws JSONException, UnsupportedEncodingException { buffer.get(bytearray, 0, buffer.remaining()); JSONObject json = new JSONObject(new String(bytearray, "UTF-8")); String user = json.getString("user"); if (users.contains(user)) { MessageProxy proxy = MessageProxy.getInstance(); double x = json.getDouble("latitude"); double y = json.getDouble("longitude"); proxy.sendMesg(user + "," + json.getDouble("latitude") + "," + json.getDouble("longitude")); System.out.println(x + "," + y); if (coordsListener.verifyCoordinates(x, y)) { System.out.println("Matched! '" + user + "' is at (" + x + ", " + y + ")"); loader.put(user, System.currentTimeMillis(), x, y); return true; } } return false; }
@Override public void execute(Tuple input, BasicOutputCollector collector) { Record record = (Record)input.getValueByField(DefaultKinesisRecordScheme.FIELD_RECORD); ByteBuffer buffer = record.getData(); String data = null; try { data = decoder.decode(buffer).toString(); JSONObject jsonObject = new JSONObject(data); String referrer = jsonObject.getString("referrer"); int firstIndex = referrer.indexOf('.'); int nextIndex = referrer.indexOf('.',firstIndex+1); collector.emit(new Values(referrer.substring(firstIndex+1,nextIndex))); } catch (CharacterCodingException|JSONException|IllegalStateException e) { LOG.error("Exception when decoding record ", e); } }
private void queryRectangle(JSONObject requestObject, PrintWriter out) throws IOException, JSONException { GeoPoint minPoint = new GeoPoint(requestObject.getDouble("minLat"), requestObject.getDouble("minLng")); GeoPoint maxPoint = new GeoPoint(requestObject.getDouble("maxLat"), requestObject.getDouble("maxLng")); String filterUserId = requestObject.getString("filterUserId"); List<String> attributesToGet = new ArrayList<String>(); attributesToGet.add(config.getRangeKeyAttributeName()); attributesToGet.add(config.getGeoJsonAttributeName()); attributesToGet.add("title"); attributesToGet.add("userId"); QueryRectangleRequest queryRectangleRequest = new QueryRectangleRequest(minPoint, maxPoint); queryRectangleRequest.getQueryRequest().setAttributesToGet(attributesToGet); QueryRectangleResult queryRectangleResult = geoDataManager.queryRectangle(queryRectangleRequest); printGeoQueryResult(queryRectangleResult, out, filterUserId); }
private void queryRadius(JSONObject requestObject, PrintWriter out) throws IOException, JSONException { GeoPoint centerPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng")); double radiusInMeter = requestObject.getDouble("radiusInMeter"); String filterUserId = requestObject.getString("filterUserId"); List<String> attributesToGet = new ArrayList<String>(); attributesToGet.add(config.getRangeKeyAttributeName()); attributesToGet.add(config.getGeoJsonAttributeName()); attributesToGet.add("title"); attributesToGet.add("userId"); QueryRadiusRequest queryRadiusRequest = new QueryRadiusRequest(centerPoint, radiusInMeter); queryRadiusRequest.getQueryRequest().setAttributesToGet(attributesToGet); QueryRadiusResult queryRadiusResult = geoDataManager.queryRadius(queryRadiusRequest); printGeoQueryResult(queryRadiusResult, out, filterUserId); }
public List<String> getListField(String field) throws JSONException { List<String> rlt = null; if(fields.containsKey(field)) { String value = fields.get(field); JSONArray array = new JSONArray(value); if(array.length() > 0) { rlt = new ArrayList<String>(); for(int i = 0; i < array.length(); i++) { rlt.add(array.getString(i)); } } } return rlt; }
private JSONObject toJSON(AmazonCloudSearchAddRequest document) throws JSONException { JSONObject doc = new JSONObject(); doc.put("type", "add"); doc.put("id", document.id.toLowerCase()); doc.put("version", document.version); doc.put("lang", document.lang); JSONObject fields = new JSONObject(); for(Map.Entry<String, Object> entry : document.fields.entrySet()) { if(entry.getValue() instanceof Collection) { JSONArray array = new JSONArray(); Iterator i = ((Collection)entry.getValue()).iterator(); while(i.hasNext()) { array.put(i.next()); } fields.put(entry.getKey(), array); } else { fields.put(entry.getKey(), entry.getValue()); } } doc.put("fields", fields); return doc; }
private void createIntegration(Resource resource, Method method, JSONObject config) { if (config == null) { return; } try { final JSONObject integ = config.getJSONObject(resource.getPath()) .getJSONObject(method.getHttpMethod().toLowerCase()) .getJSONObject("integration"); IntegrationType type = IntegrationType.valueOf(integ.getString("type").toUpperCase()); LOG.info("Creating integration with type " + type); PutIntegrationInput input = new PutIntegrationInput() .withType(type) .withUri(integ.getString("uri")) .withCredentials(integ.optString("credentials")) .withHttpMethod(integ.optString("httpMethod")) .withRequestParameters(jsonObjectToHashMapString(integ.optJSONObject("requestParameters"))) .withRequestTemplates(jsonObjectToHashMapString(integ.optJSONObject("requestTemplates"))) .withCacheNamespace(integ.optString("cacheNamespace")) .withCacheKeyParameters(jsonObjectToListString(integ.optJSONArray("cacheKeyParameters"))); Integration integration = method.putIntegration(input); createIntegrationResponses(integration, integ.optJSONObject("responses")); } catch (JSONException e) { LOG.info(format("Skipping integration for method %s of %s: %s", method.getHttpMethod(), resource.getPath(), e)); } }
private List<String> jsonObjectToListString (JSONArray json) { if (json == null) { return null; } final List<String> list = new ArrayList<>(); for (int i = 0; i < json.length(); i++) { try { list.add(json.getString(i)); } catch (JSONException e) {} } return list; }
private String getAuthorizationTypeFromConfig(Resource resource, String method, JSONObject config) { if (config == null) { return "NONE"; } try { return config.getJSONObject(resource.getPath()) .getJSONObject(method.toLowerCase()) .getJSONObject("auth") .getString("type") .toUpperCase(); } catch (JSONException exception) { return "NONE"; } }
public static boolean isJSONValid(String test) { try { new JSONObject(test); } catch (JSONException ex) { try { new JSONArray(test); } catch (JSONException ex1) { return false; } } return true; }
@RequestMapping(value = "/api/sourceinstance", method = RequestMethod.GET) public ResponseEntity<String> getSourceInstance() throws JSONException { JSONObject resp = new JSONObject(); resp.put("sourceInstance", instanceService.getSourceInstanceId()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<String>(resp.toString(), headers, HttpStatus.OK); }
boolean runAllParagraph(String noteId, String hubMsg) { LOG.info("Running paragraph with noteId {}", noteId); try { JSONObject data = new JSONObject(hubMsg); if (data.equals(JSONObject.NULL) || !(data.get("data") instanceof JSONArray)) { LOG.error("Wrong \"data\" format for RUN_NOTEBOOK"); return false; } Client client = Client.getInstance(); if (client == null) { LOG.warn("Base client isn't initialized, returning"); return false; } Message zeppelinMsg = new Message(OP.RUN_PARAGRAPH); JSONArray paragraphs = data.getJSONArray("data"); String principal = data.getJSONObject("meta").getString("owner"); for (int i = 0; i < paragraphs.length(); i++) { if (!(paragraphs.get(i) instanceof JSONObject)) { LOG.warn("Wrong \"paragraph\" format for RUN_NOTEBOOK"); continue; } zeppelinMsg.data = gson.fromJson(paragraphs.getString(i), new TypeToken<Map<String, Object>>(){}.getType()); zeppelinMsg.principal = principal; zeppelinMsg.ticket = TicketContainer.instance.getTicket(principal); client.relayToZeppelin(zeppelinMsg, noteId); LOG.info("\nSending RUN_PARAGRAPH message to Zeppelin "); } } catch (JSONException e) { LOG.error("Failed to parse RUN_NOTEBOOK message from ZeppelinHub ", e); return false; } return true; }
public static String createAttributes(Integer numAttributes) throws JSONException { // Create between 1 and 10 ATTRIBUTES int random = generator.nextInt(10) + 1; JSONObject jsonObject = new JSONObject(); if (numAttributes == null) numAttributes = new Integer(random); for (int i = 0; i < numAttributes; i++) { jsonObject.put("key_" + i, UUID.randomUUID().toString()); } return jsonObject.toString(); }
public static String updateStringAttributes(List<String> attributes) throws JSONException { JSONObject jsonObject = new JSONObject(); for (String attribute : attributes) { jsonObject.put(attribute, UUID.randomUUID().toString()); } return jsonObject.toString(); }
public void test() throws JSONException, UnsupportedEncodingException { String str = "00001,35.65,139.65"; initialize("test"); ByteBuffer buffer = ByteBuffer.allocateDirect(128); buffer.put(str.getBytes()); buffer.flip(); verifyRecord(buffer); }
private void notifyComplete( final JSONObject jsonMessage ) throws JSONException { final String jobId = jsonMessage.getString( "jobId" ); final String inputKey = jsonMessage.getJSONObject( "input" ).getString( "key" ); final JSONArray jsonOutputList = jsonMessage.getJSONArray( "outputs" ); for ( int i = 0; i < jsonOutputList.length(); i++ ) { final JSONObject jsonOutput = jsonOutputList.getJSONObject( i ); final String outputKey = jsonOutput.getString( "key" ); final TranscodeEvent completedTranscodeEvent = new TranscodeEvent( jobId, new MovieId( inputKey ), new MovieId( outputKey ) ); this.transcodeEventHandler.onTranscodeComplete( completedTranscodeEvent ); } }
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } }
private HNUserItem createUserFromHNAPIResult(String result) { if(result == null || result.isEmpty()) return null; try { HNUserItem useritem = new HNUserItem(); JSONObject profile_jo = new JSONObject(result); useritem.setId(profile_jo.getString("id")); useritem.setCreated(profile_jo.getLong("created")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); sdf.setTimeZone(TimeZone.getTimeZone("America/Louisville")); useritem.setCreatedHumanReadable(sdf.format(profile_jo.getInt("karma")*1000)); useritem.setKarma(profile_jo.getInt("karma")); if(profile_jo.has("about")) useritem.setAbout(profile_jo.getString("about")); useritem.setDelay(profile_jo.getInt("delay")); if(profile_jo.has("submitted")) { JSONArray ja = profile_jo.getJSONArray("submitted"); HashSet<String> hs = new HashSet<String>(); if (ja != null) { int len = ja.length(); for (int i=0;i<len;i++) { hs.add(ja.get(i).toString()); } useritem.setSubmitted(hs); } } return useritem; } catch (JSONException e) { e.printStackTrace(); return null; } }
private void emit(Map<Object, Long> counts, int actualWindowLengthInSeconds) { for (Entry<Object, Long> entry : counts.entrySet()) { String referrer = entry.getKey().toString(); Long count = entry.getValue(); long currentEPOCH = java.lang.System.currentTimeMillis(); if(jedis.llen("l:"+referrer) > 100 ) { String lastEPOCH = jedis.lpop("l:"+referrer); jedis.hdel("h:"+referrer,lastEPOCH); } jedis.hset("h:" + referrer, String.valueOf(currentEPOCH), count.toString()); jedis.rpush("l:"+referrer,String.valueOf(currentEPOCH)); JSONObject msg = new JSONObject(); try { msg.put("name", referrer); msg.put("time", currentEPOCH); msg.put("count", count); } catch (JSONException e) { LOG.error("Exception when creating JSON Message", e); } jedis.publish("pubsubCounters",msg.toString()); } }
@Override public void run() { try { AmazonIndex amazonIndex = new AmazonIndex("pricing.us-east-1.amazonaws.com", "/offers/v1.0/aws/index.json"); GoogleCloud googleCloud = new GoogleCloud("www.cloudpricingcalculator.appspot.com","/static/data/pricelist.json"); } catch (JSONException | IOException ex) { Logger.getLogger(PricingGetterService.class.getName()).log(Level.SEVERE, null, ex); } }
private List getUserList(SqlSession session) throws IOException, ServletException, JSONException { UserExample example = new UserExample(); io.starter.model.UserExample.Criteria criteria = example.createCriteria(); example.setDistinct(true); List results = session.selectList( "io.starter.dao.UserMapper.selectByExample", example); // return the JSON result return results; }
private void putPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException { GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng")); AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(requestObject.getString("s3-photo-url")); AttributeValue titleAttributeValue = new AttributeValue().withS(requestObject.getString("title")); AttributeValue userIdAttributeValue = new AttributeValue().withS(requestObject.getString("userId")); PutPointRequest putPointRequest = new PutPointRequest(geoPoint, rangeKeyAttributeValue); putPointRequest.getPutItemRequest().addItemEntry("title", titleAttributeValue); putPointRequest.getPutItemRequest().addItemEntry("userId", userIdAttributeValue); PutPointResult putPointResult = geoDataManager.putPoint(putPointRequest); printPutPointResult(putPointResult, out); }
private void getPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException { GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng")); AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(requestObject.getString("rangeKey")); GetPointRequest getPointRequest = new GetPointRequest(geoPoint, rangeKeyAttributeValue); GetPointResult getPointResult = geoDataManager.getPoint(getPointRequest); printGetPointRequest(getPointResult, out); }
private void deletePoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException { GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng")); AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(requestObject.getString("rangeKey")); DeletePointRequest deletePointRequest = new DeletePointRequest(geoPoint, rangeKeyAttributeValue); DeletePointResult deletePointResult = geoDataManager.deletePoint(deletePointRequest); printDeletePointResult(deletePointResult, out); }
/** * Validates a JSON string representing JSON object. * @param text Text to validate * @return True, if text is a valid JSON object. */ private boolean validJSONObject(final String text) { boolean result = true; try { new JSONObject(text); } catch (final JSONException ex) { result = false; } return result; }
/** * Validates a JSON string representing JSON array. * @param text Text to validate * @return True, if text is a valid JSON array. */ private boolean validJSONArray(final String text) { boolean result = true; try { new JSONArray(text); } catch (final JSONException ex) { result = false; } return result; }
private Object toJSON(AmazonCloudSearchDeleteRequest document) throws JSONException { JSONObject doc = new JSONObject(); doc.put("type", "delete"); doc.put("id", document.id.toLowerCase()); doc.put("version", document.version); return doc; }
private AmazonCloudSearchResult fromJSON(String responseBody) throws JSONException { AmazonCloudSearchResult result = new AmazonCloudSearchResult(); JSONObject root = new JSONObject(responseBody); JSONObject status = root.getJSONObject("status"); if(status != null) { result.rid = status.getString("rid"); result.time = status.getLong("time-ms"); } JSONObject hits = root.getJSONObject("hits"); if(hits != null) { result.found = hits.getInt("found"); result.start = hits.getInt("start"); if(result.found > 0) { JSONArray hitArray = hits.getJSONArray("hit"); if(hitArray != null) { for(int i = 0; i < hitArray.length(); i++) { JSONObject row = hitArray.getJSONObject(i); Hit hit = new Hit(); hit.id = row.getString("id"); JSONObject fields = row.getJSONObject("fields"); String[] names = JSONObject.getNames(fields); for(String name : names) { if(hit.fields == null) { hit.fields = new HashMap<String, String>(); } hit.fields.put(name, fields.getString(name)); } if(result.hits == null) { result.hits = new ArrayList<Hit>(); } result.hits.add(hit); } } } } return result; }
private void putPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException { GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng")); AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(UUID.randomUUID().toString()); AttributeValue schoolNameKeyAttributeValue = new AttributeValue().withS(requestObject.getString("schoolName")); PutPointRequest putPointRequest = new PutPointRequest(geoPoint, rangeKeyAttributeValue); putPointRequest.getPutItemRequest().addItemEntry("schoolName", schoolNameKeyAttributeValue); PutPointResult putPointResult = geoDataManager.putPoint(putPointRequest); printPutPointResult(putPointResult, out); }