List of usage examples for com.fasterxml.jackson.databind.node ObjectNode toString
public String toString()
From source file:com.glaf.mail.web.rest.MailTaskResource.java
@GET @POST/* w ww . ja v a 2 s . c o m*/ @Path("/mailList") @ResponseBody @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public byte[] mailList(@Context HttpServletRequest request) { Map<String, Object> params = RequestUtils.getParameterMap(request); MailItemQuery query = new MailItemQuery(); Tools.populate(query, params); logger.debug("params:" + params); String gridType = ParamUtils.getString(params, "gridType"); if (gridType == null) { gridType = "easyui"; } int start = 0; int limit = 10; String orderName = null; String order = null; if ("easyui".equals(gridType)) { int pageNo = ParamUtils.getInt(params, "page"); limit = ParamUtils.getInt(params, "rows"); start = (pageNo - 1) * limit; orderName = ParamUtils.getString(params, "sort"); order = ParamUtils.getString(params, "order"); } else if ("extjs".equals(gridType)) { start = ParamUtils.getInt(params, "start"); limit = ParamUtils.getInt(params, "limit"); orderName = ParamUtils.getString(params, "sort"); order = ParamUtils.getString(params, "dir"); } else if ("yui".equals(gridType)) { start = ParamUtils.getInt(params, "startIndex"); limit = ParamUtils.getInt(params, "results"); orderName = ParamUtils.getString(params, "sort"); order = ParamUtils.getString(params, "dir"); } if (start < 0) { start = 0; } if (limit <= 0) { limit = Paging.DEFAULT_PAGE_SIZE; } int pageNo = start / limit + 1; query.setPageSize(limit); query.setPageNo(pageNo); query.setTaskId(request.getParameter("taskId")); logger.debug("taskId:" + query.getTaskId()); logger.debug("pageNo:" + query.getPageNo()); ObjectNode responseJSON = new ObjectMapper().createObjectNode(); if (query.getTaskId() != null) { int total = mailDataFacede.getMailCount(query); if (total > 0) { responseJSON.put("total", total); responseJSON.put("totalCount", total); responseJSON.put("totalRecords", total); responseJSON.put("start", start); responseJSON.put("startIndex", start); responseJSON.put("limit", limit); responseJSON.put("pageSize", limit); if (StringUtils.isNotEmpty(orderName)) { query.setSortOrder(orderName); if (StringUtils.equals(order, "desc")) { query.setSortOrder("desc"); } } List<MailItem> list = mailDataFacede.getMailItems(query); if (list != null && !list.isEmpty()) { ArrayNode rowsJSON = new ObjectMapper().createArrayNode(); if ("yui".equals(gridType)) { responseJSON.set("records", rowsJSON); } else { responseJSON.set("rows", rowsJSON); } responseJSON.put("lastRow", list.get(list.size() - 1).getId()); for (MailItem mailItem : list) { ObjectNode rowJSON = new ObjectMapper().createObjectNode(); rowJSON.put("id", mailItem.getId()); rowJSON.put("itemId", mailItem.getId()); if (mailItem.getTaskId() != null) { rowJSON.put("taskId", mailItem.getTaskId()); } if (mailItem.getMailTo() != null) { rowJSON.put("mailTo", mailItem.getMailTo()); } if (mailItem.getSendDate() != null) { rowJSON.put("sendDate", DateUtils.getDateTime(mailItem.getSendDate())); } rowJSON.put("sendStatus", mailItem.getSendStatus()); rowJSON.put("retryTimes", mailItem.getRetryTimes()); if (mailItem.getReceiveIP() != null) { rowJSON.put("receiveIP", mailItem.getReceiveIP()); } if (mailItem.getReceiveDate() != null) { rowJSON.put("receiveDate", DateUtils.getDateTime(mailItem.getReceiveDate())); } rowJSON.put("receiveStatus", mailItem.getReceiveStatus()); rowJSON.put("lastModified", mailItem.getLastModified()); rowsJSON.add(rowJSON); } } } } try { return responseJSON.toString().getBytes("UTF-8"); } catch (IOException e) { return responseJSON.toString().getBytes(); } }
From source file:com.glaf.mail.web.rest.MailAccountResource.java
@GET @POST/*from w w w.ja v a2s . c o m*/ @Path("/list") @ResponseBody @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public byte[] list(@Context HttpServletRequest request) { Map<String, Object> params = RequestUtils.getParameterMap(request); MailAccountQuery query = new MailAccountQuery(); Tools.populate(query, params); String gridType = ParamUtils.getString(params, "gridType"); if (gridType == null) { gridType = "easyui"; } int start = 0; int limit = 10; String orderName = null; String order = null; if ("easyui".equals(gridType)) { int pageNo = ParamUtils.getInt(params, "page"); limit = ParamUtils.getInt(params, "rows"); start = (pageNo - 1) * limit; orderName = ParamUtils.getString(params, "sort"); order = ParamUtils.getString(params, "order"); } else if ("extjs".equals(gridType)) { start = ParamUtils.getInt(params, "start"); limit = ParamUtils.getInt(params, "limit"); orderName = ParamUtils.getString(params, "sort"); order = ParamUtils.getString(params, "dir"); } else if ("yui".equals(gridType)) { start = ParamUtils.getInt(params, "startIndex"); limit = ParamUtils.getInt(params, "results"); orderName = ParamUtils.getString(params, "sort"); order = ParamUtils.getString(params, "dir"); } if (start < 0) { start = 0; } if (limit <= 0) { limit = Paging.DEFAULT_PAGE_SIZE; } String actorId = RequestUtils.getActorId(request); query.createBy(actorId); ObjectNode responseJSON = new ObjectMapper().createObjectNode(); int total = mailAccountService.getMailAccountCountByQueryCriteria(query); if (total > 0) { responseJSON.put("total", total); responseJSON.put("totalCount", total); responseJSON.put("totalRecords", total); responseJSON.put("start", start); responseJSON.put("startIndex", start); responseJSON.put("limit", limit); responseJSON.put("pageSize", limit); if (StringUtils.isNotEmpty(orderName)) { query.setSortOrder(orderName); if (StringUtils.equals(order, "desc")) { query.setSortOrder("desc"); } } List<MailAccount> list = mailAccountService.getMailAccountsByQueryCriteria(start, limit, query); if (list != null && !list.isEmpty()) { ArrayNode rowsJSON = new ObjectMapper().createArrayNode(); if ("yui".equals(gridType)) { responseJSON.set("records", rowsJSON); } else { responseJSON.set("rows", rowsJSON); } for (MailAccount mailAccount : list) { ObjectNode rowJSON = new ObjectMapper().createObjectNode(); rowJSON.put("id", mailAccount.getId()); rowJSON.put("mailAccountId", mailAccount.getId()); if (mailAccount.getAccountType() != null) { rowJSON.put("accountType", mailAccount.getAccountType()); } if (mailAccount.getCreateBy() != null) { rowJSON.put("createBy", mailAccount.getCreateBy()); } if (mailAccount.getMailAddress() != null) { rowJSON.put("mailAddress", mailAccount.getMailAddress()); } if (mailAccount.getShowName() != null) { rowJSON.put("showName", mailAccount.getShowName()); } if (mailAccount.getUsername() != null) { rowJSON.put("username", mailAccount.getUsername()); } if (mailAccount.getPassword() != null) { rowJSON.put("password", mailAccount.getPassword()); } if (mailAccount.getPop3Server() != null) { rowJSON.put("pop3Server", mailAccount.getPop3Server()); } rowJSON.put("receivePort", mailAccount.getReceivePort()); if (mailAccount.getSmtpServer() != null) { rowJSON.put("smtpServer", mailAccount.getSmtpServer()); } rowJSON.put("sendPort", mailAccount.getSendPort()); rowJSON.put("autoReceive", mailAccount.autoReceive()); rowJSON.put("rememberPassword", mailAccount.rememberPassword()); rowJSON.put("locked", mailAccount.getLocked()); if (mailAccount.getCreateDate() != null) { rowJSON.put("createDate", DateUtils.getDateTime(mailAccount.getCreateDate())); } rowJSON.put("authFlag", mailAccount.authFlag()); rowsJSON.add(rowJSON); } } } try { return responseJSON.toString().getBytes("UTF-8"); } catch (IOException e) { return responseJSON.toString().getBytes(); } }
From source file:com.appdynamics.analytics.processor.event.ElasticSearchEventService.java
private void processAndSetRequest(String searchRequest, SearchRequestBuilder req, String accountName, String eventType) throws IOException /* */ {//from w ww. j a v a 2 s . c o m /* 1563 */ ObjectNode requestNode = parseSearchRequest(searchRequest); /* */ /* 1565 */ if (requestNode.get("fields") == null) { /* 1566 */ String[] includes = Strings.EMPTY_ARRAY; /* */ /* */ /* */ /* 1570 */ JsonNode sourceNode = requestNode.remove("_source"); /* 1571 */ if ((sourceNode == null) || (sourceNode.asBoolean(Boolean.TRUE.booleanValue()))) { /* 1572 */ if (sourceNode != null) /* */ { /* 1574 */ if (sourceNode.isArray()) { /* 1575 */ includes = arrayOfStringsFromNode((ArrayNode) sourceNode); /* 1576 */ } else if (sourceNode.isTextual()) { /* 1577 */ includes = new String[] { sourceNode.asText() }; /* */ } /* */ } /* 1580 */ ArrayList<String> excludedFields = Lists.newArrayList(EXCLUDED_FIELDS); /* 1581 */ for (HiddenField hiddenField : this.hiddenFieldsService.getHiddenFields(accountName, eventType)) { /* 1582 */ excludedFields.add(hiddenField.getFieldName()); /* */ } /* 1584 */ req.setFetchSource(includes, Strings.toStringArray(excludedFields)); /* */ } else { /* 1586 */ req.setFetchSource(false); /* */ } /* */ } /* */ /* */ /* 1591 */ req.setExtraSource(requestNode.toString()); /* */ }
From source file:com.glaf.core.web.rest.MxSystemParamResource.java
@GET @POST/*from w w w .j av a 2s .co m*/ @Path("/json") @ResponseBody @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public byte[] json(@Context HttpServletRequest request) { ObjectNode responseJSON = new ObjectMapper().createObjectNode(); String serviceKey = request.getParameter("serviceKey"); String businessKey = request.getParameter("businessKey"); try { Map<String, InputDefinition> paramMap = new java.util.HashMap<String, InputDefinition>(); List<InputDefinition> params = systemParamService.getInputDefinitions(serviceKey); if (params != null && !params.isEmpty()) { for (InputDefinition def : params) { paramMap.put(def.getKeyName(), def); } } List<SystemParam> rows = systemParamService.getSystemParams(serviceKey, businessKey); if (rows != null && !rows.isEmpty()) { responseJSON.put("total", rows.size()); ArrayNode rowsJSON = new ObjectMapper().createArrayNode(); for (SystemParam param : rows) { ObjectNode json = new ObjectMapper().createObjectNode(); InputDefinition def = paramMap.get(param.getKeyName()); if (param.getTitle() != null) { json.put("name", param.getTitle() + " (" + param.getKeyName() + ")"); } else { json.put("name", param.getKeyName()); } json.put("title", param.getTitle()); if (param.getStringVal() != null) { json.put("value", param.getStringVal()); } String javaType = param.getJavaType(); if (def != null) { javaType = def.getJavaType(); json.put("group", def.getTypeTitle()); } else { json.put("group", param.getTypeCd()); } if ("Integer".equals(javaType)) { json.put("editor", "numberbox"); } else if ("Long".equals(javaType)) { json.put("editor", "numberbox"); } else if ("Double".equals(javaType)) { json.put("editor", "numberbox"); } else if ("Date".equals(javaType)) { json.put("editor", "datebox"); } else { json.put("editor", "text"); if (def != null) { String inputType = def.getInputType(); String validType = def.getValidType(); if (StringUtils.isNotEmpty(def.getRequired())) { json.put("required", def.getRequired()); } ObjectNode editor = new ObjectMapper().createObjectNode(); ObjectNode options = new ObjectMapper().createObjectNode(); if (validType != null) { options.put("validType", validType); } if (inputType != null) { if ("checkbox".equals(inputType)) { options.put("on", true); options.put("off", false); } if ("combobox".equals(inputType)) { options.put("valueField", def.getValueField()); options.put("textField", def.getTextField()); if (def.getUrl() != null) { options.put("url", request.getContextPath() + def.getUrl()); } if (StringUtils.isNotEmpty(def.getRequired())) { options.put("required", def.getRequired()); } } } editor.put("type", inputType); if (options.size() > 0) { editor.set("options", options); } json.set("editor", editor); } } rowsJSON.add(json); } responseJSON.set("rows", rowsJSON); } logger.debug(responseJSON.toString()); return responseJSON.toString().getBytes("UTF-8"); } catch (IOException e) { return responseJSON.toString().getBytes(); } }
From source file:org.activiti.rest.service.api.history.HistoricProcessInstanceQueryResourceTest.java
/** * Test querying historic process instance based on variables. POST query/historic-process-instances *///from ww w . j a v a 2 s .co m @Deployment public void testQueryProcessInstancesWithVariables() throws Exception { HashMap<String, Object> processVariables = new HashMap<String, Object>(); processVariables.put("stringVar", "Azerty"); processVariables.put("intVar", 67890); processVariables.put("booleanVar", false); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables); String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_QUERY); // Process variables ObjectNode requestNode = objectMapper.createObjectNode(); ArrayNode variableArray = objectMapper.createArrayNode(); ObjectNode variableNode = objectMapper.createObjectNode(); variableArray.add(variableNode); requestNode.put("variables", variableArray); // String equals variableNode.put("name", "stringVar"); variableNode.put("value", "Azerty"); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Integer equals variableNode.removeAll(); variableNode.put("name", "intVar"); variableNode.put("value", 67890); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Boolean equals variableNode.removeAll(); variableNode.put("name", "booleanVar"); variableNode.put("value", false); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String not equals variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "ghijkl"); variableNode.put("operation", "notEquals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Integer not equals variableNode.removeAll(); variableNode.put("name", "intVar"); variableNode.put("value", 45678); variableNode.put("operation", "notEquals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Boolean not equals variableNode.removeAll(); variableNode.put("name", "booleanVar"); variableNode.put("value", true); variableNode.put("operation", "notEquals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String equals ignore case variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "azeRTY"); variableNode.put("operation", "equalsIgnoreCase"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String not equals ignore case (not supported) variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "HIJKLm"); variableNode.put("operation", "notEqualsIgnoreCase"); assertErrorResult(url, requestNode, HttpStatus.SC_BAD_REQUEST); // String equals without value variableNode.removeAll(); variableNode.put("value", "Azerty"); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String equals with non existing value variableNode.removeAll(); variableNode.put("value", "Azerty2"); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode); // String like ignore case variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "azerty"); variableNode.put("operation", "likeIgnoreCase"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "azerty2"); variableNode.put("operation", "likeIgnoreCase"); assertResultsPresentInPostDataResponse(url, requestNode); requestNode = objectMapper.createObjectNode(); requestNode.put("finished", true); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("finished", false); assertResultsPresentInPostDataResponse(url, requestNode, processInstance2.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("processDefinitionId", processInstance.getProcessDefinitionId()); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("processDefinitionKey", "oneTaskProcess"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("processDefinitionKey", "oneTaskProcess"); HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + url + "?sort=startTime"); httpPost.setEntity(new StringEntity(requestNode.toString())); CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_OK); // Check status and size JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data"); closeResponse(response); assertEquals(2, dataNode.size()); assertEquals(processInstance.getId(), dataNode.get(0).get("id").asText()); assertEquals(processInstance2.getId(), dataNode.get(1).get("id").asText()); }
From source file:org.flowable.rest.service.api.history.HistoricProcessInstanceQueryResourceTest.java
/** * Test querying historic process instance based on variables. POST query/historic-process-instances *///from ww w . j a v a 2s .c o m @Deployment public void testQueryProcessInstancesWithVariables() throws Exception { HashMap<String, Object> processVariables = new HashMap<String, Object>(); processVariables.put("stringVar", "Azerty"); processVariables.put("intVar", 67890); processVariables.put("booleanVar", false); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables); String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_QUERY); // Process variables ObjectNode requestNode = objectMapper.createObjectNode(); ArrayNode variableArray = objectMapper.createArrayNode(); ObjectNode variableNode = objectMapper.createObjectNode(); variableArray.add(variableNode); requestNode.set("variables", variableArray); // String equals variableNode.put("name", "stringVar"); variableNode.put("value", "Azerty"); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Integer equals variableNode.removeAll(); variableNode.put("name", "intVar"); variableNode.put("value", 67890); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Boolean equals variableNode.removeAll(); variableNode.put("name", "booleanVar"); variableNode.put("value", false); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String not equals variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "ghijkl"); variableNode.put("operation", "notEquals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Integer not equals variableNode.removeAll(); variableNode.put("name", "intVar"); variableNode.put("value", 45678); variableNode.put("operation", "notEquals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // Boolean not equals variableNode.removeAll(); variableNode.put("name", "booleanVar"); variableNode.put("value", true); variableNode.put("operation", "notEquals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String equals ignore case variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "azeRTY"); variableNode.put("operation", "equalsIgnoreCase"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String not equals ignore case (not supported) variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "HIJKLm"); variableNode.put("operation", "notEqualsIgnoreCase"); assertErrorResult(url, requestNode, HttpStatus.SC_BAD_REQUEST); // String equals without value variableNode.removeAll(); variableNode.put("value", "Azerty"); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); // String equals with non existing value variableNode.removeAll(); variableNode.put("value", "Azerty2"); variableNode.put("operation", "equals"); assertResultsPresentInPostDataResponse(url, requestNode); // String like ignore case variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "azerty"); variableNode.put("operation", "likeIgnoreCase"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); variableNode.removeAll(); variableNode.put("name", "stringVar"); variableNode.put("value", "azerty2"); variableNode.put("operation", "likeIgnoreCase"); assertResultsPresentInPostDataResponse(url, requestNode); requestNode = objectMapper.createObjectNode(); requestNode.put("finished", true); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("finished", false); assertResultsPresentInPostDataResponse(url, requestNode, processInstance2.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("processDefinitionId", processInstance.getProcessDefinitionId()); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("processDefinitionKey", "oneTaskProcess"); assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId()); requestNode = objectMapper.createObjectNode(); requestNode.put("processDefinitionKey", "oneTaskProcess"); HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + url + "?sort=startTime"); httpPost.setEntity(new StringEntity(requestNode.toString())); CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_OK); // Check status and size JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data"); closeResponse(response); assertEquals(2, dataNode.size()); assertEquals(processInstance.getId(), dataNode.get(0).get("id").asText()); assertEquals(processInstance2.getId(), dataNode.get(1).get("id").asText()); }
From source file:gov.osti.services.Metadata.java
/** * Acquire a listing of all records by OWNER. * * @param rows the number of rows desired (if present) * @param start the starting row number (from 0) * @return the Metadata information in the desired format * @throws JsonProcessingException// w w w .j av a2 s .c om */ @GET @Path("/projects") @Produces(MediaType.APPLICATION_JSON) @RequiresAuthentication public Response listProjects(@QueryParam("rows") int rows, @QueryParam("start") int start) throws JsonProcessingException { EntityManager em = DoeServletContextListener.createEntityManager(); // get the security user in context Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); try { Set<String> roles = user.getRoles(); String rolecode = (null == roles) ? "" : (roles.isEmpty()) ? "" : roles.iterator().next(); TypedQuery<DOECodeMetadata> query; // admins see ALL PROJECTS if ("OSTI".equals(rolecode)) { query = em.createQuery("SELECT md FROM DOECodeMetadata md", DOECodeMetadata.class); } else if (StringUtils.isNotEmpty(rolecode)) { // if you have another ROLE, it is assumed to be a SITE ADMIN; see all those records query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.siteOwnershipCode = :site", DOECodeMetadata.class).setParameter("site", rolecode); } else { // no roles, you see only YOUR OWN projects query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.owner = lower(:owner)", DOECodeMetadata.class).setParameter("owner", user.getEmail()); } // if rows specified, and greater than 100, cap it there rows = (rows > 100) ? 100 : rows; // if pagination elements are present, set them on the query if (0 != rows) query.setMaxResults(rows); if (0 != start) query.setFirstResult(start); // get a List of records RecordsList records = new RecordsList(query.getResultList()); records.setStart(start); ObjectNode recordsObject = mapper.valueToTree(records); // lookup previous Snapshot status info for each item TypedQuery<MetadataSnapshot> querySnapshot = em .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class) .setParameter("status", DOECodeMetadata.Status.Approved); // lookup system Snapshot status info for each item TypedQuery<MetadataSnapshot> querySystemSnapshot = em .createNamedQuery("MetadataSnapshot.findByCodeIdAsSystemStatus", MetadataSnapshot.class) .setParameter("status", DOECodeMetadata.Status.Approved); JsonNode recordNode = recordsObject.get("records"); if (recordNode.isArray()) { int rowCount = 0; for (JsonNode objNode : recordNode) { rowCount++; // skip non-approved records String currentStatus = objNode.get("workflow_status").asText(); if (!currentStatus.equalsIgnoreCase("Approved")) continue; // get code_id to find Snapshot long codeId = objNode.get("code_id").asLong(); querySnapshot.setParameter("codeId", codeId); querySystemSnapshot.setParameter("codeId", codeId); String lastApprovalFor = ""; List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList(); for (MetadataSnapshot ms : results) { lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString(); } // add "approve as" status indicator to response record, if not blank if (!StringUtils.isBlank(lastApprovalFor)) ((ObjectNode) objNode).put("approved_as", lastApprovalFor); String systemStatus = ""; List<MetadataSnapshot> resultsSystem = querySystemSnapshot.setMaxResults(1).getResultList(); for (MetadataSnapshot ms : resultsSystem) { systemStatus = ms.getSnapshotKey().getSnapshotStatus().toString(); } // add "system status" indicator to response record, if not blank if (!StringUtils.isBlank(lastApprovalFor)) ((ObjectNode) objNode).put("system_status", systemStatus); } recordsObject.put("total", rowCount); } return Response.status(Response.Status.OK).entity(recordsObject.toString()).build(); } finally { em.close(); } }
From source file:org.bimserver.servlets.UploadServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getHeader("Origin") != null && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) { response.setStatus(403);// w w w. j a v a 2s . c o m return; } response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); String token = (String) request.getSession().getAttribute("token"); ObjectNode result = OBJECT_MAPPER.createObjectNode(); response.setContentType("text/json"); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); long poid = -1; String comment = null; if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); InputStream in = null; String name = ""; long deserializerOid = -1; boolean merge = false; boolean sync = false; String compression = null; String action = null; long topicId = -1; while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { if ("action".equals(item.getFieldName())) { action = Streams.asString(item.openStream()); } else if ("token".equals(item.getFieldName())) { token = Streams.asString(item.openStream()); } else if ("poid".equals(item.getFieldName())) { poid = Long.parseLong(Streams.asString(item.openStream())); } else if ("comment".equals(item.getFieldName())) { comment = Streams.asString(item.openStream()); } else if ("topicId".equals(item.getFieldName())) { topicId = Long.parseLong(Streams.asString(item.openStream())); } else if ("sync".equals(item.getFieldName())) { sync = Streams.asString(item.openStream()).equals("true"); } else if ("merge".equals(item.getFieldName())) { merge = Streams.asString(item.openStream()).equals("true"); } else if ("compression".equals(item.getFieldName())) { compression = Streams.asString(item.openStream()); } else if ("deserializerOid".equals(item.getFieldName())) { deserializerOid = Long.parseLong(Streams.asString(item.openStream())); } } else { name = item.getName(); in = item.openStream(); if ("file".equals(action)) { ServiceInterface serviceInterface = getBimServer().getServiceFactory() .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class); SFile file = new SFile(); byte[] data = IOUtils.toByteArray(in); file.setData(data); file.setSize(data.length); file.setFilename(name); file.setMime(item.getContentType()); result.put("fileId", serviceInterface.uploadFile(file)); } else if (poid != -1) { InputStream realStream = null; if ("gzip".equals(compression)) { realStream = new GZIPInputStream(in); } else if ("deflate".equals(compression)) { realStream = new InflaterInputStream(in); } else { realStream = in; } InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(realStream); inputStreamDataSource.setName(name); DataHandler ifcFile = new DataHandler(inputStreamDataSource); if (token != null) { if (topicId == -1) { ServiceInterface service = getBimServer().getServiceFactory() .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class); long newTopicId = service.checkin(poid, comment, deserializerOid, -1L, name, ifcFile, merge, sync); result.put("topicId", newTopicId); } else { ServiceInterface service = getBimServer().getServiceFactory() .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class); long newTopicId = service.checkinInitiated(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge, true); result.put("topicId", newTopicId); } } } else { result.put("exception", "No poid"); } } } } } catch (Exception e) { LOGGER.error("", e); sendException(response, e); return; } response.getWriter().write(result.toString()); }