Java Code Examples for play.libs.Json#fromJson()

The following examples show how to use play.libs.Json#fromJson() . 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: ActionDeserializer.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Deserialize JSON node based on ActionType
 *
 * @return deserialize value if ActionType is supported, otherwise return null value.
 * @throws IOException
 */
@Override
public IActionServiceModel deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    JsonNode rootNode = parser.getCodec().readTree(parser);
    JsonNode typeNode = rootNode.get(TYPE_NODE_NAME);
    if (typeNode == null || StringUtil.isNullOrEmpty(typeNode.asText())) return null;
    ActionType actionType = ActionType.from(typeNode.asText());

    IActionServiceModel action = null;
    switch (actionType) {
        case Email:
            HashMap parameters = Json.fromJson(rootNode.get(PARAMETERS_NODE_NAME), HashMap.class);
            try {
                action = new EmailActionServiceModel(parameters);
            } catch (InvalidInputException e) {
                this.log.error("Cannot deserialize email action parameters");
            }
            break;
        default:
            this.log.error("Unknown action type: " + actionType.toString());
    }

    return action;
}
 
Example 2
Source File: StorageTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@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 3
Source File: PostgresLineageGraphVersionDao.java    From ground with Apache License 2.0 6 votes vote down vote up
@Override
public LineageGraphVersion retrieveFromDatabase(long id) throws GroundException {
  String sql = String.format(SqlConstants.SELECT_STAR_BY_ID, "lineage_graph_version", id);
  JsonNode json = Json.parse(PostgresUtils.executeQueryToJson(dbSource, sql));

  if (json.size() == 0) {
    throw new GroundException(ExceptionType.VERSION_NOT_FOUND, this.getType().getSimpleName(), String.format("%d", id));
  }

  LineageGraphVersion lineageGraphVersion = Json.fromJson(json.get(0), LineageGraphVersion.class);

  List<Long> edgeIds = new ArrayList<>();
  sql = String.format(SqlConstants.SELECT_LINEAGE_GRAPH_VERSION_EDGES, id);

  JsonNode edgeJson = Json.parse(PostgresUtils.executeQueryToJson(dbSource, sql));
  for (JsonNode edge : edgeJson) {
    edgeIds.add(edge.get("lineageEdgeVersionId").asLong());
  }

  RichVersion richVersion = super.retrieveFromDatabase(id);
  return new LineageGraphVersion(id, richVersion.getTags(), richVersion.getStructureVersionId(), richVersion.getReference(),
                                  richVersion.getParameters(), lineageGraphVersion.getLineageGraphId(), edgeIds);
}
 
Example 4
Source File: DeviceGroupControllerTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = 100000)
@Category({UnitTest.class})
public void creatAsyncTest() throws Exception {
    String groupId = rand.NextString();
    String displayName = rand.NextString();
    Iterable<DeviceGroupCondition> conditions = Json.fromJson(Json.parse(condition), new ArrayList<DeviceGroupCondition>().getClass());
    String etag = rand.NextString();
    DeviceGroup model = new DeviceGroup(groupId, displayName, conditions, etag);
    Mockito.when(mockStorage.createDeviceGroupAsync(Mockito.any(DeviceGroup.class)))
            .thenReturn(CompletableFuture.supplyAsync(() -> model));
    controller = new DeviceGroupController(mockStorage);
    TestUtils.setRequest(String.format("{\"DisplayName\":\"%s\",\"Conditions\":%s}", displayName, condition));
    String resultStr = TestUtils.getString(controller.createAsync().toCompletableFuture().get());
    DeviceGroupApiModel result = Json.fromJson(Json.parse(resultStr), DeviceGroupApiModel.class);
    assertEquals(result.getId(), groupId);
    assertEquals(result.getDisplayName(), displayName);
    assertEquals(Json.stringify(Json.toJson(result.getConditions())), Json.stringify(Json.toJson(conditions)));
    assertEquals(result.getETag(), etag);
}
 
Example 5
Source File: AlarmsController.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * @return One alert.
 */
@Authorize("UpdateAlarms")
public Result patch(String id) throws Exception {

    AlarmStatus alarm = Json.fromJson(request().body().asJson(), AlarmStatus.class);

    // validate input
    if (!(alarm.status.equalsIgnoreCase("open") ||
          alarm.status.equalsIgnoreCase("closed") ||
          alarm.status.equalsIgnoreCase("acknowledged"))) {

        return badRequest(
            "Status must be `open`, acknowledged`, or `closed`. " +
                "Value provided: " + alarm.status);
    }

    return ok(toJson(new AlarmApiModel(this.alarms.update(id, alarm.status))));
}
 
Example 6
Source File: StorageWriteLock.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
public CompletionStage<Optional<Boolean>> tryLockAsync() throws
        ResourceOutOfDateException, ExternalDependencyException, ConflictingResourceException {
    if (this.lastETag != null) {
        throw new ResourceOutOfDateException("Lock has already been acquired");
    }

    ValueApiModel model = this.getLock();

    if (!this.testLockFunc.apply(model)) {
        return CompletableFuture.supplyAsync(() -> Optional.of(false));
    }
    try {
        this.lastValue = model == null ? type.newInstance() : Json.fromJson(Json.parse(model.getData()), type);
    } catch (InstantiationException | IllegalAccessException e) {
        String message = String.format("Lock failed when creating new instance type " + type.getTypeName());
        log.error(message, e);
        throw new ExternalDependencyException(message);
    }
    this.setLockFlagAction.accept(this.lastValue, true);

    return updateLock(model);
}
 
Example 7
Source File: ItemsTest.java    From pfe-samples with MIT License 5 votes vote down vote up
@Test
public void getItem() {
    Result response = route(jsonRequest(routes.Items.create(), itemCreate));
    Item createdItem = Json.fromJson(Json.parse(contentAsString(response)), Item.class);
    Result response2 = route(jsonRequest(routes.Items.details(createdItem.id)));
    assertThat(status(response)).isEqualTo(OK);
    Item item = Json.fromJson(Json.parse(contentAsString(response2)), Item.class);
    assertThat(item.name).isEqualTo("Play Framework Essentials");
    assertThat(item.price).isEqualTo(42.0);
}
 
Example 8
Source File: ItemsTest.java    From pfe-samples with MIT License 5 votes vote down vote up
@Test
public void createItem() {
    Result response = route(jsonRequest(routes.Items.create(), itemCreate));
    assertThat(status(response)).isEqualTo(OK);
    Item item = Json.fromJson(Json.parse(contentAsString(response)), Item.class);
    assertThat(item.name).isEqualTo("Play Framework Essentials");
    assertThat(item.price).isEqualTo(42.0);
    assertThat(item.id).isNotNull();
}
 
Example 9
Source File: ItemsTest.java    From pfe-samples with MIT License 5 votes vote down vote up
@Test
public void updateItem() {
    Result response = route(jsonRequest(routes.Items.create(), itemCreate));
    Item createdItem = Json.fromJson(Json.parse(contentAsString(response)), Item.class);
    Items.CreateItem update = new Items.CreateItem();
    update.name = createdItem.name;
    update.price = 10.0;
    Result response2 = route(jsonRequest(routes.Items.update(createdItem.id), Json.toJson(update)));
    assertThat(status(response)).isEqualTo(OK);
    Item item = Json.fromJson(Json.parse(contentAsString(response2)), Item.class);
    assertThat(item.name).isEqualTo("Play Framework Essentials");
    assertThat(item.price).isEqualTo(10.0);
}
 
Example 10
Source File: PostgresLineageEdgeVersionDao.java    From ground with Apache License 2.0 5 votes vote down vote up
@Override
public LineageEdgeVersion retrieveFromDatabase(long id) throws GroundException {
  String sql = String.format(SqlConstants.SELECT_STAR_BY_ID, "lineage_edge_version", id);
  JsonNode json = Json.parse(PostgresUtils.executeQueryToJson(dbSource, sql));

  if (json.size() == 0) {
    throw new GroundException(ExceptionType.VERSION_NOT_FOUND, this.getType().getSimpleName(), String.format("%d", id));
  }

  LineageEdgeVersion lineageEdgeVersion = Json.fromJson(json.get(0), LineageEdgeVersion.class);
  RichVersion richVersion = super.retrieveFromDatabase(id);

  return new LineageEdgeVersion(id, richVersion, lineageEdgeVersion);
}
 
Example 11
Source File: ValuesControllerTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = 100000)
public void createTest() throws Exception {
    String testValue = keyGenerator.generate();
    String testKey = keyGenerator.generate();
    ValueServiceModel model = new ValueServiceModel(testKey, testValue);
    Mockito.when(mockStorage.create(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(ValueServiceModel.class)))
            .thenReturn(model);
    TestUtils.setRequest(String.format("{\"Data\":\"%s\"}", keyGenerator.generate(), keyGenerator.generate()));
    String resultJson = TestUtils.getString(controller.put(keyGenerator.generate(), keyGenerator.generate()));
    ValueServiceModel result = Json.fromJson(Json.parse(resultJson), ValueServiceModel.class);
    assertEquals(result.Data, testValue);
}
 
Example 12
Source File: SolutionSettingsController.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Authorize("ReadAll")
public CompletionStage<Result> setThemeAsync() throws BaseException {
    Object theme = new Object();
    JsonNode node = request().body().asJson();
    if (node != null) {
        theme = Json.fromJson(node, Object.class);
    }
    return storage.setThemeAsync(theme)
            .thenApply(result -> ok(toJson(result)));
}
 
Example 13
Source File: ItemsTest.java    From pfe-samples with MIT License 5 votes vote down vote up
@Test
public void deleteItem() {
    Result response = route(jsonRequest(routes.Items.create(), itemCreate));
    Item createdItem = Json.fromJson(Json.parse(contentAsString(response)), Item.class);
    Result response2 = route(jsonRequest(routes.Items.delete(createdItem.id)));
    assertThat(status(response2)).isEqualTo(OK);
    assertThat(status(route(jsonRequest(routes.Items.details(createdItem.id))))).isEqualTo(NOT_FOUND);
}
 
Example 14
Source File: ValuesControllerTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = 100000)
public void getTest() throws Exception {
    String testKey = keyGenerator.generate();
    String testValue = keyGenerator.generate();
    ValueServiceModel model = new ValueServiceModel(testKey, testValue);
    Mockito.when(mockStorage.get(Mockito.any(String.class), Mockito.any(String.class)))
            .thenReturn(model);
    String resultJson = TestUtils.getString(controller.get(keyGenerator.generate(), keyGenerator.generate()));
    ValueServiceModel result = Json.fromJson(Json.parse(resultJson), ValueServiceModel.class);
    assertEquals(result.Data, testValue);
}
 
Example 15
Source File: ValuesController.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/**
 * create or update an item
 *
 * @return result
 */
public Result put(String collectionId, String key) throws Exception {
    ensureValidId(collectionId, key);
    JsonNode jsonBody = request().body().asJson();
    ValueServiceModel inputModel = Json.fromJson(jsonBody, ValueServiceModel.class);
    ValueServiceModel result = (inputModel.ETag == null) ?
            this.container.create(collectionId, key, inputModel) :
            this.container.upsert(collectionId, key, inputModel);
    return ok(toJson(new ValueApiModel(result)));
}
 
Example 16
Source File: StorageAdapterClient.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
private static <A> A fromJson(String json, Class<A> clazz) {
    return Json.fromJson(Json.parse(json), clazz);
}
 
Example 17
Source File: TestUtils.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
public static <T> T getResult(Result result, Class<T> clazz) {
    final String jsonResult = getString(result);
    return Json.fromJson(Json.parse(jsonResult), clazz);
}
 
Example 18
Source File: EventListApiModelTest.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
@Before
public void setUp() {
    InputStream stream = EventListApiModelTest.class.getResourceAsStream(TSI_SAMPLE_EVENTS_FILE);
    this.events = Json.fromJson(Json.parse(stream), EventListApiModel.class);
}
 
Example 19
Source File: StorageAdapterClient.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
private static <A> A fromJson(String json, Class<A> clazz) {
    return Json.fromJson(Json.parse(json), clazz);
}
 
Example 20
Source File: Storage.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
private static <A> A fromJson(String json, Class<A> clazz) {
    return Json.fromJson(Json.parse(json), clazz);
}