List of usage examples for javax.json JsonObject getString
String getString(String name);
From source file:eu.forgetit.middleware.component.Extractor.java
public void testVideoAnalysis(Exchange exchange) { logger.debug("New message retrieved"); JsonObject jsonBody = MessageTools.getBody(exchange); JsonObjectBuilder job = Json.createObjectBuilder(); for (Entry<String, JsonValue> entry : jsonBody.entrySet()) { job.add(entry.getKey(), entry.getValue()); }/* www .j av a2 s .co m*/ if (jsonBody != null) { String videoPath = jsonBody.getString("videoPath"); logger.debug("Retrieved Video Path: " + videoPath); job.add("videoPath", videoPath); String method = jsonBody.getString("method"); logger.debug("Retrieved VAM: " + method); job.add("method", method); // ONE video per call if (videoPath != null && !videoPath.isEmpty()) { logger.debug("Executing Video Analysis Method: " + method); String result = service.video_request(videoPath, method); //System.out.println("VAM method "+method+" result:\n"+result); // Video analysis service response String response = service.video_results(videoPath); logger.debug("VAM method " + method + " result:\n" + response); job.add("result", response); } else { logger.debug("Unable to process video, wrong request"); job.add("result", "Unable to process video, wrong request"); } exchange.getOut().setBody(job.build().toString()); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } }
From source file:org.btc4j.daemon.BtcJsonRpcHttpClient.java
public JsonValue invoke(String method, JsonArray parameters) throws BtcException { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add(JSONRPC_REALM, JSONRPC_VERSION).add(JSONRPC_METHOD, method); if (parameters != null) { builder.add(JSONRPC_PARAMS, parameters); } else {// w w w.j av a 2s . c o m builder.addNull(JSONRPC_PARAMS); } String guid = UUID.randomUUID().toString(); builder.add(JSONRPC_ID, guid); JsonObject request = builder.build(); JsonObject response = jsonObject(jsonValue(jsonInvoke(String.valueOf(request)))); if (response == null) { LOG.severe(BTC4J_DAEMON_DATA_NULL_JSON); throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BTC4J_DAEMON_DATA_NULL_JSON); } if (!(guid.equals(jsonId(response)))) { LOG.severe(BTC4J_DAEMON_DATA_INVALID_ID); throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BTC4J_DAEMON_DATA_INVALID_ID); } JsonValue error = response.get(JSONRPC_ERROR); if ((error != null) && (error.getValueType().equals(ValueType.OBJECT))) { JsonObject errorObj = (JsonObject) error; int code = errorObj.getInt(JSONRPC_CODE); String message = errorObj.getString(JSONRPC_MESSAGE); JsonObject data = (JsonObject) errorObj.get(JSONRPC_DATA); String dataStr = (data == null) ? "" : (" " + String.valueOf(data)); LOG.severe("error: " + code + " " + message + dataStr); throw new BtcException(code, message + dataStr); } return response.get(JSONRPC_RESULT); }
From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java
/** * Gets the information for the given ElectionID from the bulletin board and returns it as a election object * @param electionId/*from w w w . ja v a 2 s. c om*/ * the identifier (id) for the desired election * @return returns tje election object for a given id */ public Election getElectionById(int electionId) { Election election = null; try { URL url = new URL(bulletinBoardUrl + "/elections/" + electionId); InputStream urlInputStream = url.openStream(); JsonReader jsonReader = Json.createReader(urlInputStream); JsonObject obj = jsonReader.readObject(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); Parameters parameters = this.getParameters(); //gets the json string and transforms it into a election object //translates the header information of the election String title = obj.getString("electionTitle"); LocalDateTime beginDate = LocalDateTime.parse(obj.getString("beginDate"), format); LocalDateTime endDate = LocalDateTime.parse(obj.getString("endDate"), format); String appVersion = obj.getString("appVersion"); String coefficientsString = obj.getString("coefficients"); String h_HatString = obj.getString("electionGenerator"); List<Voter> voterlist = new ArrayList<Voter>(); //get th list of voters for (JsonObject result : obj.getJsonArray("voters").getValuesAs(JsonObject.class)) { String voterEmail = result.getString("email"); String voterPublicCredential = result.getString("publicCredential"); String voterAppVersion = result.getString("appVersion"); Voter voter = new Voter(voterEmail, voterPublicCredential, voterAppVersion); voterlist.add(voter); } //get the votingTopic JsonObject electionTopicObj = obj.getJsonObject("votingTopic"); String topic = electionTopicObj.getString("topic"); int pick = electionTopicObj.getInt("pick"); ElectionTopic electionTopic = new ElectionTopic(topic, pick); JsonArray optionsArray = electionTopicObj.getJsonArray("options"); for (int i = 0; i < optionsArray.size(); i++) { electionTopic.addOption(optionsArray.getString(i)); } election = new Election(electionId, title, voterlist, parameters, beginDate, endDate, electionTopic, appVersion, h_HatString, coefficientsString); } catch (IOException x) { System.err.println(x); } return election; }
From source file:eu.forgetit.middleware.component.Extractor.java
public void videoNDDAnalysis(Exchange exchange) { logger.debug("New message retrieved"); JsonObject jsonBody = MessageTools.getBody(exchange); JsonObjectBuilder job = Json.createObjectBuilder(); for (Entry<String, JsonValue> entry : jsonBody.entrySet()) { job.add(entry.getKey(), entry.getValue()); }/* w ww. j a v a 2 s .c o m*/ if (jsonBody != null) { //String videoPaths = getVideoPath(jsonBody); String videoPath = jsonBody.getString("videoPath"); logger.debug("Retrieved Video Path: " + videoPath); job.add("videoPath", videoPath); //String method = jsonBody.getString("method"); //System.out.println("Retrieved VAM: "+method); // ONE video per call if (videoPath != null && !videoPath.isEmpty()) { logger.debug("Executing Video Analysis Method: Near Duplicate Detection"); String response_tmp = service.video_ndd_request(videoPath); logger.debug("Video NDD Analysis method result:\n" + response_tmp); // call id is returned at the response String callid; String[] callid_tmp = response_tmp.split("::"); callid = callid_tmp[1].trim(); String response = service.video_ndd_result(callid); logger.debug("Video NDD result:\n" + response); job.add("result", response); } else { logger.debug("Unable to process video, wrong request"); job.add("result", "Unable to process video, wrong request"); } exchange.getOut().setBody(job.build().toString()); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } }
From source file:org.apache.tamaya.etcd.EtcdAccessor.java
/** * Deletes a given key. The response is as follows: * /*from w w w.jav a 2s .com*/ * <pre> * _key.source=[etcd]http://127.0.0.1:4001 * _key.createdIndex=12 * _key.modifiedIndex=34 * _key.ttl=300 * _key.expiry=... * // optional * _key.prevNode.createdIndex=12 * _key.prevNode.modifiedIndex=34 * _key.prevNode.ttl=300 * _key.prevNode.expiration=... * _key.prevNode.value=... * </pre> * * @param key the key to be deleted. * @return the response mpas as described above. */ public Map<String, String> delete(String key) { final Map<String, String> result = new HashMap<>(); try { final HttpDelete delete = new HttpDelete(serverURL + "/v2/keys/" + key); delete.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout) .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build()); try (CloseableHttpResponse response = httpclient.execute(delete)) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final HttpEntity entity = response.getEntity(); final JsonReader reader = readerFactory .createReader(new StringReader(EntityUtils.toString(entity))); final JsonObject o = reader.readObject(); final JsonObject node = o.getJsonObject("node"); if (node.containsKey("createdIndex")) { result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex"))); } if (node.containsKey("modifiedIndex")) { result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex"))); } if (node.containsKey("expiration")) { result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration"))); } if (node.containsKey("ttl")) { result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl"))); } parsePrevNode(key, result, o); EntityUtils.consume(entity); } } } catch (final Exception e) { LOG.log(Level.INFO, "Error deleting key '" + key + "' from etcd: " + serverURL, e); result.put("_ERROR", "Error deleting '" + key + "' from etcd: " + serverURL + ": " + e.toString()); } return result; }
From source file:org.apache.tamaya.etcd.EtcdAccessor.java
/** * Creates/updates an entry in etcd. The response as follows: * //from w w w. j a v a2s. c o m * <pre> * { * "action": "set", * "node": { * "createdIndex": 3, * "key": "/message", * "modifiedIndex": 3, * "value": "Hello etcd" * }, * "prevNode": { * "createdIndex": 2, * "key": "/message", * "value": "Hello world", * "modifiedIndex": 2 * } * } * </pre> * * is mapped to: * * <pre> * key=value * _key.source=[etcd]http://127.0.0.1:4001 * _key.createdIndex=12 * _key.modifiedIndex=34 * _key.ttl=300 * _key.expiry=... * // optional * _key.prevNode.createdIndex=12 * _key.prevNode.modifiedIndex=34 * _key.prevNode.ttl=300 * _key.prevNode.expiration=... * </pre> * * @param key the property key, not null * @param value the value to be set * @param ttlSeconds the ttl in seconds (optional) * @return the result map as described above. */ public Map<String, String> set(String key, String value, Integer ttlSeconds) { final Map<String, String> result = new HashMap<>(); try { final HttpPut put = new HttpPut(serverURL + "/v2/keys/" + key); put.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout) .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build()); final List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("value", value)); if (ttlSeconds != null) { nvps.add(new BasicNameValuePair("ttl", ttlSeconds.toString())); } put.setEntity(new UrlEncodedFormEntity(nvps)); try (CloseableHttpResponse response = httpclient.execute(put)) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final HttpEntity entity = response.getEntity(); final JsonReader reader = readerFactory .createReader(new StringReader(EntityUtils.toString(entity))); final JsonObject o = reader.readObject(); final JsonObject node = o.getJsonObject("node"); if (node.containsKey("createdIndex")) { result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex"))); } if (node.containsKey("modifiedIndex")) { result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex"))); } if (node.containsKey("expiration")) { result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration"))); } if (node.containsKey("ttl")) { result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl"))); } result.put(key, node.getString("value")); result.put("_" + key + ".source", "[etcd]" + serverURL); parsePrevNode(key, result, node); EntityUtils.consume(entity); } } } catch (final Exception e) { LOG.log(Level.INFO, "Error writing to etcd: " + serverURL, e); result.put("_ERROR", "Error writing '" + key + "' to etcd: " + serverURL + ": " + e.toString()); } return result; }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.exac.EXACResourceImplementation.java
private String getValue(JsonObject obj, String field) { if (field.contains(".")) { String thisField = field.split("\\.")[0]; String remaining = field.replaceFirst(thisField + ".", ""); return getValue(obj.getJsonObject(thisField), remaining); }/*from ww w . j a v a2 s . co m*/ if (obj.containsKey(field)) { ValueType vt = obj.get(field).getValueType(); if (vt == ValueType.NUMBER) { return obj.getJsonNumber(field).toString(); } else if (vt == ValueType.TRUE) { return "TRUE"; } else if (vt == ValueType.FALSE) { return "FALSE"; } return obj.getString(field); } return ""; }
From source file:csg.files.CSGFiles.java
@Override public void loadData(AppDataComponent data, AppDataComponent recData, AppDataComponent schData, AppDataComponent projectData, AppDataComponent courseData, String filePath) throws IOException { // CLEAR THE OLD DATA OUT TAData dataManager = (TAData) data;/*from w w w .ja v a2 s .c om*/ ScheduleData schDataManager = (ScheduleData) schData; RecitationData recDataManager = (RecitationData) recData; ProjectData projectDataManager = (ProjectData) projectData; CourseData courseDataManager = (CourseData) courseData; workspace = (CSGWorkspace) app.getWorkspaceComponent(); // LOAD THE JSON FILE WITH ALL THE DATA JsonObject json = loadJSONFile(filePath); // LOAD THE START AND END HOURS String startHour = json.getString(JSON_START_HOUR); String endHour = json.getString(JSON_END_HOUR); dataManager.initHours(startHour, endHour); // NOW RELOAD THE WORKSPACE WITH THE LOADED DATA app.getWorkspaceComponent().reloadWorkspace(app.getTADataComponent()); int startDay = json.getInt(JSON_STARTDAY); int startMonth = json.getInt(JSON_STARTMONTH); int startYear = json.getInt(JSON_STARTYEAR); courseDataManager.setStartDay(startDay); courseDataManager.setStartMonth(startMonth); courseDataManager.setStartYear(startYear); if (startDay != 0 && startMonth != 0 && startYear != 0) { LocalDate startDate = LocalDate.of(startYear, startMonth, startDay); workspace.getMonStartDatePicker().setValue(startDate); } else { workspace.getMonStartDatePicker().setValue(null); } int endDay = json.getInt(JSON_ENDDAY); int endMonth = json.getInt(JSON_ENDMONTH); int endYear = json.getInt(JSON_ENDYEAR); courseDataManager.setEndDay(endDay); courseDataManager.setEndMonth(endMonth); courseDataManager.setEndYear(endYear); if (endDay != 0 && endMonth != 0 && endYear != 0) { LocalDate endDate = LocalDate.of(endYear, endMonth, endDay); workspace.getFriEndDatePicker().setValue(endDate); } else { workspace.getFriEndDatePicker().setValue(null); } // NOW LOAD ALL THE UNDERGRAD TAs JsonArray jsonTAArray = json.getJsonArray(JSON_UNDERGRAD_TAS); for (int i = 0; i < jsonTAArray.size(); i++) { JsonObject jsonTA = jsonTAArray.getJsonObject(i); String name = jsonTA.getString(JSON_NAME); String email = jsonTA.getString(JSON_EMAIL); boolean ug = jsonTA.getBoolean(JSON_UG); BooleanProperty isUndergrad = new SimpleBooleanProperty(); isUndergrad.setValue(ug); dataManager.addTA(name, email, isUndergrad); } // AND THEN ALL THE OFFICE HOURS JsonArray jsonOfficeHoursArray = json.getJsonArray(JSON_OFFICE_HOURS); for (int i = 0; i < jsonOfficeHoursArray.size(); i++) { JsonObject jsonOfficeHours = jsonOfficeHoursArray.getJsonObject(i); String day = jsonOfficeHours.getString(JSON_DAY); String time = jsonOfficeHours.getString(JSON_TIME); String name = jsonOfficeHours.getString(JSON_NAME); dataManager.addOfficeHoursReservation(day, time, name); } JsonArray jsonRecitationArray = json.getJsonArray(JSON_RECITATION); for (int i = 0; i < jsonRecitationArray.size(); i++) { JsonObject jsonRec = jsonRecitationArray.getJsonObject(i); String section = jsonRec.getString(JSON_SECTION); String instructor = jsonRec.getString(JSON_INSTRUCTOR); String dayTime = jsonRec.getString(JSON_DAYTIME); String location = jsonRec.getString(JSON_LOCATION); String firstTA = jsonRec.getString(JSON_FIRSTTA); String secondTA = jsonRec.getString(JSON_SECONDTA); recDataManager.addRecitation(section, instructor, dayTime, location, firstTA, secondTA); } JsonArray jsonScheduleArray = json.getJsonArray(JSON_SCHEDULEITEM); for (int i = 0; i < jsonScheduleArray.size(); i++) { JsonObject jsonSch = jsonScheduleArray.getJsonObject(i); String type = jsonSch.getString(JSON_TYPE); int month = jsonSch.getInt(JSON_MONTH); int day = jsonSch.getInt(JSON_DAY); int year = jsonSch.getInt(JSON_YEAR); String time = jsonSch.getString(JSON_TIME); String title = jsonSch.getString(JSON_TITLE); String topic = jsonSch.getString(JSON_TOPIC); String link = jsonSch.getString(JSON_LINK); String criteria = jsonSch.getString(JSON_CRITERIA); schDataManager.addScheduleItem(type, LocalDate.of(year, month, day), time, title, topic, link, criteria); } JsonArray jsonTeamArray = json.getJsonArray(JSON_TEAMS); for (int i = 0; i < jsonTeamArray.size(); i++) { JsonObject jsonTeam = jsonTeamArray.getJsonObject(i); String name = jsonTeam.getString(JSON_NAME); String color = jsonTeam.getString(JSON_COLOR); String textColor = jsonTeam.getString(JSON_TEXTCOLOR); String link = jsonTeam.getString(JSON_LINK); projectDataManager.addTeam(name, color, textColor, link); } JsonArray jsonStudentArray = json.getJsonArray(JSON_STUDENTS); for (int i = 0; i < jsonStudentArray.size(); i++) { JsonObject jsonStudent = jsonStudentArray.getJsonObject(i); String firstName = jsonStudent.getString(JSON_FIRSTNAME); String lastName = jsonStudent.getString(JSON_LASTNAME); String team = jsonStudent.getString(JSON_TEAM); String role = jsonStudent.getString(JSON_ROLE); projectDataManager.addStudent(firstName, lastName, team, role); } JsonArray jsonTemplateArray = json.getJsonArray(JSON_COURSETEMPLATE); courseDataManager.getTemplates().clear(); for (int i = 0; i < jsonTemplateArray.size(); i++) { JsonObject jsonTemplate = jsonTemplateArray.getJsonObject(i); boolean use = jsonTemplate.getBoolean(JSON_USE); String navbar = jsonTemplate.getString(JSON_NAVBAR); String fileName = jsonTemplate.getString(JSON_FILENAME); String script = jsonTemplate.getString(JSON_SCRIPT); courseDataManager.addTemplate(use, navbar, fileName, script); } JsonObject courseJson = json.getJsonObject(JSON_COURSE); courseDataManager.setNumber(courseJson.getString(JSON_NUMBER)); courseDataManager.setSemester(courseJson.getString(JSON_SEMESTER)); courseDataManager.setSubject(courseJson.getString(JSON_SUBJECT)); courseDataManager.setYear(courseJson.getString(JSON_YEAR)); courseDataManager.setTitle(courseJson.getString(JSON_TITLE)); courseDataManager.setInsName(courseJson.getString(JSON_INSTRUCTORNAME)); courseDataManager.setInsHome(courseJson.getString(JSON_INSTRUCTORHOME)); courseDataManager.setBannerLink(courseJson.getString(JSON_BANNER)); courseDataManager.setLeftFooterLink(courseJson.getString(JSON_LEFTFOOTER)); courseDataManager.setRightFooterLink(courseJson.getString(JSON_RIGHTFOOTER)); courseDataManager.setTemplateDir(courseJson.getString(JSON_TEMPLATEDIR)); courseDataManager.setExportDir(courseJson.getString(JSON_EXPORTDIR)); courseDataManager.setStyleSheet(courseJson.getString(JSON_STYLESHEET)); workspace.getSubjectCombo().setValue(courseDataManager.getSubject()); workspace.getNumCombo().setValue(courseDataManager.getNumber()); workspace.getSemCombo().setValue(courseDataManager.getSemester()); workspace.getYearCombo().setValue(courseDataManager.getYear()); workspace.getTitleTextField().setText(courseDataManager.getTitle()); workspace.getInsNameTextField().setText(courseDataManager.getInsName()); workspace.getInsHomeTextField().setText(courseDataManager.getInsHome()); workspace.getStyleSheetCombo().setValue(courseDataManager.getStyleSheet()); if (!courseDataManager.getBannerLink().isEmpty()) { FileInputStream bannerLocation = new FileInputStream(courseJson.getString(JSON_BANNER)); Image newImg = new Image(bannerLocation); workspace.getBannerImage().setImage(newImg); } else { workspace.getBannerImage().setImage(null); } if (!courseDataManager.getLeftFooterLink().isEmpty()) { FileInputStream leftFooterLocation = new FileInputStream(courseJson.getString(JSON_LEFTFOOTER)); Image newImg2 = new Image(leftFooterLocation); workspace.getLeftFooterImage().setImage(newImg2); } else { workspace.getLeftFooterImage().setImage(null); } if (!courseDataManager.getRightFooterLink().isEmpty()) { FileInputStream rightFooterLocation = new FileInputStream(courseJson.getString(JSON_RIGHTFOOTER)); Image newImg3 = new Image(rightFooterLocation); workspace.getRightFooterImage().setImage(newImg3); } else { workspace.getRightFooterImage().setImage(null); } workspace.getCourseTemplateLocLabel().setText(courseJson.getString(JSON_TEMPLATEDIR)); workspace.getExportLabel().setText(courseJson.getString(JSON_EXPORTDIR)); }
From source file:edu.harvard.iq.dataverse.api.HarvestingServer.java
/** * create an OAI set from spec in path and other parameters from POST body * (as JSON). {"name":$set_name,/* w ww .j av a 2 s . c om*/ * "description":$optional_set_description,"definition":$set_search_query_string}. */ @POST @Path("{specname}") public Response createOaiSet(String jsonBody, @PathParam("specname") String spec, @QueryParam("key") String apiKey) throws IOException, JsonParseException { /* * authorization modeled after the UI (aka HarvestingSetsPage) */ AuthenticatedUser dvUser; try { dvUser = findAuthenticatedUserOrDie(); } catch (WrappedResponse wr) { return wr.getResponse(); } if (!dvUser.isSuperuser()) { return badRequest(ResourceBundle.getBundle("Bundle") .getString("harvestserver.newSetDialog.setspec.superUser.required")); } StringReader rdr = new StringReader(jsonBody); try (JsonReader jrdr = Json.createReader(rdr)) { JsonObject json = jrdr.readObject(); OAISet set = new OAISet(); //Validating spec if (!StringUtils.isEmpty(spec)) { if (spec.length() > 30) { return badRequest(ResourceBundle.getBundle("Bundle") .getString("harvestserver.newSetDialog.setspec.sizelimit")); } if (!Pattern.matches("^[a-zA-Z0-9\\_\\-]+$", spec)) { return badRequest(ResourceBundle.getBundle("Bundle") .getString("harvestserver.newSetDialog.setspec.invalid")); // If it passes the regex test, check } if (oaiSetService.findBySpec(spec) != null) { return badRequest(ResourceBundle.getBundle("Bundle") .getString("harvestserver.newSetDialog.setspec.alreadyused")); } } else { return badRequest(ResourceBundle.getBundle("Bundle") .getString("harvestserver.newSetDialog.setspec.required")); } set.setSpec(spec); String name, desc, defn; try { name = json.getString("name"); } catch (NullPointerException npe_name) { return badRequest(ResourceBundle.getBundle("Bundle") .getString("harvestserver.newSetDialog.setspec.required")); } try { defn = json.getString("definition"); } catch (NullPointerException npe_defn) { throw new JsonParseException("definition unspecified"); } try { desc = json.getString("description"); } catch (NullPointerException npe_desc) { desc = ""; //treating description as optional } set.setName(name); set.setDescription(desc); set.setDefinition(defn); oaiSetService.save(set); return created("/harvest/server/oaisets" + spec, oaiSetAsJson(set)); } }
From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java
private void checkLevelsLogged(final JsonLogServer server, final Set<Logger.Level> expectedLevels, final String msg) throws IOException, InterruptedException { executeRequest(msg, Collections.singletonMap("includeLevel", "true")); final List<JsonObject> foundMessages = new ArrayList<>(); for (int i = 0; i < expectedLevels.size(); i++) { final JsonObject foundMessage = server.getLogMessage(DFT_TIMEOUT); if (foundMessage == null) { final String failureMessage = "A log messages was not received within " + DFT_TIMEOUT + " milliseconds." + System.lineSeparator() + "Found the following messages: " + foundMessages + System.lineSeparator() + "Expected the following levels to be logged: " + expectedLevels;/*from w w w. ja va 2s . co m*/ Assert.fail(failureMessage); } foundMessages.add(foundMessage); } Assert.assertEquals(expectedLevels.size(), foundMessages.size()); // Check that we have all the expected levels final Collection<String> levels = expectedLevels.stream().map(Enum::name).collect(Collectors.toList()); final Iterator<JsonObject> iter = foundMessages.iterator(); while (iter.hasNext()) { final JsonObject foundMessage = iter.next(); final String foundLevel = foundMessage.getString("level"); Assert.assertNotNull("Expected a level on " + foundMessage, foundLevel); Assert.assertTrue(String.format("Level %s was logged, but not expected.", foundLevel), levels.remove(foundLevel)); iter.remove(); } // The string levels should be empty, if not we're missing an expected level Assert.assertTrue("Found levels that did not appear to be logged: " + levels, levels.isEmpty()); }