List of usage examples for com.fasterxml.jackson.databind.node ObjectNode toString
public String toString()
From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java
public static void createRESTUser(String usrName, String pass, String... roleNames) { try {/*from w w w .j a v a 2s . c om*/ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpGet getrequest = new HttpGet("http://localhost:8002" + "/manage/v2/users/" + usrName); HttpResponse resp = client.execute(getrequest); if (resp.getStatusLine().getStatusCode() == 200) { System.out.println("User already exist"); } else { System.out.println("User dont exist"); client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); ObjectMapper mapper = new ObjectMapper(); ObjectNode mainNode = mapper.createObjectNode(); // ObjectNode childNode = mapper.createObjectNode(); ArrayNode childArray = mapper.createArrayNode(); mainNode.put("user-name", usrName); mainNode.put("description", "user discription"); mainNode.put("password", pass); for (String rolename : roleNames) childArray.add(rolename); mainNode.withArray("role").addAll(childArray); //System.out.println(type + mainNode.path("range-element-indexes").path("range-element-index").toString()); System.out.println(mainNode.toString()); HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/users?format=json"); post.addHeader("Content-type", "application/json"); post.setEntity(new StringEntity(mainNode.toString())); HttpResponse response = client.execute(post); HttpEntity respEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 400) { System.out.println("User already exist"); } else if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); System.out.println(content); } else { System.out.println("No Proper Response"); } } } catch (Exception e) { // writing error to Log e.printStackTrace(); } }
From source file:io.gs2.matchmaking.Gs2MatchmakingClient.java
/** * ???????<br>/*from w w w . j a va 2s . c o m*/ * <br> * ?8????????????<br> * ???100??????????<br> * ???????????<br> * <br> * - : 10<br> * <br> * * @param request * @return ? */ public PasscodeCreateGatheringResult passcodeCreateGathering(PasscodeCreateGatheringRequest request) { ObjectNode body = JsonNodeFactory.instance.objectNode(); HttpPost post = createHttpPost( Gs2Constant.ENDPOINT_HOST + "/matchmaking/" + (request.getMatchmakingName() == null || request.getMatchmakingName().equals("") ? "null" : request.getMatchmakingName()) + "/passcode", credential, ENDPOINT, PasscodeCreateGatheringRequest.Constant.MODULE, PasscodeCreateGatheringRequest.Constant.FUNCTION, body.toString()); if (request.getRequestId() != null) { post.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } post.setHeader("X-GS2-ACCESS-TOKEN", request.getAccessToken()); return doRequest(post, PasscodeCreateGatheringResult.class); }
From source file:io.gs2.ranking.Gs2RankingClient.java
/** * ????<br>/*w w w. j av a 2s . com*/ * <br> * * @param request * @return ? */ public CreateGameModeResult createGameMode(CreateGameModeRequest request) { ObjectNode body = JsonNodeFactory.instance.objectNode().put("gameMode", request.getGameMode()) .put("asc", request.getAsc()).put("calcInterval", request.getCalcInterval()); if (request.getPutScoreTriggerScript() != null) body.put("putScoreTriggerScript", request.getPutScoreTriggerScript()); if (request.getPutScoreDoneTriggerScript() != null) body.put("putScoreDoneTriggerScript", request.getPutScoreDoneTriggerScript()); if (request.getCalculateRankingDoneTriggerScript() != null) body.put("calculateRankingDoneTriggerScript", request.getCalculateRankingDoneTriggerScript()); HttpPost post = createHttpPost(Gs2Constant.ENDPOINT_HOST + "/ranking/" + (request.getRankingTableName() == null || request.getRankingTableName().equals("") ? "null" : request.getRankingTableName()) + "/mode", credential, ENDPOINT, CreateGameModeRequest.Constant.MODULE, CreateGameModeRequest.Constant.FUNCTION, body.toString()); if (request.getRequestId() != null) { post.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } return doRequest(post, CreateGameModeResult.class); }
From source file:com.hrm.controller.RegisterController.java
/** * author qwc/* www . java 2s .co m*/ * 201741?9:21:32 * @param request * @param response * @throws IOException * ?? */ @RequestMapping("checkAccount") public void checkPAccount(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); ObjectMapper mapper = new ObjectMapper(); ObjectNode checkStatus = mapper.createObjectNode(); int checkAmount = 0; String account = null; String StuAccount = request.getParameter("username"); String ComAccount = request.getParameter("comusername"); if (StuAccount != null) { account = StuAccount; checkAmount = IComServiceImplRegister.accountCheckService(account); } else { account = ComAccount; checkAmount = IComServiceImplRegister.accountCheckService(account); } if (checkAmount == 0) { checkStatus.put("valid", true); out.write(checkStatus.toString());/*?*/ } else { checkStatus.put("valid", false); out.write(checkStatus.toString());/*?*/ } }
From source file:controllers.CommentController.java
public Result getComment(Long id, Long versionId, String email, String format) { System.out.println("GET COMMENT"); ObjectNode response = Json.newObject(); ObjectNode result = Json.newObject(); ObjectNode user = Json.newObject();/*from w w w .j a v a2 s .co m*/ JsonNode json = request().body().asJson(); // User node if (userRepository.getUserIdByEmail(email) == null) { user.put("user_id", -1); user.put("fullname", "Visitor"); user.put("is_logged_in", false); user.put("is_add_allowed", false); user.put("is_edit_allowed", false); } else { user.put("user_id", userRepository.getUserIdByEmail(email)); user.put("fullname", userRepository.getUsernameByEmail(email)); user.put("is_logged_in", true); user.put("is_add_allowed", true); user.put("is_edit_allowed", true); } user.put("picture", "/assets/images/user_blank_picture.png"); // result result.put("comments", getCommentArray(id, versionId, 0L)); result.put("total_comment", commentRepository.countComments(id, versionId)); result.put("user", user); // response response.put("results", result); return ok(response.toString()); }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
/** * {@inheritDoc }//www.java 2 s . c o m */ @Override protected InputStream normalizeLinks(final String entitySetName, final String entityKey, final InputStream is, final NavigationLinks links) throws Exception { final ObjectMapper mapper = new ObjectMapper(); final ObjectNode srcNode = (ObjectNode) mapper.readTree(is); if (links != null) { for (String linkTitle : links.getLinkNames()) { // normalize link srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX); srcNode.set(linkTitle + JSON_NAVIGATION_SUFFIX, new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle))); } for (String linkTitle : links.getInlineNames()) { // normalize link if exist; declare a new one if missing srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX); srcNode.set(linkTitle + JSON_NAVIGATION_SUFFIX, new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle))); // remove inline srcNode.remove(linkTitle); // remove from links links.removeLink(linkTitle); } } srcNode.set(JSON_EDITLINK_NAME, new TextNode(Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")")); return IOUtils.toInputStream(srcNode.toString()); }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
@Override public InputStream readEntities(final List<String> links, final String linkName, final String next, final boolean forceFeed) throws Exception { if (links.isEmpty()) { throw new NotFoundException(); }/*from w ww . j ava 2 s.c om*/ final ObjectMapper mapper = new ObjectMapper(); final ObjectNode node = mapper.createObjectNode(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (forceFeed || links.size() > 1) { bos.write("[".getBytes()); } for (String link : links) { try { final Map.Entry<String, String> uri = Commons.parseEntityURI(link); final Map.Entry<String, InputStream> entity = readEntity(uri.getKey(), uri.getValue(), Accept.JSON_FULLMETA); if (bos.size() > 1) { bos.write(",".getBytes()); } IOUtils.copy(entity.getValue(), bos); } catch (Exception e) { // log and ignore link LOG.warn("Error parsing uri {}", link, e); } } if (forceFeed || links.size() > 1) { bos.write("]".getBytes()); } node.set(JSON_VALUE_NAME, mapper.readTree(new ByteArrayInputStream(bos.toByteArray()))); if (StringUtils.isNotBlank(next)) { node.set(JSON_NEXTLINK_NAME, new TextNode(next)); } return IOUtils.toInputStream(node.toString()); }
From source file:org.activiti.rest.service.api.runtime.TaskResourceTest.java
/** * Test updating a single task. PUT runtime/tasks/{taskId} *///from w w w .j a v a2 s . c o m public void testUpdateTask() throws Exception { try { Task task = taskService.newTask(); taskService.saveTask(task); Task parentTask = taskService.newTask(); taskService.saveTask(parentTask); ObjectNode requestNode = objectMapper.createObjectNode(); Calendar dueDate = Calendar.getInstance(); String dueDateString = getISODateString(dueDate.getTime()); requestNode.put("name", "New task name"); requestNode.put("description", "New task description"); requestNode.put("assignee", "assignee"); requestNode.put("owner", "owner"); requestNode.put("priority", 20); requestNode.put("delegationState", "resolved"); requestNode.put("dueDate", dueDateString); requestNode.put("parentTaskId", parentTask.getId()); // Execute the request HttpPut httpPut = new HttpPut( SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK, task.getId())); httpPut.setEntity(new StringEntity(requestNode.toString())); closeResponse(executeRequest(httpPut, HttpStatus.SC_OK)); task = taskService.createTaskQuery().taskId(task.getId()).singleResult(); assertEquals("New task name", task.getName()); assertEquals("New task description", task.getDescription()); assertEquals("assignee", task.getAssignee()); assertEquals("owner", task.getOwner()); assertEquals(20, task.getPriority()); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); assertEquals(dateFormat.parse(dueDateString), task.getDueDate()); assertEquals(parentTask.getId(), task.getParentTaskId()); } finally { // Clean adhoc-tasks even if test fails List<Task> tasks = taskService.createTaskQuery().list(); for (Task task : tasks) { taskService.deleteTask(task.getId(), true); } } }
From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java
private String indexRowWithDateAndType(JsonEvent event) { Optional<String> formattedType = type.format(event); if (!formattedType.isPresent()) { throw new IllegalStateException( "Issue with type, could not extract field from event " + type.original()); }// w w w.ja v a2 s . co m Optional<String> formattedIndex = index.format(event); if (!formattedIndex.isPresent()) { throw new IllegalStateException( "Issue with index, could not extract field from event: " + index.original()); } Optional<String> formattedDocumentId = Optional.empty(); if (documentId.isPresent()) { formattedDocumentId = documentId.get().format(event); if (!formattedDocumentId.isPresent()) { throw new IllegalStateException( "Issue with index, could not extract field from event: " + index.original()); } } ObjectNode objectNode = OBJECT_MAPPER.createObjectNode(); ObjectNode data = OBJECT_MAPPER.createObjectNode(); // Prepare for adding day to index for each event if (indexIsPrefix) { LocalDate indexDate; // TODO: Not sure how to handle this... what should be the behaviour if the specified timestamp field // does not exist if (event.has(this.timestampField)) { indexDate = LocalDate.parse(event.valueAsString(this.timestampField).substring(0, 10), DateTimeFormatter.ISO_DATE); } else { indexDate = LocalDate.now(); } data.put("_index", formattedIndex.get() + indexDate.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"))); } else { data.put("_index", formattedIndex.get()); } data.put("_type", formattedType.get()); if (formattedDocumentId.isPresent()) { data.put("_id", formattedDocumentId.get()); } objectNode.set("index", data); return objectNode.toString(); }
From source file:edu.nwpu.gemfire.monitor.controllers.PulseController.java
@RequestMapping(value = "/pulseUpdate", method = RequestMethod.POST) public void getPulseUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException { String pulseData = request.getParameter("pulseData"); ObjectNode responseMap = mapper.createObjectNode(); JsonNode requestMap = null;/*ww w .j a v a 2 s . co m*/ try { requestMap = mapper.readTree(pulseData); Iterator<?> keys = requestMap.fieldNames(); // Execute Services while (keys.hasNext()) { String serviceName = keys.next().toString(); try { PulseService pulseService = pulseServiceFactory.getPulseServiceInstance(serviceName); responseMap.put(serviceName, pulseService.execute(request)); } catch (Exception serviceException) { LOGGER.warning("serviceException [for service " + serviceName + "] = " + serviceException.getMessage()); responseMap.put(serviceName, EMPTY_JSON); } } } catch (Exception e) { if (LOGGER.fineEnabled()) { LOGGER.fine("Exception Occurred : " + e.getMessage()); } } // Create Response response.getOutputStream().write(responseMap.toString().getBytes()); }