play.libs.Json Java Examples
The following examples show how to use
play.libs.Json.
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: AbstractIndexer.java From samantha with MIT License | 6 votes |
public void index(RequestContext requestContext) { JsonNode reqBody = requestContext.getRequestBody(); EntityDAO entityDAO = EntityDAOUtilities.getEntityDAO(daoConfigs, requestContext, reqBody.get(daoConfigKey), injector); ArrayNode toIndex = Json.newArray(); ExpandedEntityDAO expandedEntityDAO = new ExpandedEntityDAO(expanders, entityDAO, requestContext); while (expandedEntityDAO.hasNextEntity()) { toIndex.add(expandedEntityDAO.getNextEntity()); if (toIndex.size() >= batchSize) { index(toIndex, requestContext); notifyDataSubscribers(toIndex, requestContext); toIndex.removeAll(); } } if (toIndex.size() > 0) { index(toIndex, requestContext); notifyDataSubscribers(toIndex, requestContext); } expandedEntityDAO.close(); entityDAO.close(); }
Example #2
Source File: UserSkillControllerTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testAddSkill() { Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.USER_ID, "{userId} uuiuhcf784508 8y8c79-fhh"); innerMap.put(JsonKey.SKILL_NAME, Arrays.asList("C", "C++")); innerMap.put(JsonKey.ENDORSED_USER_ID, "uuiuhcf784508"); requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); Http.RequestBuilder req = new Http.RequestBuilder().bodyJson(json).uri("/v1/user/skill/add").method("POST"); //req.headers(headerMap); Result result = Helpers.route(application,req); assertEquals(200, result.status()); }
Example #3
Source File: FlagController.java From NationStatesPlusPlus with MIT License | 6 votes |
public Result regionFlags(String regions) throws SQLException { String[] regionNames = regions.split(","); Map<String, String> json = new HashMap<String, String>(regionNames.length); Connection conn = null; try { conn = getConnection(); for (String region : regionNames) { json.put(region, Utils.getRegionFlag(region, conn)); } } finally { DbUtils.closeQuietly(conn); } Result result = Utils.handleDefaultGetHeaders(request(), response(), String.valueOf(json.hashCode()), "21600"); if (result != null) { return result; } return ok(Json.toJson(json)).as("application/json"); }
Example #4
Source File: CSVFileIndexer.java From samantha with MIT License | 6 votes |
public void index(JsonNode documents, RequestContext requestContext) { JsonNode reqBody = requestContext.getRequestBody(); String operation = JsonHelpers.getOptionalString(reqBody, ConfigKey.DATA_OPERATION.get(), DataOperation.INSERT.get()); if (operation.equals(DataOperation.INSERT.get()) || operation.equals(DataOperation.UPSERT.get())) { JsonNode arr; if (!documents.isArray()) { ArrayNode tmp = Json.newArray(); tmp.add(documents); arr = tmp; } else { arr = documents; } int timestamp = (int) (System.currentTimeMillis() / 1000); for (JsonNode document : arr) { if (document.has(timestampField)) { timestamp = document.get(timestampField).asInt(); } else { logger.warn("Time field {} is not present in the entity to be indexed.", timestampField); } dataService.writeCSV(indexType, document, dataFields, timestamp); } } else { throw new BadRequestException("Data operation " + operation + " is not supported"); } }
Example #5
Source File: StorageTest.java From remote-monitoring-services-java with MIT License | 6 votes |
@Test(timeout = StorageTest.TIMEOUT) @Category({UnitTest.class}) public void getDeviceGroupsAsyncTest() throws BaseException, ExecutionException, InterruptedException { String groupId = rand.NextString(); String displayName = rand.NextString(); Iterable<DeviceGroupCondition> conditions = null; String etag = rand.NextString(); ValueApiModel model = new ValueApiModel(groupId, null, etag, null); DeviceGroup group = new DeviceGroup(); group.setDisplayName(displayName); group.setConditions(conditions); model.setData(Json.stringify(Json.toJson(group))); Mockito.when(mockClient.getAsync(Mockito.any(String.class), Mockito.any(String.class))). thenReturn(CompletableFuture.supplyAsync(() -> model)); DeviceGroup result = storage.getDeviceGroupAsync(groupId).toCompletableFuture().get(); assertEquals(result.getDisplayName(), displayName); assertEquals(result.getConditions(), conditions); }
Example #6
Source File: TestUtilities.java From samantha with MIT License | 6 votes |
static public void setUpUserMultiTypeSequence(List<ObjectNode> entities) { ObjectNode entity1 = Json.newObject(); entity1.put("user", "123"); entity1.put("item", "10|2|10|7|4|5"); entity1.put("click", "1|0|0|0|0|1"); entity1.put("rating", "0|0|1|0|0|1"); entity1.put("wishlist", "1|0|0|1|0|1"); entity1.put("tstamp", "1|2|3|4|5|6"); entities.add(entity1); ObjectNode entity2 = Json.newObject(); entity2.put("user", "455"); entity2.put("item", "5"); entity2.put("click", "0"); entity2.put("rating", "1"); entity2.put("wishlist", "0"); entity2.put("tstamp", "1"); entities.add(entity2); }
Example #7
Source File: StorageTest.java From remote-monitoring-services-java with MIT License | 6 votes |
@Test(timeout = StorageTest.TIMEOUT) @Category({UnitTest.class}) public void setThemeAsyncTest() throws BaseException, ExecutionException, InterruptedException { String name = rand.NextString(); String description = rand.NextString(); String jsonData = String.format("{\"Name\":\"%s\",\"Description\":\"%s\"}", name, description); Object theme = Json.fromJson(Json.parse(jsonData), Object.class); ValueApiModel model = new ValueApiModel(); model.setData(jsonData); Mockito.when(mockClient.updateAsync(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))). thenReturn(CompletableFuture.supplyAsync(() -> model)); Object result = storage.setThemeAsync(theme).toCompletableFuture().get(); JsonNode node = Json.toJson(result); assertEquals(node.get("Name").asText(), name); assertEquals(node.get("Description").asText(), description); assertEquals(node.get("AzureMapsKey").asText(), azureMapsKey); }
Example #8
Source File: RMBController.java From NationStatesPlusPlus with MIT License | 6 votes |
@Deprecated public static JsonNode calculatePostRatings(Connection conn, int rmbPost) throws SQLException { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); PreparedStatement select = conn.prepareStatement("SELECT nation_name, rating_type FROM assembly.rmb_ratings WHERE rmb_post = ?"); select.setInt(1, rmbPost); ResultSet result = select.executeQuery(); while(result.next()) { Map<String, String> ratings = new HashMap<String, String>(2); ratings.put("nation", result.getString(1)); ratings.put("type", String.valueOf(result.getInt(2))); ratings.put("rmb_post", String.valueOf(rmbPost)); list.add(ratings); } DbUtils.closeQuietly(result); DbUtils.closeQuietly(select); return Json.toJson(list); }
Example #9
Source File: NodeController.java From ground with Apache License 2.0 | 6 votes |
@BodyParser.Of(BodyParser.Json.class) public final CompletionStage<Result> addNodeVersion() { return CompletableFuture.supplyAsync( () -> { JsonNode json = request().body().asJson(); List<Long> parentIds = GroundUtils.getListFromJson(json, "parentIds"); ((ObjectNode) json).remove("parentIds"); NodeVersion nodeVersion = Json.fromJson(json, NodeVersion.class); try { nodeVersion = this.postgresNodeVersionDao.create(nodeVersion, parentIds); } catch (GroundException e) { e.printStackTrace(); throw new CompletionException(e); } return Json.toJson(nodeVersion); }, PostgresUtils.getDbSourceHttpContext(this.actorSystem)) .thenApply(Results::created) .exceptionally(e -> GroundUtils.handleException(e, request())); }
Example #10
Source File: PostgresItemDao.java From ground with Apache License 2.0 | 6 votes |
protected T retrieve(String sql, Object field) throws GroundException { JsonNode json = Json.parse(PostgresUtils.executeQueryToJson(dbSource, sql)); if (json.size() == 0) { throw new GroundException(ExceptionType.ITEM_NOT_FOUND, this.getType().getSimpleName(), field.toString()); } Class<T> type = this.getType(); JsonNode itemJson = json.get(0); long id = itemJson.get("itemId").asLong(); String name = itemJson.get("name").asText(); String sourceKey = itemJson.get("sourceKey").asText(); Object[] args = {id, name, sourceKey, this.postgresTagDao.retrieveFromDatabaseByItemId(id)}; Constructor<T> constructor; try { constructor = type.getConstructor(long.class, String.class, String.class, Map.class); return constructor.newInstance(args); } catch (Exception e) { throw new GroundException(ExceptionType.OTHER, String.format("Catastrophic failure: Unable to instantiate Item.\n%s: %s.", e.getClass().getName(), e.getMessage())); } }
Example #11
Source File: LineageGraphController.java From ground with Apache License 2.0 | 6 votes |
public final CompletionStage<Result> getLineageGraphVersion(Long id) { return CompletableFuture.supplyAsync( () -> { try { return this.cache.getOrElse( "lineage_graph_versions." + id, () -> Json.toJson(this.postgresLineageGraphVersionDao.retrieveFromDatabase(id)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(actorSystem)) .thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
Example #12
Source File: EdgeController.java From ground with Apache License 2.0 | 6 votes |
public final CompletionStage<Result> getLatest(String sourceKey) { return CompletableFuture.supplyAsync( () -> { try { return this.cache.getOrElse( "edge_leaves." + sourceKey, () -> Json.toJson(this.postgresEdgeDao.getLeaves(sourceKey)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(actorSystem)) .thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
Example #13
Source File: SQLBasedIndexer.java From samantha with MIT License | 6 votes |
public ObjectNode getIndexedDataDAOConfig(RequestContext requestContext) { ObjectNode ret = Json.newObject(); ret.put(daoNameKey, daoName); if (cacheJsonFile == null) { ret.put("retrieverName", retrieverName); ret.put("setCursorKey", setCursorKey); } else { try { BufferedWriter writer = new BufferedWriter(new FileWriter(cacheJsonFile)); SamanthaConfigService configService = injector .instanceOf(SamanthaConfigService.class); EntityDAO dao = new RetrieverBasedDAO(retrieverName, configService, requestContext); while (dao.hasNextEntity()) { IndexerUtilities.writeJson(dao.getNextEntity(), writer); } dao.close(); writer.close(); } catch (IOException e) { throw new BadRequestException(e); } ret.put(filePathKey, cacheJsonFile); ret.put(separatorKey, "\t"); } return ret; }
Example #14
Source File: EmailServiceControllerTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testsendMail() { PowerMockito.mockStatic(RequestInterceptor.class); when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.ORG_NAME, "org123"); innerMap.put(JsonKey.SUBJECT, "subject"); innerMap.put(JsonKey.BODY, "body"); List<String> recepeintsEmails = new ArrayList<>(); recepeintsEmails.add("abc"); List<String> receipeintUserIds = new ArrayList<>(); receipeintUserIds.add("user001"); innerMap.put("recipientEmails", recepeintsEmails); innerMap.put("recipientUserIds", receipeintUserIds); requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/notification/email").method("POST"); //req.headers(headerMap); Result result = Helpers.route(application,req); assertEquals(200, result.status()); }
Example #15
Source File: BadgeAssertionControllerTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test @Ignore public void getAssertionListTest() { PowerMockito.mockStatic(RequestInterceptor.class); when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); List<String> assertionList = new ArrayList<String>(); assertionList.add("assertionId"); innerMap.put(JsonKey.FILTERS, assertionList); Map<String, Object> dataMap = new HashMap<>(); requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/search").method("POST"); Result result = Helpers.route(application, req); assertEquals(200, result.status()); }
Example #16
Source File: DbOperationControllerTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testgetMetrics() { PowerMockito.mockStatic(RequestInterceptor.class); when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(ENTITY_NAME, entityName); List<String> requiredFields = new ArrayList<>(); requiredFields.add("userid"); innerMap.put(REQUIRED_FIELDS, requiredFields); Map<String, Object> filters = new HashMap<>(); filters.put(JsonKey.USER_ID, "usergt78y4ry85464"); innerMap.put(JsonKey.FILTERS, filters); innerMap.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/metrics").method("POST"); //req.headers(headerMap); Result result = Helpers.route(application,req); assertEquals(200, result.status()); }
Example #17
Source File: GroupController.java From htwplus with MIT License | 6 votes |
/** * Get the temporary avatar image * * @param id * @return */ public Result getTempAvatar(Long id) { ObjectNode result = Json.newObject(); Group group = groupManager.findById(id); if (group == null) { return notFound(); } if (!Secured.editGroup(group)) { result.put("error", "Not allowed."); return forbidden(result); } File tempAvatar = avatarManager.getTempAvatar(group.id); if (tempAvatar != null) { return ok(tempAvatar); } else { return notFound(); } }
Example #18
Source File: EmailActionExecutor.java From remote-monitoring-services-java with MIT License | 6 votes |
private String generatePayload(EmailActionServiceModel emailAction, AsaAlarmApiModel alarm) { DateTime alarmDate = new DateTime(Long.parseLong(alarm.getDateCreated())); String emailBody = this.emailTemplate.replace("${subject}", emailAction.getSubject()) .replace("${notes}", emailAction.getNotes()) .replace("${alarmDate}", alarmDate.toString(DATE_FORMAT_STRING)) .replace("${ruleId}", alarm.getRuleId()) .replace("${ruleDescription}", alarm.getRuleDescription()) .replace("${ruleSeverity}", alarm.getRuleSeverity()) .replace("${deviceId}", alarm.getDeviceId()) .replace("${alarmUrl}", this.generateRuleDetailUrl(alarm.getRuleId())); EmailActionPayload payload = new EmailActionPayload( emailAction.getRecipients(), emailAction.getSubject(), emailBody ); return Json.stringify(Json.toJson(payload)); }
Example #19
Source File: GraphController.java From ground with Apache License 2.0 | 6 votes |
@BodyParser.Of(BodyParser.Json.class) public final CompletionStage<Result> addGraph() { return CompletableFuture.supplyAsync( () -> { JsonNode json = request().body().asJson(); Graph graph = Json.fromJson(json, Graph.class); try { graph = this.postgresGraphDao.create(graph); } catch (GroundException e) { throw new CompletionException(e); } return Json.toJson(graph); }, PostgresUtils.getDbSourceHttpContext(actorSystem)) .thenApply(Results::created) .exceptionally(e -> GroundUtils.handleException(e, request())); }
Example #20
Source File: ESBasedIndexer.java From samantha with MIT License | 6 votes |
private void bulkIndex(String indexType, JsonNode data) { if (data.size() == 0) { return; } if (uniqueFields.size() > 0) { Set<String> keys = new HashSet<>(); ArrayNode uniqued = Json.newArray(); for (JsonNode point : data) { String key = FeatureExtractorUtilities.composeConcatenatedKey(point, dataFields); if (!keys.contains(key)) { keys.add(key); uniqued.add(point); } } data = uniqued; } BulkResponse resp = elasticSearchService.bulkIndex(elasticSearchIndex, indexType, data); if (resp.hasFailures()) { throw new BadRequestException(resp.buildFailureMessage()); } }
Example #21
Source File: StructureController.java From ground with Apache License 2.0 | 6 votes |
public final CompletionStage<Result> getHistory(String sourceKey) { return CompletableFuture.supplyAsync( () -> { try { return this.cache.getOrElse( "structure_history." + sourceKey, () -> Json.toJson(this.postgresStructureDao.getHistory(sourceKey)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(actorSystem)) .thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
Example #22
Source File: LineageGraphController.java From ground with Apache License 2.0 | 6 votes |
public final CompletionStage<Result> getHistory(String sourceKey) { return CompletableFuture.supplyAsync( () -> { try { return this.cache.getOrElse( "lineage_graph_history." + sourceKey, () -> Json.toJson(this.postgresLineageGraphDao.getHistory(sourceKey)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(actorSystem)) .thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
Example #23
Source File: DbOperationControllerTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testupdate() { PowerMockito.mockStatic(RequestInterceptor.class); when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(ENTITY_NAME, entityName); innerMap.put(INDEXED, true); Map<String, Object> payLoad = new HashMap<>(); payLoad.put(JsonKey.USER_ID, "usergt78y4ry85464"); payLoad.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); innerMap.put(PAYLOAD, payLoad); requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/update").method("POST"); /*//req.headers(headerMap);*/ Result result = Helpers.route(application,req); assertEquals(200, result.status()); }
Example #24
Source File: StudentController.java From tutorials with MIT License | 6 votes |
public CompletionStage<Result> update(Http.Request request) { JsonNode json = request.body().asJson(); return supplyAsync(() -> { if (json == null) { return badRequest(Util.createResponse("Expecting Json data", false)); } Optional<Student> studentOptional = studentStore.updateStudent(Json.fromJson(json, Student.class)); return studentOptional.map(student -> { if (student == null) { return notFound(Util.createResponse("Student not found", false)); } JsonNode jsonObject = Json.toJson(student); return ok(Util.createResponse(jsonObject, true)); }).orElse(internalServerError(Util.createResponse("Could not create data.", false))); }, ec.current()); }
Example #25
Source File: FeatureSupportRetrieverConfig.java From samantha with MIT License | 6 votes |
public Retriever getRetriever(RequestContext requestContext) { FeatureSupportModelManager manager = new FeatureSupportModelManager(modelName, modelFile, injector); IndexedVectorModel model = (IndexedVectorModel) manager.manage(requestContext); List<ObjectNode> results = new ArrayList<>(); int size = model.getIndexSize(); for (int i=0; i<size; i++) { ObjectNode one = Json.newObject(); Map<String, String> keys = FeatureExtractorUtilities.decomposeKey(model.getKeyByIndex(i)); RealVector vector = model.getIndexVector(i); one.put(supportAttr, vector.getEntry(0)); for (String attr : itemAttrs) { one.put(attr, keys.get(attr)); } results.add(one); } return new PrecomputedRetriever(results, config, requestContext, injector); }
Example #26
Source File: PubSubTest.java From WAMPlay with MIT License | 6 votes |
@Test public void serverPublishTest(){ WAMPlayServer.addTopic(SIMPLE); subscribe(SIMPLE, client); subscribe(SIMPLE, client2); List<String> eligible = new ArrayList<String>(); eligible.add(client2.getSessionID()); WAMPlayServer.publishEligible(SIMPLE, Json.toJson(HELLO), eligible); assertThat(client.lastMessage().toString()).doesNotContain(HELLO); assertThat(client2.lastMessage().toString()).contains(HELLO); WAMPlayServer.publish(SIMPLE, Json.toJson(HELLO)); assertThat(client.lastMessage().toString()).contains(HELLO); assertThat(client.lastMessage().isArray()).isTrue(); }
Example #27
Source File: LineageGraphController.java From ground with Apache License 2.0 | 6 votes |
@BodyParser.Of(BodyParser.Json.class) public final CompletionStage<Result> createLineageGraph() { return CompletableFuture.supplyAsync( () -> { JsonNode json = request().body().asJson(); LineageGraph lineageGraph = Json.fromJson(json, LineageGraph.class); try { lineageGraph = this.postgresLineageGraphDao.create(lineageGraph); } catch (GroundException e) { throw new CompletionException(e); } return Json.toJson(lineageGraph); }, PostgresUtils.getDbSourceHttpContext(this.actorSystem)) .thenApply(Results::created) .exceptionally(e -> GroundUtils.handleException(e, request())); }
Example #28
Source File: GeoLocationControllerTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testupdateGeoLocation() { PowerMockito.mockStatic(RequestInterceptor.class); when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.ROOT_ORG_ID, "org123"); innerMap.put(JsonKey.ID,"123"); requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/location/update").method("PATCH"); //req.headers(headerMap); Result result = Helpers.route(application,req); assertEquals(200, result.status()); }
Example #29
Source File: PortfolioController.java From reactive-stock-trader with Apache License 2.0 | 6 votes |
public CompletionStage<Result> openPortfolio() { Form<OpenPortfolioForm> form = openPortfolioForm.bindFromRequest(); if (form.hasErrors()) { return CompletableFuture.completedFuture(badRequest(form.errorsAsJson())); } else { OpenPortfolioDetails openRequest = form.get().toRequest(); return portfolioService .openPortfolio() .invoke(openRequest) .thenApply(portfolioId -> { val jsonResult = Json.newObject() .put("portfolioId", portfolioId.getId()); return Results.created(jsonResult); }); } }
Example #30
Source File: WorldAssemblyController.java From NationStatesPlusPlus with MIT License | 6 votes |
public Result getWADelegates() throws SQLException { List<String> delegates = new ArrayList<String>(); Connection conn = null; try { conn = getConnection(); PreparedStatement select = conn.prepareStatement("SELECT delegate FROM assembly.region WHERE delegate <> \"0\" AND alive = 1"); ResultSet set = select.executeQuery(); while(set.next()) { delegates.add(set.getString(1)); } DbUtils.closeQuietly(set); DbUtils.closeQuietly(select); } finally { DbUtils.closeQuietly(conn); } Result result = Utils.handleDefaultGetHeaders(request(), response(), String.valueOf(delegates.hashCode())); if (result != null) { return result; } return ok(Json.toJson(delegates)).as("application/json"); }