List of usage examples for java.util Map clear
void clear();
From source file:com.esd.ps.InspectorController.java
/** * /*w w w . ja v a2s. c o m*/ * * @param taskEffective * @param day * @param workerId * @param firstDate * @param lastDate * @param session * @return */ @RequestMapping(value = "/auditing", method = RequestMethod.POST) @ResponseBody public Map<String, Object> auditingPost(int taskEffective, int day, int workerId, HttpSession session, String note) { Map<String, Object> map = new HashMap<>(); int userId = Integer.parseInt(session.getAttribute("userId").toString()); int inspectorrecordId = 0; //StackTraceElement[] items = Thread.currentThread().getStackTrace(); int m = taskService.updateAduitByWorkerId(workerId, taskEffective); List<Integer> packList = null; if (m > 0) { if (taskEffective == 0 && note.length() > 0) { inspectorrecord inspectorrecord = new inspectorrecord(); inspectorrecord.setInspectorid(userId); inspectorrecord.setNote(note); inspectorRecordService.insertSelective(inspectorrecord); inspectorrecordId = inspectorRecordService.getMaxIdByInspectorId(userId); } inspector ins = inspectorService.getinspectorByUserId(userId); int insId = 0; if (ins != null) { insId = ins.getInspectorId(); } else { insId = 0; } //?? if (taskEffective == 1) { salaryService.insertTimer(workerId); packList = workerRecordService.getPackIdByDateTime2(workerId); } if (day > 0) { day = 3600 * 1000 * day; } workerRecordService.updateAduitByWorkerId2(workerId, taskEffective, day, insId, inspectorrecordId); } else { map.clear(); map.put(Constants.REPLAY, 0); map.put(Constants.MESSAGE, "!"); return map; } /** * ?,?packpack_status */ if (taskEffective == 1) { for (Iterator<Integer> iterator = packList.iterator(); iterator.hasNext();) { Integer packId = (Integer) iterator.next(); // pack = (? + )+ wav.length0 if (taskService .getTaskCountByPackId(packId) == (workerRecordService.getFinishTaskCountByPackId(packId, 2) + taskService.getWorkerIdZeroCountByPackId(packId))) { packWithBLOBs pack = new packWithBLOBs(); pack.setPackId(packId); pack.setPackStatus(1); packService.updateByPrimaryKeySelective(pack); } } } map.clear(); map.put(Constants.REPLAY, 1); map.put(Constants.MESSAGE, "?"); return map; }
From source file:org.hsweb.web.controller.config.ConfigController.java
/** * ??["core.system.version","upload.path"] ?coresystem.versionuploadpath * <br/>: {"core":{"system.version":"1.0"},"upload":{"path":"/files"}} * * @param ids ??/*w ww. jav a 2 s .co m*/ * @return ? */ @RequestMapping(value = "/info", method = RequestMethod.GET) @Cacheable(value = CACHE_KEY, key = "'info_list'+#ids.hashCode()") @AccessLogger("???") public Object batch(@RequestParam(value = "ids", defaultValue = "[]") String ids, boolean map) { List<String> requestData = JSON.parseArray(ids, String.class); //?? Map<String, Object> config = new LinkedHashMap<>(); //: cfg.name,cfg.data,cfg.other?cfg????? Map<String, Map<String, String>> temp = new LinkedHashMap<>(); for (String request : requestData) { Config conf = null; try { conf = configService.selectByPk(request); } catch (Exception e) { } //?[.]??: core.system.version,?core?system.version if (conf == null && request.contains(".")) { String[] res = request.split("[.]", 2); String name = res[0]; //: core String key = res[1]; //: system.version Map cache; //?? if ((cache = temp.get(name)) == null) { try { conf = configService.selectByPk(name); cache = conf.toMap(); } catch (Exception e) { } if (cache == null) { config.put(request, new LinkedHashMap<>()); continue; } temp.put(name, cache); } Map<String, Object> tmp = (Map) config.get(name); if (tmp != null) { tmp.put(key, cache.get(key)); } else { tmp = new LinkedHashMap<>(); tmp.put(key, cache.get(key)); config.put(name, tmp); } } else { //?? if (conf != null) { config.put(request, map ? conf.toMap() : conf.toList()); } } } temp.clear(); return config; }
From source file:fragment.web.SupportControllerTest.java
@Test public void testListTicketsPageAsRootOtherTenant() throws Exception { Tenant otherTenant = tenantDAO.find(2L); User otherMasterUser = otherTenant.getOwner(); userDAO.save(otherMasterUser);//from w ww . j a v a 2s . c om asUser(otherMasterUser); Tenant systemTenant = controller.getCurrentUser().getTenant(); createTestTicket(3, otherTenant, otherMasterUser); asUser(getRootUser()); systemTenant = controller.getCurrentUser().getTenant(); String view = controller.listTicketsPage(systemTenant, tenant.getUuid(), "All", false, "", "", "", map, request); List<TicketStatus> listTicketStatus = new ArrayList<Ticket.TicketStatus>(); listTicketStatus.add(TicketStatus.NEW); listTicketStatus.add(TicketStatus.CLOSED); listTicketStatus.add(TicketStatus.ESCALATED); listTicketStatus.add(TicketStatus.WORKING); List<User> users = new ArrayList<User>(); users.add(user); Map<String, String> responseAttribute = new HashMap<String, String>(); responseAttribute.put("queryLocator", "xyz"); List<Ticket> tickets = supportService.list(0, 0, listTicketStatus, users, "", "", responseAttribute); Assert.assertEquals("support.tickets.list", view); Assert.assertTrue(map.containsKey("tickets")); Assert.assertTrue(map.containsValue(tickets)); @SuppressWarnings("unchecked") List<String> list = (List<String>) map.get("tickets"); Assert.assertEquals(5, list.size()); systemTenant = controller.getCurrentUser().getTenant(); view = controller.listTicketsPage(systemTenant, otherTenant.getUuid(), "All", false, "", "", "", map, request); responseAttribute.clear(); responseAttribute.put("queryLocator", "xyz"); Assert.assertEquals("support.tickets.list", view); Assert.assertTrue(map.containsKey("tickets")); @SuppressWarnings("unchecked") List<String> list1 = (List<String>) map.get("tickets"); Assert.assertEquals(9, list1.size()); }
From source file:com.imaginary.home.device.hue.HueBulb.java
private @Nonnegative boolean fade(@Nonnull TimePeriod<?> transitionTime, @Nonnegative int targetBrightness) throws CommunicationException { logger.debug("Fading to " + targetBrightness + " over " + transitionTime + " for " + bulbId); if (targetBrightness < 0) { targetBrightness = 0;//from w w w . ja v a 2 s .c om } int currentBrightness = (int) ((getBrightness() * 254) / 100); boolean on = isOn(); if ((on && targetBrightness == currentBrightness) || (!on && targetBrightness == 0)) { if (logger.isDebugEnabled()) { logger.debug("Nothing to do for " + bulbId); } return false; } if (!on) { logger.debug("Bulb is currently off"); currentBrightness = 0; } if (logger.isDebugEnabled()) { logger.debug(bulbId + ".currentBrightness=" + currentBrightness); } int distance; if (targetBrightness == 0) { distance = currentBrightness; } else if (targetBrightness > currentBrightness) { distance = targetBrightness - currentBrightness; } else { distance = currentBrightness - targetBrightness; } if (logger.isDebugEnabled()) { logger.debug(bulbId + ".distance=" + distance); } int conversionTime = transitionTime.convertTo(TimePeriod.MILLISECOND).intValue() / 100; Map<String, Object> state = new HashMap<String, Object>(); long startTimestamp = System.currentTimeMillis(); String resource = "lights/" + bulbId + "/state"; HueMethod method = new HueMethod(hue); if (conversionTime < 1) { conversionTime = 1; } if (!on) { state.put("on", true); state.put("bri", 0); if (logger.isDebugEnabled()) { logger.debug("Turning " + bulbId + " on..."); } try { method.put(resource, new JSONObject(state)); } catch (Throwable t) { t.printStackTrace(); } } int interval = 100; int step = 1; if (conversionTime < distance) { step = distance / conversionTime; } else { interval = (conversionTime / distance) * 100; } if (logger.isDebugEnabled()) { logger.debug(bulbId + " -> interval + =" + interval + ", step=" + step); } int stepCount = distance / step; if (logger.isDebugEnabled()) { logger.debug(bulbId + ".stepCount=" + stepCount); } if (targetBrightness < currentBrightness) { step = -step; } state.clear(); for (int i = 0; i < stepCount; i++) { try { Thread.sleep(interval); } catch (InterruptedException ignore) { } // adjust for slow network int actual = (int) (System.currentTimeMillis() - startTimestamp) / interval; int bri = currentBrightness + (actual * step); if (bri <= 254 && bri >= 0) { state.put("bri", bri); if (logger.isTraceEnabled()) { logger.debug(bulbId + " -> setting brightness to " + bri); } try { method.put(resource, new JSONObject(state)); } catch (HueException ignore) { } } if (bri == targetBrightness) { break; } } if (getBrightness() != targetBrightness) { if (logger.isDebugEnabled()) { logger.debug(bulbId + " -> cleaning up"); } state.clear(); state.put("bri", targetBrightness); try { method.put(resource, new JSONObject(state)); } catch (HueException ignore) { } } if (targetBrightness == 0) { if (logger.isDebugEnabled()) { logger.debug(bulbId + " -> turning off"); } flip(false); } int brightness = (int) ((getBrightness() * 254) / 100); if (logger.isDebugEnabled()) { logger.debug(bulbId + ".brightness=" + brightness); } return true; }
From source file:com.linkedin.pinot.integration.tests.BaseClusterIntegrationTest.java
/** * Run equivalent Pinot and H2 query and compare the results. * <p>LIMITATIONS://from w w w . j a v a2s .c o m * <ul> * <li>Skip comparison for selection and aggregation group-by when H2 results are too large to exhaust.</li> * <li>Do not examine the order of result records.</li> * </ul> * * @param pqlQuery Pinot PQL query. * @param sqlQueries H2 SQL queries. * @throws Exception */ protected void runQuery(String pqlQuery, @Nullable List<String> sqlQueries) throws Exception { try { _queryCount++; // Run the query. // TODO Use Pinot client API for this JSONObject response = postQuery(pqlQuery); // Check exceptions. JSONArray exceptions = response.getJSONArray("exceptions"); if (exceptions.length() > 0) { String failureMessage = "Got exceptions: " + exceptions; failure(pqlQuery, sqlQueries, failureMessage, null); return; } // Check total docs. long numTotalDocs = response.getLong("totalDocs"); if (numTotalDocs != TOTAL_DOCS) { String failureMessage = "Number of total documents does not match, expected: " + TOTAL_DOCS + ", got: " + numTotalDocs; failure(pqlQuery, sqlQueries, failureMessage, null); return; } // Skip comparison if SQL queries not specified. if (sqlQueries == null) { return; } // Check results. Statement h2statement = _connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); int numDocsScanned = response.getInt("numDocsScanned"); if (response.has("aggregationResults")) { // Aggregation and Group-by results. // Get results type. JSONArray aggregationResultsArray = response.getJSONArray("aggregationResults"); int numAggregationResults = aggregationResultsArray.length(); int numSqlQueries = sqlQueries.size(); if (numAggregationResults != numSqlQueries) { String failureMessage = "Number of aggregation results: " + numAggregationResults + " does not match number of SQL queries: " + numSqlQueries; failure(pqlQuery, sqlQueries, failureMessage); } JSONObject firstAggregationResult = aggregationResultsArray.getJSONObject(0); if (firstAggregationResult.has("value")) { // Aggregation results. // Check over all aggregation functions. for (int i = 0; i < numAggregationResults; i++) { // Get expected value for the aggregation. h2statement.execute(sqlQueries.get(i)); ResultSet sqlResultSet = h2statement.getResultSet(); sqlResultSet.first(); String sqlValue = sqlResultSet.getString(1); // If SQL value is null, it means no record selected in H2. if (sqlValue == null) { // Check number of documents scanned is 0. if (numDocsScanned != 0) { String failureMessage = "No record selected in H2 but number of records selected in Pinot: " + numDocsScanned; failure(pqlQuery, sqlQueries, failureMessage); } // Skip further comparison. return; } // Get actual value for the aggregation. String pqlValue = aggregationResultsArray.getJSONObject(i).getString("value"); // Fuzzy compare expected value and actual value. double expectedValue = Double.parseDouble(sqlValue); double actualValue = Double.parseDouble(pqlValue); if (Math.abs(actualValue - expectedValue) >= 1.0) { String failureMessage = "Value: " + i + " does not match, expected: " + sqlValue + ", got: " + pqlValue; failure(pqlQuery, sqlQueries, failureMessage); return; } } } else if (firstAggregationResult.has("groupByResult")) { // Group-by results. // Get number of groups and number of group keys in each group. JSONArray firstGroupByResults = aggregationResultsArray.getJSONObject(0) .getJSONArray("groupByResult"); int numGroups = firstGroupByResults.length(); // If no group-by result returned by Pinot, set numGroupKeys to 0 since no comparison needed. int numGroupKeys; if (numGroups == 0) { numGroupKeys = 0; } else { numGroupKeys = firstGroupByResults.getJSONObject(0).getJSONArray("group").length(); } // Check over all aggregation functions. for (int i = 0; i < numAggregationResults; i++) { // Get number of group keys. JSONArray groupByResults = aggregationResultsArray.getJSONObject(i) .getJSONArray("groupByResult"); // Construct expected result map from group keys to value. h2statement.execute(sqlQueries.get(i)); ResultSet sqlResultSet = h2statement.getResultSet(); Map<String, String> expectedValues = new HashMap<>(); int sqlNumGroups; for (sqlNumGroups = 0; sqlResultSet.next() && sqlNumGroups < MAX_COMPARISON_LIMIT; sqlNumGroups++) { if (numGroupKeys != 0) { StringBuilder groupKey = new StringBuilder(); for (int groupKeyIndex = 1; groupKeyIndex <= numGroupKeys; groupKeyIndex++) { // Convert boolean value to lower case. groupKey.append( convertBooleanToLowerCase(sqlResultSet.getString(groupKeyIndex))) .append(' '); } expectedValues.put(groupKey.toString(), sqlResultSet.getString(numGroupKeys + 1)); } } if (sqlNumGroups == 0) { // No record selected in H2. // Check if no record selected in Pinot. if (numGroups != 0) { String failureMessage = "No group returned in H2 but number of groups returned in Pinot: " + numGroups; failure(pqlQuery, sqlQueries, failureMessage); return; } // Check if number of documents scanned is 0. if (numDocsScanned != 0) { String failureMessage = "No group returned in Pinot but number of records selected: " + numDocsScanned; failure(pqlQuery, sqlQueries, failureMessage); } // Skip further comparison. return; } else if (sqlNumGroups < MAX_COMPARISON_LIMIT) { // Only compare exhausted results. // Check that all Pinot results are contained in the H2 results. for (int resultIndex = 0; resultIndex < numGroups; resultIndex++) { // Fetch Pinot group keys. JSONObject groupByResult = groupByResults.getJSONObject(resultIndex); JSONArray group = groupByResult.getJSONArray("group"); StringBuilder groupKeyBuilder = new StringBuilder(); for (int groupKeyIndex = 0; groupKeyIndex < numGroupKeys; groupKeyIndex++) { groupKeyBuilder.append(group.getString(groupKeyIndex)).append(' '); } String groupKey = groupKeyBuilder.toString(); // Check if Pinot group keys contained in H2 results. if (!expectedValues.containsKey(groupKey)) { String failureMessage = "Group returned in Pinot but not in H2: " + groupKey; failure(pqlQuery, sqlQueries, failureMessage); return; } // Fuzzy compare expected value and actual value. String sqlValue = expectedValues.get(groupKey); String pqlValue = groupByResult.getString("value"); double expectedValue = Double.parseDouble(sqlValue); double actualValue = Double.parseDouble(pqlValue); if (Math.abs(actualValue - expectedValue) >= 1.0) { String failureMessage = "Value: " + i + " does not match, expected: " + sqlValue + ", got: " + pqlValue + ", for group: " + groupKey; failure(pqlQuery, sqlQueries, failureMessage); return; } } } else { // Cannot get exhausted results. // Skip further comparison. LOGGER.debug("SQL: {} returned at least {} rows, skipping comparison.", sqlQueries.get(0), MAX_COMPARISON_LIMIT); return; } } } else { // Neither aggregation or group-by results. String failureMessage = "Inside aggregation results, no aggregation or group-by results found"; failure(pqlQuery, sqlQueries, failureMessage); } } else if (response.has("selectionResults")) { // Selection results. // Construct expected result set. h2statement.execute(sqlQueries.get(0)); ResultSet sqlResultSet = h2statement.getResultSet(); ResultSetMetaData sqlMetaData = sqlResultSet.getMetaData(); Set<String> expectedValues = new HashSet<>(); Map<String, String> reusableExpectedValueMap = new HashMap<>(); Map<String, List<String>> reusableMultiValuesMap = new HashMap<>(); List<String> reusableColumnOrder = new ArrayList<>(); int numResults; for (numResults = 0; sqlResultSet.next() && numResults < MAX_COMPARISON_LIMIT; numResults++) { reusableExpectedValueMap.clear(); reusableMultiValuesMap.clear(); reusableColumnOrder.clear(); int numColumns = sqlMetaData.getColumnCount(); for (int i = 1; i <= numColumns; i++) { String columnName = sqlMetaData.getColumnName(i); // Handle null result and convert boolean value to lower case. String columnValue = sqlResultSet.getString(i); if (columnValue == null) { columnValue = "null"; } else { columnValue = convertBooleanToLowerCase(columnValue); } // Handle multi-value columns. int length = columnName.length(); if (length > 5 && columnName.substring(length - 5, length - 1).equals("__MV")) { // Multi-value column. String multiValueColumnName = columnName.substring(0, length - 5); List<String> multiValue = reusableMultiValuesMap.get(multiValueColumnName); if (multiValue == null) { multiValue = new ArrayList<>(); reusableMultiValuesMap.put(multiValueColumnName, multiValue); reusableColumnOrder.add(multiValueColumnName); } multiValue.add(columnValue); } else { // Single-value column. reusableExpectedValueMap.put(columnName, columnValue); reusableColumnOrder.add(columnName); } } // Add multi-value column results to the expected values. // The reason for this step is that Pinot does not maintain order of elements in multi-value columns. for (Map.Entry<String, List<String>> entry : reusableMultiValuesMap.entrySet()) { List<String> multiValue = entry.getValue(); Collections.sort(multiValue); reusableExpectedValueMap.put(entry.getKey(), multiValue.toString()); } // Build expected value String. StringBuilder expectedValue = new StringBuilder(); for (String column : reusableColumnOrder) { expectedValue.append(column).append(':').append(reusableExpectedValueMap.get(column)) .append(' '); } expectedValues.add(expectedValue.toString()); } JSONObject selectionColumnsAndResults = response.getJSONObject("selectionResults"); JSONArray selectionColumns = selectionColumnsAndResults.getJSONArray("columns"); JSONArray selectionResults = selectionColumnsAndResults.getJSONArray("results"); int numSelectionResults = selectionResults.length(); if (numResults == 0) { // No record selected in H2. // Check if no record selected in Pinot. if (numSelectionResults != 0) { String failureMessage = "No record selected in H2 but number of records selected in Pinot: " + numSelectionResults; failure(pqlQuery, sqlQueries, failureMessage); return; } // Check if number of documents scanned is 0. if (numDocsScanned != 0) { String failureMessage = "No selection result returned in Pinot but number of records selected: " + numDocsScanned; failure(pqlQuery, sqlQueries, failureMessage); } } else if (numResults < MAX_COMPARISON_LIMIT) { // Only compare exhausted results. // Check that Pinot results are contained in the H2 results. int numColumns = selectionColumns.length(); for (int i = 0; i < numSelectionResults; i++) { // Build actual value String. StringBuilder actualValueBuilder = new StringBuilder(); JSONArray selectionResult = selectionResults.getJSONArray(i); for (int columnIndex = 0; columnIndex < numColumns; columnIndex++) { // Convert column name to all uppercase to make it compatible with H2. String columnName = selectionColumns.getString(columnIndex).toUpperCase(); Object columnResult = selectionResult.get(columnIndex); if (columnResult instanceof JSONArray) { // Multi-value column. JSONArray columnResultsArray = (JSONArray) columnResult; List<String> multiValue = new ArrayList<>(); int length = columnResultsArray.length(); for (int elementIndex = 0; elementIndex < length; elementIndex++) { multiValue.add(columnResultsArray.getString(elementIndex)); } for (int elementIndex = length; elementIndex < MAX_ELEMENTS_IN_MULTI_VALUE; elementIndex++) { multiValue.add("null"); } Collections.sort(multiValue); actualValueBuilder.append(columnName).append(':').append(multiValue.toString()) .append(' '); } else { // Single-value column. actualValueBuilder.append(columnName).append(':').append((String) columnResult) .append(' '); } } String actualValue = actualValueBuilder.toString(); // Check actual value in expected values set. if (!expectedValues.contains(actualValue)) { String failureMessage = "Selection result returned in Pinot but not in H2: " + actualValue; failure(pqlQuery, sqlQueries, failureMessage); return; } } } else { // Cannot get exhausted results. LOGGER.debug("SQL: {} returned at least {} rows, skipping comparison.", sqlQueries.get(0), MAX_COMPARISON_LIMIT); } } else { // Neither aggregation or selection results. String failureMessage = "No aggregation or selection results found for query: " + pqlQuery; failure(pqlQuery, sqlQueries, failureMessage); } } catch (Exception e) { String failureMessage = "Caught exception while running query."; failure(pqlQuery, sqlQueries, failureMessage, e); } }
From source file:com.evolveum.polygon.connector.hcm.DocumentProcessing.java
public String processMultiValuedAttributes(Map<String, String> multiValuedAttributeBuffer) { Map<String, String> renamedAttributes = new HashMap<String, String>(); List<String> unchangedAttributes = new ArrayList<String>(); Boolean typeValueWasSet = false; String typeValue = ""; for (String attributeName : multiValuedAttributeBuffer.keySet()) { String[] nameParts = attributeName.split(DELIMITER); String lastPart = nameParts[nameParts.length - 1]; if (TYPE.equals(lastPart)) { typeValue = multiValuedAttributeBuffer.get(attributeName); typeValueWasSet = true;/* w w w .j a v a 2s . com*/ } else { if (typeValueWasSet) { StringBuilder buildAttributeName = new StringBuilder(attributeName).append(DOT) .append(typeValue); renamedAttributes.put(buildAttributeName.toString(), multiValuedAttributeBuffer.get(attributeName)); } else { unchangedAttributes.add(attributeName); } } } if (!unchangedAttributes.isEmpty()) { for (String attributeName : unchangedAttributes) { StringBuilder buildAttributeName = new StringBuilder(attributeName).append(DOT).append(typeValue); renamedAttributes.put(buildAttributeName.toString(), multiValuedAttributeBuffer.get(attributeName)); } } multiValuedAttributeBuffer.clear(); attributeMap.putAll(renamedAttributes); elementIsMultiValued = false; return ""; }
From source file:net.firejack.platform.core.store.process.CaseStore.java
@Override @Transactional/*from ww w. j a va 2 s . c o m*/ public CaseModel moveCaseToActivity(Long entityId, Long activityActionId, Long assigneeId, Long currentUserId, String comment) { CaseModel processCase; if (entityId == null || activityActionId == null || currentUserId == null) { processCase = null; } else { UserModel currentUser = userStore.findById(currentUserId); LinkedList<Criterion> restrictions = new LinkedList<Criterion>(); restrictions.add(Restrictions.idEq(activityActionId)); Map<String, String> aliases = new HashMap<String, String>(); aliases.put("activityFrom", "from"); aliases.put("activityTo", "to"); aliases.put("status", "status"); List<ActivityActionModel> foundActions = activityActionStore.search(restrictions, aliases, null); ActivityActionModel activityAction = foundActions.get(0); UserModel assignee = assigneeId == null ? null : userStore.findById(assigneeId); restrictions.clear(); restrictions.add(Restrictions.idEq(activityAction.getActivityFrom().getId())); aliases.clear(); aliases.put("parent", "parent"); List<ProcessModel> processList = activityStore.searchWithProjection(restrictions, Projections.property("parent"), aliases, null); CaseObjectModel caseObjectModel; if (processList.isEmpty()) { processCase = null; caseObjectModel = null; } else { ProcessModel processModel = processList.get(0); EntityModel entityModel = getHibernateTemplate().get(EntityModel.class, processModel.getMain().getId()); restrictions.clear(); restrictions.add(Restrictions.eq("entityType", entityModel.getLookup())); restrictions.add(Restrictions.eq("entityId", entityId)); restrictions.add(Restrictions.eq("case.process.id", processModel.getId())); aliases.clear(); aliases.put("case", "case"); List<CaseObjectModel> caseObjects = caseObjectStore.search(restrictions, aliases, null, false); caseObjectModel = caseObjects.isEmpty() ? null : caseObjects.get(0); processCase = caseObjectModel == null ? null : caseObjectModel.getCase(); } if (processCase != null) { restrictions.clear(); restrictions.add(Restrictions.and(Restrictions.eq("case.id", processCase.getId()), Restrictions.eq("active", Boolean.TRUE))); List<TaskModel> currentActiveTasks = taskStore.search(restrictions, null); TaskModel oldActiveTaskModel; if (currentActiveTasks.isEmpty()) { oldActiveTaskModel = null; } else { oldActiveTaskModel = currentActiveTasks.get(0); for (TaskModel activeTask : currentActiveTasks) { activeTask.setActive(Boolean.FALSE); } taskStore.saveOrUpdateAll(currentActiveTasks); } StatusModel status = activityAction.getStatus(); ActivityModel toActivity = activityAction.getActivityTo(); boolean isNotFinalStep = !status.getName().equals(StatusModel.STATUS_FINISHED) && toActivity.getActivityOrder() != ActivityOrder.END; String taskDescription = StringUtils.isBlank(toActivity.getDescription()) ? processCase.getDescription() : toActivity.getDescription(); Date updateDate = new Date(System.currentTimeMillis()); TaskModel nextTaskModel = new TaskModel(); nextTaskModel.setDescription(taskDescription); nextTaskModel.setActivity(toActivity); nextTaskModel.setCase(processCase); nextTaskModel.setUpdateDate(updateDate); nextTaskModel.setAssignee(assignee); nextTaskModel.setActive(isNotFinalStep); taskStore.saveOrUpdate(nextTaskModel); processCase.setStatus(status); processCase.setActive(isNotFinalStep); saveOrUpdate(processCase); caseObjectModel.setTask(nextTaskModel); caseObjectModel.setStatus(status); caseObjectModel.setUpdateDate(updateDate); caseObjectModel.setUpdatedBy(currentUser); caseObjectStore.saveOrUpdate(caseObjectModel); if (oldActiveTaskModel != null) { CaseActionModel caseAction = new CaseActionModel(); caseAction.setPerformedOn(updateDate); caseAction.setType(CaseActionType.PERFORM_ACTIVITY); caseAction.setCase(processCase); caseAction.setUser(currentUser); caseAction.setTaskModel(oldActiveTaskModel); if (StringUtils.isNotBlank(comment)) { CaseNoteModel caseNote = new CaseNoteModel(); caseNote.setProcessCase(processCase); caseNote.setText(comment); caseNote.setUser(currentUser); caseNoteStore.saveOrUpdate(caseNote); caseAction.setCaseNote(caseNote); } caseActionStore.saveOrUpdate(caseAction); } } } return processCase; }
From source file:com.healthcit.cacure.businessdelegates.GeneratedModuleDataManager.java
/** * Updates the GeneratedFormDataDetail object with * randomly generated unique key field values. *///from w w w . ja va 2 s . c o m private Map<String, JSONObject> generateUniqueKey(GeneratedModuleDataDetail form, Map<String, JSONObject> lastUniqueKey, String entityId, int moduleId, int entityModuleId) { log.debug("Generating unique key.............."); log.debug("=========================="); // Get the list of "unique-per-entity" fields List<Map<String, Object>> uniquePerEntityQuestions = form.retrieveUniquePerEntityQuestions(); // Get the list of "unique-per-all-modules" fields List<Map<String, Object>> uniquePerAllModulesQuestions = form.retrieveUniquePerAllModulesQuestions(); // Get the list of "unique-per-entity-modules" fields List<Map<String, Object>> uniquePerEntityModulesQuestions = form.retrieveUniquePerEntityModulesQuestions(); // Generate the answer values: first for "unique-per-entity", then "unique-per-entity-modules", then "unique-per-all-modules" Map<String, JSONObject> uniqueKey = new HashMap<String, JSONObject>(); // Get the map of answer-value to "unique-per-entity" question fields Map<Object, List<Object>> uniquePerEntityCombinations = form.getUniquePerEntityQuestionCombinations(); // Get the map of answer-value to "unique-per-all-modules" question fields Map<Object, List<Object>> uniquePerAllModulesCombinations = form .getUniquePerAllModuleQuestionCombinations(); // Get the map of answer-value to "unique-per-entity-modules" question fields Map<Object, List<Object>> uniquePerEntityModulesCombinations = form .getUniquePerEntityModuleQuestionCombinations(); // Generate the answer values: first for "unique-per-entity", then "unique-per-entity-modules", then "unique-per-all-modules" uniqueKey.clear(); // First, generate the unique answer values for "unique-per-entity" fields buildNewKey(uniqueKey, lastUniqueKey, uniquePerEntityQuestions, uniquePerEntityCombinations, entityId); // Then, generate the unique answer values for "unique-per-entity-modules" fields buildNewKey(uniqueKey, lastUniqueKey, uniquePerEntityModulesQuestions, uniquePerEntityModulesCombinations, entityModuleId); // Then, generate the unique answer values for "unique-per-all-modules" fields buildNewKey(uniqueKey, lastUniqueKey, uniquePerAllModulesQuestions, uniquePerAllModulesCombinations, moduleId); // Debugging log.debug("Generated unique key fields: " + (uniqueKey.isEmpty() ? "NONE" : "")); for (Map.Entry<String, JSONObject> entry : uniqueKey.entrySet()) { log.debug("==========Key: " + entry.getKey()); log.debug("==========Text:" + StringUtils.defaultIfEmpty((String) entry.getValue().get(ANSWERVALUE_TEXT), "") + "==========Value:" + entry.getValue().get(ANSWERVALUE_VALUE).toString()); } return uniqueKey; }
From source file:ai.grakn.test.graql.analytics.DegreeTest.java
@Test public void testDegreeIsPersisted() throws Exception { // TODO: Fix on TinkerGraphComputer assumeFalse(usingTinker());//from w w w. j a v a 2 s. com // create a simple graph RoleType pet = graph.putRoleType("pet"); RoleType owner = graph.putRoleType("owner"); RoleType breeder = graph.putRoleType("breeder"); RelationType mansBestFriend = graph.putRelationType("mans-best-friend").hasRole(pet).hasRole(owner) .hasRole(breeder); EntityType person = graph.putEntityType("person").playsRole(owner).playsRole(breeder); EntityType animal = graph.putEntityType("animal").playsRole(pet); // make one person breeder and owner Entity coco = animal.addEntity(); Entity dave = person.addEntity(); Relation daveBreedsAndOwnsCoco = mansBestFriend.addRelation().putRolePlayer(pet, coco).putRolePlayer(owner, dave); // manual degrees Map<String, Long> referenceDegrees = new HashMap<>(); referenceDegrees.put(coco.getId(), 1L); referenceDegrees.put(dave.getId(), 1L); referenceDegrees.put(daveBreedsAndOwnsCoco.getId(), 2L); graph.commit(); // compute and persist degrees graph.graql().compute().degree().persist().execute(); // check degrees are correct graph = factory.getGraph(); GraknGraph finalGraph = graph; referenceDegrees.entrySet().forEach(entry -> { Instance instance = finalGraph.getConcept(entry.getKey()); assertTrue(instance.resources().iterator().next().getValue().equals(entry.getValue())); }); // check only expected resources exist Collection<String> allConcepts = new ArrayList<>(); ResourceType<Long> rt = graph.getResourceType(AbstractComputeQuery.degree); Collection<Resource<Long>> degrees = rt.instances(); Map<Instance, Long> currentDegrees = new HashMap<>(); degrees.forEach(degree -> { Long degreeValue = degree.getValue(); degree.ownerInstances().forEach(instance -> currentDegrees.put(instance, degreeValue)); }); // check all resources exist and no more assertTrue(CollectionUtils.isEqualCollection(currentDegrees.values(), referenceDegrees.values())); // persist again and check again graph.graql().compute().degree().persist().execute(); // check only expected resources exist graph = factory.getGraph(); rt = graph.getResourceType(AbstractComputeQuery.degree); degrees = rt.instances(); degrees.forEach(i -> i.ownerInstances().iterator().forEachRemaining(r -> allConcepts.add(r.getId()))); // check degrees are correct GraknGraph finalGraph1 = graph; referenceDegrees.entrySet().forEach(entry -> { Instance instance = finalGraph1.getConcept(entry.getKey()); assertTrue(instance.resources().iterator().next().getValue().equals(entry.getValue())); }); degrees = rt.instances(); currentDegrees.clear(); degrees.forEach(degree -> { Long degreeValue = degree.getValue(); degree.ownerInstances().forEach(instance -> currentDegrees.put(instance, degreeValue)); }); // check all resources exist and no more assertTrue(CollectionUtils.isEqualCollection(currentDegrees.values(), referenceDegrees.values())); }
From source file:de.vandermeer.skb.base.utils.Skb_STUtils_Tests.java
@Test public void testGetMissingChunks() { //null//from ww w .ja v a 2 s.c o m assertNull(Skb_STUtils.getMissingChunks(null, null)); assertNull(Skb_STUtils.getMissingChunks(new STGroup(), null)); assertNull(Skb_STUtils.getMissingChunks(null, new HashMap<String, List<String>>())); //empty but not-null ST and empty chunk list assertNotNull(Skb_STUtils.getMissingChunks(new STGroup(), new HashMap<String, List<String>>())); assertEquals(0, Skb_STUtils.getMissingChunks(new STGroup(), new HashMap<String, List<String>>()).size()); //some vars for further testing Map<String, List<String>> chunks = new HashMap<String, List<String>>(); ArrayList<String> ar = new ArrayList<String>(); STGroup stg = new STGroupFile(this.stgFileSimple); assertNotNull(stg); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); chunks.put(null, null); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); chunks.put("", null); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); chunks.put(null, new ArrayList<String>()); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); chunks.put("noArg", null); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); chunks.put("noArg", new ArrayList<String>()); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); chunks.put("oneArg", null); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); ar.add("one"); chunks.put("oneArg", ar); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); ar.add("two"); assertEquals(1, Skb_STUtils.getMissingChunks(stg, chunks).size()); assertEquals(1, Skb_STUtils.getMissingChunks(stg, chunks).get("oneArg").size()); assertTrue(Skb_STUtils.getMissingChunks(stg, chunks).get("oneArg").contains("two")); ar.add("three"); assertEquals(1, Skb_STUtils.getMissingChunks(stg, chunks).size()); assertEquals(2, Skb_STUtils.getMissingChunks(stg, chunks).get("oneArg").size()); assertTrue(Skb_STUtils.getMissingChunks(stg, chunks).get("oneArg").contains("two")); assertTrue(Skb_STUtils.getMissingChunks(stg, chunks).get("oneArg").contains("three")); chunks.clear(); chunks.put("noArg", null); chunks.put("oneArg", Arrays.asList(new String[] { "one" })); chunks.put("twoArgs", Arrays.asList(new String[] { "one", "two" })); assertEquals(0, Skb_STUtils.getMissingChunks(stg, chunks).size()); chunks.clear(); chunks.put("noArg", null); chunks.put("oneArg", Arrays.asList(new String[] { "three" })); chunks.put("twoArgs", Arrays.asList(new String[] { "four", "five" })); assertEquals(2, Skb_STUtils.getMissingChunks(stg, chunks).size()); assertEquals(1, Skb_STUtils.getMissingChunks(stg, chunks).get("oneArg").size()); assertTrue(Skb_STUtils.getMissingChunks(stg, chunks).get("oneArg").contains("three")); assertEquals(2, Skb_STUtils.getMissingChunks(stg, chunks).get("twoArgs").size()); assertTrue(Skb_STUtils.getMissingChunks(stg, chunks).get("twoArgs").contains("four")); assertTrue(Skb_STUtils.getMissingChunks(stg, chunks).get("twoArgs").contains("five")); }