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

The following examples show how to use play.libs.Json#toJson() . 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: 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 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 getUserSettingAsyncTest() throws BaseException, ExecutionException, InterruptedException {
    String id = this.rand.NextString();
    String name = rand.NextString();
    String description = rand.NextString();
    String jsonData = String.format("{\"Name\":\"%s\",\"Description\":\"%s\"}", name, description);
    Object data = Json.fromJson(Json.parse(jsonData), Object.class);
    ValueApiModel model = new ValueApiModel();
    model.setData(jsonData);
    Mockito.when(mockClient.getAsync(Mockito.any(String.class), Mockito.any(String.class)))
            .thenReturn(CompletableFuture.supplyAsync(() -> model));
    Object result = storage.getUserSetting(id).toCompletableFuture().get();
    JsonNode node = Json.toJson(result);
    assertEquals(node.get("Name").asText(), name);
    assertEquals(node.get("Description").asText(), description);
}
 
Example 3
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 setUserSettingAsyncTest() throws BaseException, ExecutionException, InterruptedException {
    String id = this.rand.NextString();
    String name = rand.NextString();
    String description = rand.NextString();
    String jsonData = String.format("{\"Name\":\"%s\",\"Description\":\"%s\"}", name, description);
    Object setting = 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.setUserSetting(id, setting).toCompletableFuture().get();
    JsonNode node = Json.toJson(result);
    assertEquals(node.get("Name").asText(), name);
    assertEquals(node.get("Description").asText(), description);
}
 
Example 4
Source File: RegionController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public static JsonNode getRegionalTitles(Connection conn, String region) throws SQLException {
	Map<String, String> data = new HashMap<String, String>(2);
	PreparedStatement select = conn.prepareStatement("SELECT delegate_title, founder_title FROM assembly.region WHERE name = ?");
	select.setString(1, Utils.sanitizeName(region));
	ResultSet result = select.executeQuery();
	if (result.next()) {
		String title = result.getString(1);
		if (!result.wasNull()) {
			data.put("delegate_title", title);
		}
		title = result.getString(2);
		if (!result.wasNull()) {
			data.put("founder_title", title);
		}
	}
	return Json.toJson(data);
}
 
Example 5
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 getLogoShouldReturnDefaultLogoOnException() throws BaseException, ExecutionException, InterruptedException {
    // Arrange
    Mockito.when(mockClient.getAsync(Mockito.any(String.class), Mockito.any(String.class))).thenThrow(new ResourceNotFoundException());

    // Act
    Object result = storage.getLogoAsync().toCompletableFuture().get();
    JsonNode node = Json.toJson(result);

    // Assert
    assertEquals(Logo.Default.getImage(), node.get("Image").asText());
    assertEquals(Logo.Default.getType(),node.get("Type").asText());
    assertEquals(Logo.Default.getName(), node.get("Name").asText());
    assertTrue(node.get("IsDefault").booleanValue());
}
 
Example 6
Source File: RegionController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public static JsonNode getEmbassies(Connection conn, String region, int limit) throws SQLException {
	if (limit <= 0) {
		limit = Integer.MAX_VALUE;
	}
	List<Map<String, String>> embassies = new ArrayList<Map<String, String>>();
	PreparedStatement statement = conn.prepareStatement("SELECT embassies FROM assembly.region WHERE name = ?");
	statement.setString(1, Utils.sanitizeName(region));
	ResultSet result = statement.executeQuery();
	if (result.next()) {
		String list = result.getString(1);
		if (!result.wasNull() && list != null && !list.isEmpty()) {
			String[] split = list.split(":");
			for (int i = 0; i < Math.min(limit, split.length); i++) {
				Map<String, String> regionData = new HashMap<String, String>();
				regionData.put("name", split[i]);
				regionData.put("flag", Utils.getRegionFlag(split[i], conn));
				embassies.add(regionData);
			}
		}
	}
	DbUtils.closeQuietly(result);
	DbUtils.closeQuietly(statement);
	return Json.toJson(embassies);
}
 
Example 7
Source File: RMBController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public static JsonNode calculateTotalPostRatings(DatabaseAccess access, 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", access.getNationTitle(result.getString(1)));
		ratings.put("type", String.valueOf(result.getInt(2)));
		list.add(ratings);
	}
	DbUtils.closeQuietly(result);
	DbUtils.closeQuietly(select);
	
	Map<String, Object> postRatings = new HashMap<String, Object>();
	postRatings.put("rmb_post", rmbPost);
	postRatings.put("ratings", list);
	return Json.toJson(postRatings);
}
 
Example 8
Source File: StorageTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = StorageTest.TIMEOUT)
@Category({UnitTest.class})
public void getThemeAsyncTest() throws BaseException, ExecutionException, InterruptedException {
    String name = rand.NextString();
    String description = rand.NextString();
    ValueApiModel model = new ValueApiModel();
    model.setData(String.format("{\"Name\":\"%s\",\"Description\":\"%s\"}", name, description));
    Mockito.when(mockClient.getAsync(Mockito.anyString(), Mockito.anyString()))
            .thenReturn(CompletableFuture.supplyAsync(() -> model));
    Object result = storage.getThemeAsync().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 9
Source File: UserSettingsControllerTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = 100000)
@Category({UnitTest.class})
public void getUserSettingAsyncTest() throws BaseException, ExecutionException, InterruptedException {
    String id = this.rand.NextString();
    String name = rand.NextString();
    String description = rand.NextString();
    Object model = Json.fromJson(Json.parse(String.format("{\"Name\":\"%s\",\"Description\":\"%s\"}", name, description)), Object.class);
    Mockito.when(mockStorage.getUserSetting(Mockito.any(String.class))).thenReturn(CompletableFuture.supplyAsync(() -> model));
    controller = new UserSettingsController(mockStorage);
    String resultStr = TestUtils.getString(controller.getUserSettingAsync(id).toCompletableFuture().get());
    JsonNode result = Json.toJson(Json.parse(resultStr));
    assertEquals(result.get("Name").asText(), name);
    assertEquals(result.get("Description").asText(), description);
}
 
Example 10
Source File: PubSub.java    From WAMPlay with MIT License 5 votes vote down vote up
/**
 * Method that truncates an event message before it's published. 
 * @param client WAMP client that sent the event
 * @param event Event to be truncated
 * @return Modified json event, null to halt publish
 */
@onPublish("truncate")
public static JsonNode truncatePublish(String sessionID, JsonNode event) {
	if (!event.isTextual()) {
		return cancel();
	}		
	String message = event.asText();
	if (message.length() > 10) {
		message = message.substring(0, MAX_MESSAGE_LENGTH);
	}
	return Json.toJson(message);
}
 
Example 11
Source File: SolutionSettingsControllerTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void getThemeAsyncTest() throws BaseException, ExecutionException, InterruptedException {
    String name = rand.NextString();
    String description = rand.NextString();
    Object model = Json.fromJson(Json.parse(String.format("{\"Name\":\"%s\",\"Description\":\"%s\"}", name, description)), Object.class);
    Mockito.when(mockStorage.getThemeAsync()).thenReturn(CompletableFuture.supplyAsync(() -> model));
    controller = new SolutionSettingsController(mockStorage, mockActions);
    String resultStr = TestUtils.getString(controller.getThemeAsync().toCompletableFuture().get());
    JsonNode result = Json.toJson(Json.parse(resultStr));
    assertEquals(result.get("Name").asText(), name);
    assertEquals(result.get("Description").asText(), description);
}
 
Example 12
Source File: ParamGenerator.java    From dr-elephant with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a list of particles to json
 * @param particleList Particle List
 * @return JsonNode
 */
private JsonNode particleListToJson(List<Particle> particleList) {
  JsonNode jsonNode;

  if (particleList == null) {
    jsonNode = JsonNodeFactory.instance.objectNode();
    logger.info("Null particleList, returning empty json");
  } else {
    jsonNode = Json.toJson(particleList);
  }
  return jsonNode;
}
 
Example 13
Source File: PSOParamGenerator.java    From dr-elephant with Apache License 2.0 5 votes vote down vote up
/**
 * Interacts with python scripts to generate new parameter suggestions
 * @param jobTuningInfo Job tuning information
 * @return Updated job tuning information
 */
public JobTuningInfo generateParamSet(JobTuningInfo jobTuningInfo) {
  logger.info("Generating param set for job: " + jobTuningInfo.getTuningJob().jobName);

  JobTuningInfo newJobTuningInfo = new JobTuningInfo();
  newJobTuningInfo.setTuningJob(jobTuningInfo.getTuningJob());
  newJobTuningInfo.setParametersToTune(jobTuningInfo.getParametersToTune());
  newJobTuningInfo.setJobType(jobTuningInfo.getJobType());

  JsonNode jsonJobTuningInfo = Json.toJson(jobTuningInfo);
  String parametersToTune = jsonJobTuningInfo.get(PARAMS_TO_TUNE_FIELD_NAME).toString();
  String stringTunerState = jobTuningInfo.getTunerState();
  stringTunerState = stringTunerState.replaceAll("\\s+", "");
  String jobType = jobTuningInfo.getJobType().toString();

  List<String> error = new ArrayList<String>();

  try {
    Process p = Runtime.getRuntime()
        .exec(
            PYTHON_PATH + " " + TUNING_SCRIPT_PATH + " " + stringTunerState + " " + parametersToTune + " " + jobType);
    BufferedReader inputStream = new BufferedReader(
        new InputStreamReader(p.getInputStream(), Charset.forName("UTF-8")));
    BufferedReader errorStream = new BufferedReader(
        new InputStreamReader(p.getErrorStream(), Charset.forName("UTF-8")));
    String updatedStringTunerState = inputStream.readLine();
    newJobTuningInfo.setTunerState(updatedStringTunerState);
    String errorLine;
    while ((errorLine = errorStream.readLine()) != null) {
      error.add(errorLine);
    }
    if (error.size() != 0) {
      logger.error("Error in python script running PSO: " + error.toString());
    }
  } catch (IOException e) {
    logger.error("Error in generateParamSet()", e);
  }
  return newJobTuningInfo;
}
 
Example 14
Source File: NewspaperController.java    From NationStatesPlusPlus with MIT License 5 votes vote down vote up
public static JsonNode getLatestUpdate(Connection conn, int id) throws SQLException {
	Map<String, Object> newspaper = new HashMap<String, Object>();
	try (PreparedStatement articles = conn.prepareStatement("SELECT max(articles.timestamp) FROM assembly.articles WHERE newspaper = ? AND visible = 1")) {
		articles.setInt(1, id);
		try (ResultSet result = articles.executeQuery()) {
			if (result.next()) {
				newspaper.put("timestamp", result.getLong(1));
			}
		}
	}
	newspaper.put("newspaper_id", id);
	return Json.toJson(newspaper);
}
 
Example 15
Source File: NewspaperController.java    From NationStatesPlusPlus with MIT License 4 votes vote down vote up
private JsonNode getNewspaperImpl(int id, int visible, boolean hideBody, int lookupArticleId) throws SQLException {
	Map<String, Object> newspaper = new HashMap<String, Object>();
	ArrayList<Map<String, Object>> news = new ArrayList<Map<String, Object>>();
	try (Connection conn = getConnection()) {
		try (PreparedStatement select = conn.prepareStatement("SELECT title, byline, editor, newspapers.columns FROM assembly.newspapers WHERE id = ? ")) {
			select.setInt(1, id);
			try (ResultSet result = select.executeQuery()) {
				if (result.next()) {
					newspaper.put("newspaper", result.getString(1));
					newspaper.put("byline", result.getString(2));
					newspaper.put("editor", result.getString(3));
					newspaper.put("columns", String.valueOf(result.getInt(4)));
				} else {
					return null;
				}
			}
		}

		try (PreparedStatement articles = conn.prepareStatement("SELECT id, title, articles.timestamp, author, visible, submitter" + (!hideBody ? ", article " : "") + " FROM assembly.articles WHERE visible <> " + Visibility.DELETED.getType() + " AND newspaper = ? " + (lookupArticleId != -1 ? " AND id = ? " : "") + (visible != -1 ? " AND visible = ?" : ""))) {
			int index = 1;
			articles.setInt(index, id);
			index++;
			if (lookupArticleId != -1) {
				articles.setInt(index, lookupArticleId);
				index++;
			}
			if (visible != -1) {
				articles.setInt(index, visible);
				index++;
			}
			try (ResultSet result = articles.executeQuery()) {
				while (result.next()) {
					Map<String, Object> article = new HashMap<String, Object>();
					article.put("article_id", String.valueOf(result.getInt(1)));
					article.put("title", result.getString(2));
					article.put("timestamp", String.valueOf(result.getLong(3)));
					article.put("author", result.getString(4));
					article.put("newspaper", String.valueOf(id));
					article.put("visible", String.valueOf(result.getByte(5)));
					article.put("submitter", Nation.getNationById(conn, result.getInt(6), false));
					if (!hideBody) {
						article.put("article", result.getString(7));
					}
					news.add(article);
				}
			}
		}
	}
	newspaper.put("articles", news);
	newspaper.put("newspaper_id", id);
	return Json.toJson(newspaper);
}
 
Example 16
Source File: AMQPThread.java    From NationStatesPlusPlus with MIT License 4 votes vote down vote up
private JsonNode wrapNode(JsonNode node) {
	return Json.toJson(new AMQPMessage(serverName, node));
}
 
Example 17
Source File: RecruitmentController.java    From NationStatesPlusPlus with MIT License 4 votes vote down vote up
public static JsonNode getRecruitmentCampaigns(Connection conn, String nation, int nationId, String region, boolean includeStats) throws SQLException {
	final int regionId = getRecruitmentAdministrator(conn, nation, nationId, region);
	if (regionId == -1) {
		return null;
	}
	List<Map<String, Object>> campaigns = new ArrayList<Map<String, Object>>();
	try (PreparedStatement select = conn.prepareStatement("SELECT id, created, retired, type, client_key, tgid, secret_key, allocation, gcrs_only FROM assembly.recruit_campaign WHERE region = ? AND visible = 1 ORDER BY created DESC")) {
		select.setInt(1, regionId);
		try (ResultSet set = select.executeQuery()) {
			while(set.next()) {
				Map<String, Object> campaign = new HashMap<String, Object>();
				campaign.put("id", set.getInt("id"));
				campaign.put("created", set.getLong("created"));
				campaign.put("retired", set.getLong("retired"));
				campaign.put("type", set.getInt("type"));
				campaign.put("client_key", set.getString("client_key"));
				campaign.put("tgid", set.getInt("tgid"));
				campaign.put("secret_key", set.getString("secret_key"));
				campaign.put("allocation", set.getInt("allocation"));
				campaign.put("gcrs_only", set.getInt("gcrs_only"));
				campaigns.add(campaign);
				
				if (includeStats) {
					try (PreparedStatement totalSent = conn.prepareStatement("SELECT count(id) FROM assembly.recruitment_results WHERE campaign = ?")) {
						totalSent.setInt(1, set.getInt("id"));
						try (ResultSet total = totalSent.executeQuery()) {
							total.next();
							campaign.put("total_sent", total.getInt(1));
						}
					}
	
					try (PreparedStatement pendingRecruits = conn.prepareStatement("SELECT count(r.id) FROM assembly.recruitment_results AS r LEFT JOIN assembly.nation AS n ON n.id = r.nation WHERE r.timestamp > ? AND r.campaign = ? AND n.alive = 1 AND n.region = r.region")) {
						pendingRecruits.setLong(1, System.currentTimeMillis() - Duration.standardDays(14).getMillis());
						pendingRecruits.setInt(2, set.getInt("id"));
						try (ResultSet total = pendingRecruits.executeQuery()) {
							total.next();
							campaign.put("pending_recruits", total.getInt(1));
						}
					}
	
					try (PreparedStatement recruits = conn.prepareStatement("SELECT count(r.id) FROM assembly.recruitment_results AS r LEFT JOIN assembly.nation AS n ON n.id = r.nation WHERE r.timestamp < ? AND r.campaign = ? AND n.alive = 1 AND n.region = r.region")) {
						recruits.setLong(1, System.currentTimeMillis() - Duration.standardDays(14).getMillis());
						recruits.setInt(2, set.getInt("id"));
						try (ResultSet total = recruits.executeQuery()) {
							total.next();
							campaign.put("recruits", total.getInt(1));
						}
					}
	
					try (PreparedStatement deadRecruits = conn.prepareStatement("SELECT count(r.id) FROM assembly.recruitment_results AS r LEFT JOIN assembly.nation AS n ON n.id = r.nation WHERE r.campaign = ? AND n.alive = 0 AND n.region = r.region")) {
						deadRecruits.setInt(1, set.getInt("id"));
						try (ResultSet total = deadRecruits.executeQuery()) {
							total.next();
							campaign.put("dead_recruits", total.getInt(1));
						}
					}
				}
			}
		}
	}
	return Json.toJson(campaigns);
}
 
Example 18
Source File: PubSubTest.java    From WAMPlay with MIT License 4 votes vote down vote up
private void send(WAMPlayClient client, List<Object> res) {
	JsonNode req = Json.toJson(res);
	WAMPlayServer.handleRequest(client, req);
}
 
Example 19
Source File: RecruitmentController.java    From NationStatesPlusPlus with MIT License 4 votes vote down vote up
public static JsonNode calculateRecruitmentTarget(DatabaseAccess access, Connection conn, int regionId, String nation, int nationId) throws SQLException, ExecutionException {
	final long startTime = System.currentTimeMillis();
	int status = 0; // 0 - successful recruitment, 1 - unable to find recruitment target, 2 - can not recruit (blocked)

	//Unless another nation is already recruiting, get a target
	if (canRecruit(conn, regionId)) {
		status = 1;
		Map<String, Object> data = getRecruitmentTarget(access, conn, regionId, nation);
		if (data != null) {
			int campaignId = (Integer)data.get("campaign_id");
			logRecruitmentPerformance(conn, nationId, regionId, (int)(System.currentTimeMillis() - startTime), 0, campaignId);
			return Json.toJson(data);
		}
	} else {
		status = 2;
	}
	
	logger.trace("Recruitment target status for region [{}] by recruiter nation [{}] is {}", regionId, nation, status);

	//Otherwise, abort with an instruction to delay retrying
	Map<String, Object> wait = new HashMap<String, Object>();
	long timestamp = System.currentTimeMillis();
	try (PreparedStatement lastRecruitment = conn.prepareStatement("SELECT nation, timestamp, recruiter FROM assembly.recruitment_results WHERE region = ? ORDER BY timestamp DESC LIMIT 0, 1")) {
		lastRecruitment.setInt(1, regionId);
		try (ResultSet set = lastRecruitment.executeQuery()) {
			if (set.next()) {
				wait.put("nation", access.getReverseIdCache().get(set.getInt("nation")));
				wait.put("timestamp", set.getLong("timestamp"));
				wait.put("recruiter", access.getReverseIdCache().get(set.getInt("recruiter")));
				timestamp = set.getLong("timestamp");
				logger.trace("Recruitment results table shows last recruitment for region [{}] was by recruiter [{}] at time [{}]", regionId, wait.get("nation"), new DateTime(timestamp, DateTimeZone.UTC));
			}
		}
	}
	final Duration timeSinceLastRecruitment = new Duration(DateTime.now(), new DateTime(timestamp));
	final Duration timeUntilNextRecruitment = Duration.standardMinutes(3).plus(SAFETY_FACTOR).minus(timeSinceLastRecruitment);
	wait.put("wait", Math.min(Math.max(timeUntilNextRecruitment.getStandardSeconds(), 10), 300)); 
	logger.trace("Instructing recruiter [{}] to wait for {} seconds before next recruitment attempt", wait.get("wait"));
	
	logRecruitmentPerformance(conn, nationId, regionId, (int)(System.currentTimeMillis() - startTime), status, -1);
	return Json.toJson(wait);
}
 
Example 20
Source File: WebSocketService.java    From htwplus with MIT License 2 votes vote down vote up
/**
 * WebSocket method Ping for testing purposes.
 *
 * @param wsMessage WebSocket message as JsonNode object
 * @param senderActor Sending actor
 * @param sender Sending account
 * @return WebSocket response
 */
private JsonNode wsPing(JsonNode wsMessage, ActorRef senderActor, Account sender) {
    return Json.toJson("Pong");
}