List of usage examples for java.util Date equals
public boolean equals(Object obj)
From source file:org.etudes.component.app.jforum.JForumForumServiceImpl.java
/** * {@inheritDoc}//from ww w . j a va 2s . co m */ public void updateDates(final Forum forum) { if (forum == null) { throw new IllegalArgumentException("updateDates: forum is null"); } Forum existingForum = getForum(forum.getId()); if (existingForum == null) { if (logger.isWarnEnabled()) { logger.warn("updateDates: There is no existing forum with id " + forum.getId()); } return; } // update if the date changes boolean datesChanged = false; datesChanged = checkDatesChanged(forum, existingForum); if (datesChanged) { /*forum can have dates if category or topics of the forum have no dates*/ /*if ((forum.getAccessDates() != null) && (existingForum.getAccessDates() != null)) { forum.getAccessDates().setLocked(existingForum.getAccessDates().isLocked()); }*/ int topicDatesCount = this.jforumPostService.getTopicDatesCountByForum(forum.getId()); boolean categoryDates = false; Category category = forum.getCategory(); if ((category.getAccessDates() != null) && ((category.getAccessDates().getOpenDate() != null) || (category.getAccessDates().getOpenDate() != null) || (category.getAccessDates().getAllowUntilDate() != null))) { categoryDates = true; } if ((topicDatesCount > 0) || (categoryDates)) { forum.getAccessDates().setOpenDate(null); forum.getAccessDates().setHideUntilOpen(null); forum.getAccessDates().setDueDate(null); forum.getAccessDates().setAllowUntilDate(null); } // if no dates remove any existing special access if ((forum.getAccessDates() == null) || ((forum.getAccessDates().getOpenDate() == null) && (forum.getAccessDates().getOpenDate() == null) && (forum.getAccessDates().getAllowUntilDate() == null))) { List<SpecialAccess> forumSpecialAccessList = this.jforumSpecialAccessService .getByForum(forum.getId()); for (SpecialAccess specialAccess : forumSpecialAccessList) { this.jforumSpecialAccessService.delete(specialAccess.getId()); } } this.sqlService.transact(new Runnable() { public void run() { updateDatesTXN(forum); } }, "updateForumDates: " + forum.getId()); // clear category from thread local cache clearCache(existingForum); // update the due date changes in the gradebook if (existingForum.getGradeType() == Grade.GradeType.FORUM.getType()) { Date exisDueDate = null, modDueDate = null, modOpenDate = null; boolean dueDateChanged = false; // check the due date changes if (forum.getAccessDates() != null) { modDueDate = forum.getAccessDates().getDueDate(); modOpenDate = forum.getAccessDates().getOpenDate(); if ((modOpenDate != null) && (modDueDate != null)) { if (modOpenDate.after(modDueDate)) { Grade grade = jforumGradeService.getByForumId(forum.getId()); if (grade != null && grade.isAddToGradeBook()) { boolean result = jforumGradeService.removeGradebookEntry(grade); /*if (result) { //update the grade for addToGradeBook String sql = "UPDATE jforum_grade SET add_to_gradebook = ? WHERE grade_id = ?"; Object[] fields = new Object[2]; int i = 0; fields[i++] = 0; fields[i++] = grade.getId(); if (!sqlService.dbWrite(sql.toString(), fields)) { throw new RuntimeException("updateGrade - add_to_gradebook : db write failed"); } }*/ } // clear forum from thread local cache clearCache(existingForum); return; } } } if (existingForum.getAccessDates() != null) { exisDueDate = existingForum.getAccessDates().getDueDate(); } if (modDueDate == null && exisDueDate != null) { dueDateChanged = true; } else if (modDueDate != null && exisDueDate == null) { dueDateChanged = true; } else if (modDueDate == null && exisDueDate == null) { dueDateChanged = false; } else { if (!exisDueDate.equals(modDueDate)) { dueDateChanged = true; } } //if (dueDateChanged) - removed to push due dates if invalid dates are corrected from course map //{ forum.setName(existingForum.getName()); forum.setGradeType(existingForum.getGradeType()); Grade forumGrade = this.jforumGradeService.getByForumId(forum.getId()); if (forumGrade != null && forumGrade.isAddToGradeBook()) { this.jforumGradeService.updateGradebook(forumGrade, forum); } //} } else { Date modForumDueDate = null, modForumOpenDate = null; // gradable topics of the forum in the gradebook if (forum.getAccessDates() != null) { // check for invalid dates modForumDueDate = forum.getAccessDates().getDueDate(); modForumOpenDate = forum.getAccessDates().getOpenDate(); if ((modForumOpenDate != null) && (modForumDueDate != null)) { if (modForumOpenDate.after(modForumDueDate)) { List<Grade> topicGrades = jforumGradeService.getTopicGradesByForum(forum.getId()); for (Grade topicGrade : topicGrades) { if (topicGrade.isAddToGradeBook()) { jforumGradeService.removeGradebookEntry(topicGrade); } } return; } } //update gradebook due dates for gradable forums and topics of the category List<Grade> forumTopicGrades = jforumGradeService.getTopicGradesByForum(forum.getId()); for (Grade forumTopicGrade : forumTopicGrades) { if (forumTopicGrade.isAddToGradeBook()) { if (forumTopicGrade.getType() == Grade.GradeType.TOPIC.getType()) { Topic topic = jforumPostService.getTopic(forumTopicGrade.getTopicId()); // update due date in the gradebook jforumGradeService.updateGradebook(forumTopicGrade, topic); } } } } } } }
From source file:tds.dll.mysql.ProctorDLL.java
/** * @param connection//from w w w .j a v a 2 s. com * @param clientName * @param browserKey * @param sessionName * @param proctorKey * @param procId * @param procName * @param dateBegin * @param dateEnd * @param sessionType * @return * @throws ReturnStatusException */ public SingleDataResultSet P_CreateSession_SP(SQLConnection connection, String clientName, UUID browserKey, String sessionName, Long proctorKey, String procId, String procName, Date dateBegin, Date dateEnd, Integer sessionType) throws ReturnStatusException { SingleDataResultSet result = null; UUID sessionKey = null; _Ref<String> sessionId = new _Ref<>(); String environment = null; String prefix = null; String status = "closed"; String errMsg = null; Date now = _dateUtil.getDateWRetStatus(connection); Integer audit = null; audit = _commonDll.AuditSessions_FN(connection, clientName); final String SQL_QUERY1 = "select environment from _externs where clientname = ${clientname};"; SqlParametersMaps parms1 = (new SqlParametersMaps()).put("clientname", clientName); result = executeStatement(connection, SQL_QUERY1, parms1, false).getResultSets().next(); DbResultRecord record = (result.getCount() > 0 ? result.getRecords().next() : null); if (record != null) { environment = record.<String>get("environment"); } if (environment == null) { errMsg = String.format("Unknown client: %s", clientName); return _commonDll._ReturnError_SP(connection, clientName, "P_CreateSession", errMsg); } final String SQL_QUERY2 = "select _Key from session S where clientname = ${clientname} and _efk_Proctor = ${proctorKey} and ${now} between S.DateBegin and S.DateEnd and sessiontype = ${sessiontype} limit 1 "; SqlParametersMaps parms2 = (new SqlParametersMaps()).put("clientname", clientName) .put("proctorKey", proctorKey).put("now", now).put("sessiontype", sessionType); if (exists(executeStatement(connection, SQL_QUERY2, parms2, true))) { return _commonDll._ReturnError_SP(connection, clientName, "P_CreateSession", "There already is an active session for this user."); } prefix = _commonDll._CoreSessName_FN(connection, clientName, procName); sessionKey = UUID.randomUUID(); if (dateBegin == null) { dateBegin = now; } if (dateEnd == null) { dateEnd = adjustDateHours(dateBegin, 8); } else if (DbComparator.lessOrEqual(dateEnd, dateBegin)) { dateEnd = adjustDateHours(dateBegin, 8); } if ((now.equals(dateBegin) || now.after(dateBegin)) && (now.equals(dateEnd) || now.before(dateEnd))) { status = "open"; } _commonDll._CreateClientSessionID_SP(connection, clientName, prefix, sessionId); if (sessionId.get() == null) { return _commonDll._ReturnError_SP(connection, clientName, "P_CreateSession", "Failed to insert new session into database"); } try { final String SQL_INSERT = "insert into session (_Key, Name, _efk_Proctor, ProctorID, ProctorName, status, DateBegin, DateEnd, SessionID, _fk_browser, clientname, environment, dateVisited, sessiontype, datecreated, serveraddress) " + " values (${sessionKey}, ${sessionName}, ${proctorKey}, ${procID}, ${procName}, ${status}, ${dateBegin}, ${dateEnd}, ${sessionID}, ${browserKey}, ${clientname}, ${environment}, ${now}, ${sessiontype}, now(3), ${hostname});"; SqlParametersMaps parms3 = new SqlParametersMaps(); parms3.put("sessionKey", sessionKey); parms3.put("sessionName", sessionName); parms3.put("proctorKey", proctorKey); parms3.put("procID", procId); parms3.put("procName", procName); parms3.put("status", status); parms3.put("dateBegin", dateBegin); parms3.put("dateEnd", dateEnd); parms3.put("sessionID", sessionId.toString()); parms3.put("browserKey", browserKey); parms3.put("clientname", clientName); parms3.put("environment", environment); parms3.put("now", now); parms3.put("sessiontype", sessionType); parms3.put("hostname", _commonDll.getLocalhostName()); int insertedCnt = executeStatement(connection, SQL_INSERT, parms3, false).getUpdateCount(); } catch (Exception e) { String err = e.getMessage(); _commonDll._LogDBError_SP(connection, "P_CreateSession", err, null, null, null, null, clientName, null); _commonDll._LogDBLatency_SP(connection, "P_CreateSession", now, proctorKey, true, null, null, null, clientName, null); return _commonDll._ReturnError_SP(connection, clientName, "P_CreateSession", "Failed to insert new session into database"); } String localhostname = _commonDll.getLocalhostName(); String sessionDB = getTdsSettings().getTDSSessionDBName(); // String sessionDB = getAppSettings ().get ("TDSSessionDBName"); if (DbComparator.notEqual(audit, 0)) { final String SQL_INSERT1 = "insert into ${ArchiveDB}.sessionaudit (_fk_session, DateAccessed, AccessType, hostname, browserKey, dbname) values (${sessionKey}, ${now}, ${status}, ${hostname}, ${browserKey}, ${dbname});"; SqlParametersMaps parms4 = new SqlParametersMaps().put("sessionKey", sessionKey).put("now", now) .put("status", status).put("hostname", localhostname).put("browserKey", browserKey) .put("dbname", sessionDB); int insertedCnt = executeStatement(connection, fixDataBaseNames(SQL_INSERT1), parms4, false) .getUpdateCount(); } List<CaseInsensitiveMap<Object>> resultlist = new ArrayList<CaseInsensitiveMap<Object>>(); CaseInsensitiveMap<Object> rcrd = new CaseInsensitiveMap<Object>(); rcrd.put("sessionKey", sessionKey); rcrd.put("sessionID", sessionId.get()); rcrd.put("Name", sessionName); rcrd.put("sessionStatus", status); resultlist.add(rcrd); result = new SingleDataResultSet(); result.addColumn("sessionKey", SQL_TYPE_To_JAVA_TYPE.UNIQUEIDENTIFIER); result.addColumn("sessionID", SQL_TYPE_To_JAVA_TYPE.VARCHAR); result.addColumn("Name", SQL_TYPE_To_JAVA_TYPE.VARCHAR); result.addColumn("sessionStatus", SQL_TYPE_To_JAVA_TYPE.VARCHAR); result.addRecords(resultlist); _commonDll._LogDBLatency_SP(connection, "P_CreateSession", now, proctorKey, true, null, null, sessionKey, clientName, null); return result; }
From source file:org.egov.ptis.domain.service.property.PropertyService.java
public BigDecimal getSurveyTax(Property property, Date fromDate) { BigDecimal totalTax = BigDecimal.ZERO; Map<String, Installment> yearwiseInstMap = propertyTaxUtil.getInstallmentsForCurrYear(fromDate); Date firstInstStartDate = yearwiseInstMap.get(PropertyTaxConstants.CURRENTYEAR_FIRST_HALF).getFromDate(); Date secondInstStartDate = yearwiseInstMap.get(PropertyTaxConstants.CURRENTYEAR_SECOND_HALF).getFromDate(); for (EgDemandDetails demandDetail : property.getPtDemandSet().iterator().next().getEgDemandDetails()) { if (firstInstStartDate.equals(demandDetail.getInstallmentStartDate()) || secondInstStartDate.equals(demandDetail.getInstallmentStartDate()) && !PropertyTaxConstants.DEMANDRSN_CODE_PENALTY_FINES.equalsIgnoreCase( demandDetail.getEgDemandReason().getEgDemandReasonMaster().getCode()) && !PropertyTaxConstants.DEMANDRSN_CODE_CHQ_BOUNCE_PENALTY.equalsIgnoreCase( demandDetail.getEgDemandReason().getEgDemandReasonMaster().getCode())) totalTax = totalTax.add(demandDetail.getAmount()); }/* w ww .j a va 2s . com*/ return totalTax; }
From source file:org.yes.cart.service.order.impl.handler.delivery.DeliveryUpdateOrderEventHandlerImpl.java
/** * {@inheritDoc}/*from w w w .j a v a 2 s.c o m*/ */ public boolean handle(final OrderEvent orderEvent) throws OrderException { synchronized (OrderEventHandler.syncMonitor) { final CustomerOrder customerOrder = orderEvent.getCustomerOrder(); final OrderDeliveryStatusUpdate update = (OrderDeliveryStatusUpdate) orderEvent.getParams() .get("update"); LOG.info("Received delivery update for order {}, status {}:\n{}", new Object[] { customerOrder.getOrdernum(), customerOrder.getOrderStatus(), update }); if (update != null) { final Map<Long, OrderDeliveryLineStatusUpdate> detailsByPk = new HashMap<Long, OrderDeliveryLineStatusUpdate>(); final Map<String, OrderDeliveryLineStatusUpdate> detailsBySKU = new HashMap<String, OrderDeliveryLineStatusUpdate>(); for (final OrderDeliveryLineStatusUpdate lineUpdate : update.getLineStatus()) { if (lineUpdate.getOrderLineRef() != null) { detailsByPk.put(lineUpdate.getOrderLineRef(), lineUpdate); } if (lineUpdate.getSKU() != null) { detailsBySKU.put(lineUpdate.getSKU(), lineUpdate); } } final boolean allowDeliveryTransitions = CustomerOrder.ORDER_STATUS_IN_PROGRESS .equals(customerOrder.getOrderStatus()) || CustomerOrder.ORDER_STATUS_PARTIALLY_SHIPPED.equals(customerOrder.getOrderStatus()); if (update.getAdditionalData() != null) { for (final Map.Entry<String, Pair<String, String>> data : update.getAdditionalData() .entrySet()) { if (data.getValue() != null) { customerOrder.putValue(data.getKey(), data.getValue().getFirst(), data.getValue().getSecond()); } else { customerOrder.putValue(data.getKey(), null, null); } } } for (final CustomerOrderDelivery delivery : customerOrder.getDelivery()) { Date estimatedMin = null; Date estimatedMax = null; Date guaranteed = null; Date confirmed = null; boolean notGuaranteed = false; boolean atLeastOneItemIsNotUpdated = false; boolean allItemsDeliveredOrRejected = true; // Apply updates to lines and work out estimated delivery time for (final CustomerOrderDeliveryDet detail : delivery.getDetail()) { OrderDeliveryLineStatusUpdate lineUpdate = detailsByPk .get(detail.getCustomerOrderDeliveryDetId()); if (lineUpdate == null) { if (detail.getSupplierCode().equals(update.getSupplierCode())) { lineUpdate = detailsBySKU.get(detail.getProductSkuCode()); } } if (lineUpdate != null) { if (lineUpdate.getDeliveryConfirmed() != null) { detail.setDeliveryConfirmed(lineUpdate.getDeliveryConfirmed()); } else { if (lineUpdate.getDeliveryEstimatedMin() != null) { detail.setDeliveryEstimatedMin(lineUpdate.getDeliveryEstimatedMin()); } if (lineUpdate.getDeliveryEstimatedMax() != null) { detail.setDeliveryEstimatedMax(lineUpdate.getDeliveryEstimatedMax()); } if (lineUpdate.getDeliveryGuaranteed() != null) { detail.setDeliveryGuaranteed(lineUpdate.getDeliveryGuaranteed()); } } if (StringUtils.isNotBlank(lineUpdate.getOrderDeliveryStatus())) { detail.setDeliveryRemarks(lineUpdate.getOrderDeliveryStatus()); } if (lineUpdate.isRejected()) { detail.setDeliveredQuantity(BigDecimal.ZERO); } else if (lineUpdate.getDeliveredQty() != null) { detail.setDeliveredQuantity(lineUpdate.getDeliveredQty()); } if (StringUtils.isNotBlank(lineUpdate.getSupplierInvoiceNo())) { detail.setSupplierInvoiceNo(lineUpdate.getSupplierInvoiceNo()); } if (lineUpdate.getSupplierInvoiceDate() != null) { detail.setSupplierInvoiceDate(lineUpdate.getSupplierInvoiceDate()); } if (lineUpdate.getAdditionalData() != null) { for (final Map.Entry<String, Pair<String, String>> data : lineUpdate .getAdditionalData().entrySet()) { if (data.getValue() != null) { detail.putValue(data.getKey(), data.getValue().getFirst(), data.getValue().getSecond()); } else { detail.putValue(data.getKey(), null, null); } } } } else { // No estimates and not delivery info if (detail.getDeliveryEstimatedMin() == null && detail.getDeliveryEstimatedMax() == null && detail.getDeliveryGuaranteed() == null && detail.getDeliveryConfirmed() == null && detail.getDeliveredQuantity() == null) { atLeastOneItemIsNotUpdated = true; } } estimatedMin = chooseLatestDate(estimatedMin, detail.getDeliveryEstimatedMin()); estimatedMax = chooseLatestDate(estimatedMax, detail.getDeliveryEstimatedMax()); if (guaranteed != null) { notGuaranteed = !guaranteed.equals(detail.getDeliveryGuaranteed()); } if (notGuaranteed) { estimatedMin = chooseLatestDate(estimatedMin, guaranteed); estimatedMax = chooseLatestDate(estimatedMax, guaranteed); } else { guaranteed = chooseLatestDate(guaranteed, detail.getDeliveryGuaranteed()); } confirmed = chooseLatestDate(confirmed, detail.getDeliveryConfirmed()); if (detail.getDeliveredQuantity() == null) { // All items MUST have confirmed quantity, which will allow this delivery to progress to // SHIPPED, otherwise we keep it in packing (and it need be, this can be progressed manually // from admin app) allItemsDeliveredOrRejected = false; } } if (estimatedMin != null || estimatedMax != null) { notGuaranteed = true; } // Update estimated time on the delivery level if (notGuaranteed) { if (atLeastOneItemIsNotUpdated) { // At least one item is not updated, so we only use min delivery.setDeliveryEstimatedMin(estimatedMin); delivery.setDeliveryEstimatedMax(null); delivery.setDeliveryGuaranteed(null); } else { // All items have updates, so we use the best approximation values delivery.setDeliveryEstimatedMin(estimatedMin); delivery.setDeliveryEstimatedMax(estimatedMax); delivery.setDeliveryGuaranteed(null); } } else { // All lines have same guaranteed delivery date delivery.setDeliveryEstimatedMin(null); delivery.setDeliveryEstimatedMax(null); delivery.setDeliveryGuaranteed(guaranteed); } if (allItemsDeliveredOrRejected) { delivery.setDeliveryConfirmed(confirmed); } LOG.info("Attempting to auto-progress delivery {}. Status: {}", customerOrder.getOrdernum(), delivery.getDeliveryStatus()); // Only transition orders that are in progress to avoid breaking the order state flow // Updates are only allowed if we have a confirmed/paid order which has not been fully shipping // Otherwise we only update line information, any manual intervention can still be done from admin app if (allowDeliveryTransitions) { // Transitions delivery if necessary. Since this is automated route we ignore all allocations block (date/inventory). // If the updates are coming through it means that the order is accepted and it is suppliers responsibility // to fulfil it. If supplier cannot fulfil the order, rejection flags can be sent later. if (CustomerOrderDelivery.DELIVERY_STATUS_INVENTORY_RESERVED .equals(delivery.getDeliveryStatus()) || CustomerOrderDelivery.DELIVERY_STATUS_ALLOCATION_WAIT .equals(delivery.getDeliveryStatus()) || CustomerOrderDelivery.DELIVERY_STATUS_INVENTORY_WAIT .equals(delivery.getDeliveryStatus()) || CustomerOrderDelivery.DELIVERY_STATUS_DATE_WAIT .equals(delivery.getDeliveryStatus())) { // We only void reservation, since this is automated integration flow voidReservation(delivery); delivery.setDeliveryStatus(CustomerOrderDelivery.DELIVERY_STATUS_INVENTORY_ALLOCATED); // We are sending updates, so we are packing the order be it part or full. getOrderStateManager().fireTransition(new OrderEventImpl( OrderStateManager.EVT_RELEASE_TO_PACK, customerOrder, delivery)); LOG.info( "Delivery {} was pending allocation, reservation was voided and delivery released to pack. Status: {}", customerOrder.getOrdernum(), delivery.getDeliveryStatus()); } // We already had items allocated (standard inventory flow) if (CustomerOrderDelivery.DELIVERY_STATUS_INVENTORY_ALLOCATED .equals(delivery.getDeliveryStatus())) { // We are sending updates, so we are packing the order be it part or full. getOrderStateManager().fireTransition(new OrderEventImpl( OrderStateManager.EVT_RELEASE_TO_PACK, customerOrder, delivery)); LOG.info("Delivery {} was allocated, delivery released to pack. Status: {}", customerOrder.getOrdernum(), delivery.getDeliveryStatus()); } // If we are packing it means that we have had partial update already, and if this time all lines // have relevant statuses we can progress further up to shipping completed. if (CustomerOrderDelivery.DELIVERY_STATUS_PACKING.equals(delivery.getDeliveryStatus()) && allItemsDeliveredOrRejected) { // This update confirms that all items are delivered, so we went from PACK->READY->SHIPPED // PACK->READY (payment taken) getOrderStateManager().fireTransition(new OrderEventImpl( OrderStateManager.EVT_RELEASE_TO_SHIPMENT, customerOrder, delivery)); LOG.info( "Delivery {} was in packing, all lines updated, releasing to shipment to take payment. Status: {}", customerOrder.getOrdernum(), delivery.getDeliveryStatus()); if (CustomerOrderDelivery.DELIVERY_STATUS_SHIPMENT_IN_PROGRESS .equals(delivery.getDeliveryStatus())) { // READY->SHIPPED getOrderStateManager().fireTransition(new OrderEventImpl( OrderStateManager.EVT_SHIPMENT_COMPLETE, customerOrder, delivery)); LOG.info( "Delivery {} was in shipping (payment successful), marking as complete. Status: {}", customerOrder.getOrdernum(), delivery.getDeliveryStatus()); } // else something is wrong with payment, so we leave for manual handling } // ELSE for all other statuses we only update the line statuses and wait until all lines have them } } LOG.info("Finished delivery update for order {}, status {}:\n{}", new Object[] { customerOrder.getOrdernum(), customerOrder.getOrderStatus(), update }); return true; // Return true to indicate that we want to save changes. } return false; // no update } }
From source file:org.motechproject.server.svc.impl.RegistrarBeanImpl.java
@Transactional public void editPatient(Patient patient, String firstName, String middleName, String lastName, String preferredName, Date dateOfBirth, Boolean estimatedBirthDate, Gender sex, Boolean insured, String nhis, Date nhisExpires, Patient mother, Community community, String addressLine1, String phoneNumber, Date expDeliveryDate, Boolean enroll, Boolean consent, ContactNumberType ownership, MediaType format, String language, DayOfWeek dayOfWeek, Date timeOfDay, Facility facility) { patient.setBirthdate(dateOfBirth);//from www.j a va 2 s .c om patient.setBirthdateEstimated(estimatedBirthDate); patient.setGender(GenderTypeConverter.toOpenMRSString(sex)); relationshipService.saveOrUpdateMotherRelationship(mother, patient, true); PatientEditor editor = new PatientEditor(patient); Facility currentFacility = getFacilityByPatient(patient); if (!currentFacility.equals(facility)) { patient = editor.removeFrom(currentFacility).addTo(facility).done(); } Community currentCommunity = getCommunityByPatient(patient); boolean bothCommunitiesExistAndAreSame = community != null && currentCommunity != null && currentCommunity.equals(community); if (!bothCommunitiesExistAndAreSame) { editor.removeFrom(currentCommunity).addTo(community); } setPatientAttributes(patient, phoneNumber, ownership, format, language, dayOfWeek, timeOfDay, null, null, insured, nhis, nhisExpires); editor.editName(new PersonName(firstName, middleName, lastName)); editor.editPreferredName(new PersonName(preferredName, middleName, lastName)); editor.editAddress(new PatientAddress().near(facility).in(community).at(addressLine1).build()); patientService.savePatient(patient); Integer dueDateObsId = null; if (expDeliveryDate != null) { Obs pregnancy = getActivePregnancy(patient.getPatientId()); Obs dueDateObs = getActivePregnancyDueDateObs(patient.getPatientId(), pregnancy); if (dueDateObs != null) { dueDateObsId = dueDateObs.getObsId(); if (!expDeliveryDate.equals(dueDateObs.getValueDatetime())) { dueDateObsId = updatePregnancyDueDateObs(pregnancy, dueDateObs, expDeliveryDate, dueDateObs.getEncounter()); } } } if (Boolean.FALSE.equals(enroll)) { removeAllMessageProgramEnrollments(patient.getPatientId()); } else { enrollPatient(patient, enroll, consent, null, dueDateObsId); } }
From source file:org.akaza.openclinica.control.managestudy.UpdateStudyEventServlet.java
@Override public void processRequest() throws Exception { ctx = WebApplicationContextUtils.getWebApplicationContext(context); FormDiscrepancyNotes discNotes = null; FormProcessor fp = new FormProcessor(request); int studyEventId = fp.getInt(EVENT_ID, true); int studySubjectId = fp.getInt(STUDY_SUBJECT_ID, true); String module = fp.getString(MODULE); request.setAttribute(MODULE, module); String fromResolvingNotes = fp.getString("fromResolvingNotes", true); if (StringUtil.isBlank(fromResolvingNotes)) { session.removeAttribute(ViewNotesServlet.WIN_LOCATION); session.removeAttribute(ViewNotesServlet.NOTES_TABLE); checkStudyLocked(Page.MANAGE_STUDY, respage.getString("current_study_locked")); checkStudyFrozen(Page.MANAGE_STUDY, respage.getString("current_study_frozen")); }/* w ww .ja v a 2 s. c o m*/ if (studyEventId == 0 || studySubjectId == 0) { addPageMessage(respage.getString("choose_a_study_event_to_edit")); request.setAttribute("id", new Integer(studySubjectId).toString()); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); return; } StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssub = null; if (studySubjectId > 0) { ssub = (StudySubjectBean) ssdao.findByPK(studySubjectId); request.setAttribute("studySubject", ssub); request.setAttribute("id", studySubjectId + "");// for the workflow // box, so it can // link back to view // study subject } // YW 11-07-2007, a study event could not be updated if its study // subject has been removed // Status s = ((StudySubjectBean)new // StudySubjectDAO(sm.getDataSource()).findByPK(studySubjectId)).getStatus(); Status s = ssub.getStatus(); if ("removed".equalsIgnoreCase(s.getName()) || "auto-removed".equalsIgnoreCase(s.getName())) { addPageMessage(resword.getString("study_event") + resterm.getString("could_not_be") + resterm.getString("updated") + "." + respage.getString("study_subject_has_been_deleted")); request.setAttribute("id", new Integer(studySubjectId).toString()); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); } // YW request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource()); EventCRFDAO ecrfdao = new EventCRFDAO(sm.getDataSource()); StudyEventBean studyEvent = (StudyEventBean) sedao.findByPK(studyEventId); studyEvent.setEventCRFs(ecrfdao.findAllByStudyEvent(studyEvent)); // only owner, admins, and study director/coordinator can update // if (ub.getId() != studyEvent.getOwnerId()) { // if (!ub.isSysAdmin() && // !currentRole.getRole().equals(Role.STUDYDIRECTOR) // && !currentRole.getRole().equals(Role.COORDINATOR)) { // addPageMessage(respage.getString("no_have_correct_privilege_current_study") // + respage.getString("change_study_contact_sysadmin")); // request.setAttribute("id", new Integer(studySubjectId).toString()); // forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); // return; // } // } // above removed tbh 11162007 ArrayList statuses = SubjectEventStatus.toArrayList(); // remove more statuses here, tbh, 092007 // ### updates to status setting, below added tbh 102007 // following pieces of logic to be added: /* * REMOVED can happen at any step, COMPLETED can happen if the Subject * Event is already complete, COMPLETED can also happen if all required * CRFs in the Subject Event are completed, LOCKED can occur when all * Event CRFs are completed, or not started, or removed, LOCKED/REMOVED * are only options, however, when the user is study director or study * coordinator SKIPPED/STOPPED? Additional rules spelled out on Nov 16 * 2007: STOPPED should only be in the list of choices after IDE has * been started, i.e. not when SCHEDULED SKIPPED should only be in the * list before IDE has been started, i.e. when SCHEDULED reminder about * LOCKED happening only when CRFs are completed (not as in the * above...) if a status is LOCKED already, it should allow a user to * set the event back to COMPLETED */ StudyDAO sdao = new StudyDAO(this.sm.getDataSource()); StudyBean studyBean = (StudyBean) sdao.findByPK(ssub.getStudyId()); checkRoleByUserAndStudy(ub, studyBean, sdao); // To remove signed status from the list EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource()); boolean removeSign = false; // DiscrepancyNoteDAO discDao = new // DiscrepancyNoteDAO(sm.getDataSource()); ArrayList eventCrfs = studyEvent.getEventCRFs(); for (int i = 0; i < eventCrfs.size(); i++) { EventCRFBean ecrf = (EventCRFBean) eventCrfs.get(i); EventDefinitionCRFBean edcBean = edcdao.findByStudyEventIdAndFormLayoutId(studyBean, studyEventId, ecrf.getFormLayoutId()); if (ecrf.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY) || ecrf.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) && edcBean.isDoubleEntry() == true) { removeSign = true; break; } } if (currentRole.isResearchAssistant()) { removeSign = true; } if (currentRole.isResearchAssistant2()) { removeSign = true; } if (removeSign == true || !currentRole.isInvestigator()) { statuses.remove(SubjectEventStatus.SIGNED); } // ///End of remove signed status from the list // BWP: 2735>>keep the DATA_ENTRY_STARTED status /* * if(!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus. * DATA_ENTRY_STARTED)) { * statuses.remove(SubjectEventStatus.DATA_ENTRY_STARTED); * //statuses.remove(SubjectEventStatus.SKIPPED); // per new rule * 11-2007 } */ if (!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.NOT_SCHEDULED)) { statuses.remove(SubjectEventStatus.NOT_SCHEDULED); } if (!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED)) { // can't lock a non-completed CRF, but removed above statuses.remove(SubjectEventStatus.SCHEDULED); // statuses.remove(SubjectEventStatus.SKIPPED); // addl rule: skipped should only be present before data starts // being entered } if (studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) { statuses.remove(SubjectEventStatus.SKIPPED); } if ((studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED) || studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) && currentRole.isInvestigator()) { statuses.remove(SubjectEventStatus.SIGNED); } ArrayList getECRFs = studyEvent.getEventCRFs(); // above removed tbh 102007, require to get all definitions, no matter // if they are filled in or now EventDefinitionCRFDAO edefcrfdao = new EventDefinitionCRFDAO(sm.getDataSource()); ArrayList getAllECRFs = (ArrayList) edefcrfdao.findAllByDefinition(studyBean, studyEvent.getStudyEventDefinitionId()); // does the study event have all complete CRFs which are required? logger.debug("found number of ecrfs: " + getAllECRFs.size()); // may not be populated, only entered crfs seem to ping the list for (int u = 0; u < getAllECRFs.size(); u++) { EventDefinitionCRFBean ecrfBean = (EventDefinitionCRFBean) getAllECRFs.get(u); // logger.debug("found number of existing ecrfs: " + getECRFs.size()); if (getECRFs.size() == 0) { statuses.remove(SubjectEventStatus.COMPLETED); statuses.remove(SubjectEventStatus.LOCKED); } // otherwise... for (int uv = 0; uv < getECRFs.size(); uv++) { EventCRFBean existingBean = (EventCRFBean) getECRFs.get(uv); logger.debug("***** found: " + existingBean.getCRFVersionId() + " " + existingBean.getCrf().getId() + " " + existingBean.getCrfVersion().getName() + " " + existingBean.getStatus().getName() + " " + existingBean.getStage().getName()); logger.debug( "***** comparing above to ecrfBean.DefaultVersionID: " + ecrfBean.getDefaultVersionId()); // if (existingBean.getCRFVersionId() == // ecrfBean.getDefaultVersionId()) { // OK. this only works if we go ahead and remove the drop down // will this match up? Do we need to pull it out of // studyEvent.getEventCRFs()? // only case that this will screw up is if there are no crfs // whatsoever // this is addressed in the if-clause above if (!existingBean.getStatus().equals(Status.UNAVAILABLE) && edefcrfdao.isRequiredInDefinition(existingBean.getCRFVersionId(), studyEvent)) { logger.debug("found that " + existingBean.getCrfVersion().getName() + " is required..."); // that is, it's not completed but required to complete statuses.remove(SubjectEventStatus.COMPLETED); statuses.remove(SubjectEventStatus.LOCKED); // per new rule above 11-16-2007 } // } } } // below added 092007, tbh, task #1390 if (!ub.isSysAdmin() && !currentRole.getRole().equals(Role.STUDYDIRECTOR) && !currentRole.getRole().equals(Role.COORDINATOR)) { statuses.remove(SubjectEventStatus.LOCKED); } // also, if data entry is started, can't move back to scheduled or not // scheduled if (studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) { statuses.remove(SubjectEventStatus.NOT_SCHEDULED); statuses.remove(SubjectEventStatus.SCHEDULED); } // ### tbh, above modified 102007 request.setAttribute("statuses", statuses); String action = fp.getString("action"); StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource()); StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao .findByPK(studyEvent.getStudyEventDefinitionId()); request.setAttribute(EVENT_DEFINITION_BEAN, sed); String start_date = fp.getDateTimeInputString(INPUT_STARTDATE_PREFIX); String end_date = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); SimpleDateFormat dteFormat = new SimpleDateFormat( ResourceBundleProvider.getFormatBundle().getString("date_format_string")); Date start = null; Date end = null; if (!StringUtils.isEmpty(start_date)) { start = fp.getDateTime(INPUT_STARTDATE_PREFIX); start_date = dteFormat.format(start); } if (!StringUtils.isEmpty(end_date)) { end = fp.getDateTime(INPUT_ENDDATE_PREFIX); end_date = dteFormat.format(end); } if (action.equalsIgnoreCase("submit")) { discNotes = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes); SubjectEventStatus ses = SubjectEventStatus.get(fp.getInt(SUBJECT_EVENT_STATUS_ID)); studyEvent.setSubjectEventStatus(ses); EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource()); ArrayList<EventCRFBean> eventCRFs = ecdao.findAllByStudyEvent(studyEvent); if (ses.equals(SubjectEventStatus.SKIPPED) || ses.equals(SubjectEventStatus.STOPPED)) { studyEvent.setStatus(Status.UNAVAILABLE); for (int i = 0; i < eventCRFs.size(); i++) { EventCRFBean ecb = eventCRFs.get(i); ecb.setOldStatus(ecb.getStatus()); ecb.setStatus(Status.UNAVAILABLE); ecb.setUpdater(ub); ecb.setUpdatedDate(new Date()); ecdao.update(ecb); } } else { for (int i = 0; i < eventCRFs.size(); i++) { EventCRFBean ecb = eventCRFs.get(i); ecb.setUpdater(ub); ecb.setUpdatedDate(new Date()); ecdao.update(ecb); } } // YW 3-12-2008, 2220 fix String strEnd = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); String strEndScheduled = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); String strStartScheduled = fp.getDateTimeInputString(INPUT_STARTDATE_PREFIX); if (!strStartScheduled.equals("")) { v.addValidation(INPUT_STARTDATE_PREFIX, Validator.IS_DATE_TIME); v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX); } if (!strEndScheduled.equals("")) { v.addValidation(INPUT_ENDDATE_PREFIX, Validator.IS_DATE_TIME); v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX); } // v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS); Disable validation on location, location can be // empty when updating a study event HashMap errors = v.validate(); // YW, 3-12-2008, 2220 fix << if (!strEnd.equals("") && !errors.containsKey(INPUT_STARTDATE_PREFIX) && !errors.containsKey(INPUT_ENDDATE_PREFIX)) { end = fp.getDateTime(INPUT_ENDDATE_PREFIX); if (!fp.getString(INPUT_STARTDATE_PREFIX + "Date") .equals(fp.getString(INPUT_ENDDATE_PREFIX + "Date"))) { if (end.before(start)) { v.addError(errors, INPUT_ENDDATE_PREFIX, resexception.getString("input_provided_not_occure_after_previous_start_date_time")); } } else { // if in same date, only check when both had time entered if (fp.timeEntered(INPUT_STARTDATE_PREFIX) && fp.timeEntered(INPUT_ENDDATE_PREFIX)) { if (end.before(start) || end.equals(start)) { v.addError(errors, INPUT_ENDDATE_PREFIX, resexception .getString("input_provided_not_occure_after_previous_start_date_time")); } } } } // YW >> if (!errors.isEmpty()) { setInputMessages(errors); String prefixes[] = { INPUT_STARTDATE_PREFIX, INPUT_ENDDATE_PREFIX }; fp.setCurrentDateTimeValuesAsPreset(prefixes); setPresetValues(fp.getPresetValues()); studyEvent.setLocation(fp.getString(INPUT_LOCATION)); request.setAttribute("changeDate", fp.getString("changeDate")); request.setAttribute(EVENT_BEAN, studyEvent); forwardPage(Page.UPDATE_STUDY_EVENT); } else if (studyEvent.getSubjectEventStatus().isSigned()) { // Checks if the status is signed // ----------------- request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); if (fp.getString(INPUT_STARTDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Half").equals("")) { studyEvent.setStartTimeFlag(false); } else { studyEvent.setStartTimeFlag(true); } studyEvent.setDateStarted(start); if (!strEnd.equals("")) { studyEvent.setDateEnded(end); if (fp.getString(INPUT_ENDDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Half").equals("")) { studyEvent.setEndTimeFlag(false); } else { studyEvent.setEndTimeFlag(true); } } studyEvent.setLocation(fp.getString(INPUT_LOCATION)); studyEvent.setStudyEventDefinition(sed); // ------------------- ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssb = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); ecdao = new EventCRFDAO(sm.getDataSource()); eventCRFs = ecdao.findAllByStudyEvent(studyEvent); ArrayList<Boolean> doRuleSetsExist = new ArrayList<Boolean>(); RuleSetDAO ruleSetDao = new RuleSetDAO(sm.getDataSource()); StudyBean study = (StudyBean) sdao.findByPK(ssb.getStudyId()); ArrayList eventDefinitionCRFs = (ArrayList) edcdao.findAllActiveByEventDefinitionId(study, studyEvent.getStudyEventDefinitionId()); ArrayList uncompletedEventDefinitionCRFs = getUncompletedCRFs(eventDefinitionCRFs, eventCRFs); populateUncompletedCRFsWithCRFAndVersions(uncompletedEventDefinitionCRFs); ArrayList displayEventCRFs = ViewStudySubjectServlet.getDisplayEventCRFs(sm.getDataSource(), eventCRFs, eventDefinitionCRFs, ub, currentRole, studyEvent.getSubjectEventStatus(), study); request.setAttribute("studySubject", ssb); request.setAttribute("uncompletedEventDefinitionCRFs", uncompletedEventDefinitionCRFs); request.setAttribute("displayEventCRFs", displayEventCRFs); request.setAttribute(EVENT_BEAN, studyEvent); session.setAttribute("eventSigned", studyEvent); DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil(); DisplayStudyEventBean displayEvBean = new DisplayStudyEventBean(); List<DisplayStudyEventBean> displayEvents = new ArrayList<DisplayStudyEventBean>(); // Set up a Map for the JSP view, mapping the eventCRFId to // another Map: the // inner Map maps the resolution status name to the number of // notes for that // eventCRF id, as in New --> 2 displayEvBean.setDisplayEventCRFs(displayEventCRFs); displayEvBean.setStudyEvent(studyEvent); displayEvents.add(displayEvBean); // Don't filter for res status or disc note type; disc note // beans are returned with eventCRFId set discNoteUtil.injectParentDiscNotesIntoDisplayStudyEvents(displayEvents, new HashSet(), sm.getDataSource(), 0); Map discNoteByEventCRFid = discNoteUtil.createDiscNoteMapByEventCRF(displayEvents); request.setAttribute("discNoteByEventCRFid", discNoteByEventCRFid); session.setAttribute("signatureURL", request.getRequestURL()); String originationUrl = "UpdateStudyEvent?action=" + action + "%26event_id=" + studyEventId + "%26ss_id=" + studySubjectId + "%26startDate=" + start_date + "%26startHour=" + fp.getString(INPUT_STARTDATE_PREFIX + "Hour") + "%26startMinute=" + fp.getString(INPUT_STARTDATE_PREFIX + "Minute") + "%26startHalf=" + fp.getString(INPUT_STARTDATE_PREFIX + "Half") + "%26endDate=" + end_date + "%26endHour=" + fp.getString(INPUT_ENDDATE_PREFIX + "Hour") + "%26endMinute=" + fp.getString(INPUT_ENDDATE_PREFIX + "Minute") + "%26endHalf=" + fp.getString(INPUT_ENDDATE_PREFIX + "Half") + "%26statusId=" + studyEvent.getSubjectEventStatus().getId(); request.setAttribute(ORIGINATING_PAGE, originationUrl); // response.sendRedirect(request.getContextPath() + "/pages/userSignature"); forwardPage(Page.UPDATE_STUDY_EVENT_SIGNED); } else { logger.debug("no validation error"); // YW 08-17-2007 << update start_time_flag column if (fp.getString(INPUT_STARTDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Half").equals("")) { studyEvent.setStartTimeFlag(false); } else { studyEvent.setStartTimeFlag(true); } // YW >> studyEvent.setDateStarted(start); // YW, 3-12-2008, 2220 fix which adding End datetime << if (!strEnd.equals("")) { studyEvent.setDateEnded(end); if (fp.getString(INPUT_ENDDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Half").equals("")) { studyEvent.setEndTimeFlag(false); } else { studyEvent.setEndTimeFlag(true); } } // YW >> studyEvent.setLocation(fp.getString(INPUT_LOCATION)); logger.debug("update study event and discrepancy notes..."); studyEvent.setUpdater(ub); studyEvent.setUpdatedDate(new Date()); updateClosedQueriesForUpdatedStudySubjectFields(studyEvent); StudyEventBean updatedStudyEvent = (StudyEventBean) sedao.update(studyEvent); // save discrepancy notes into DB FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource()); AddNewSubjectServlet.saveFieldNotes(INPUT_LOCATION, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); // getRuleSetService().runRulesInBeanProperty(createRuleSet(ssub,sed),currentStudy,ub,request,ssub); addPageMessage(respage.getString("study_event_updated")); request.setAttribute("id", new Integer(studySubjectId).toString()); session.removeAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); // FORWARD SHOULD BE TO THE NEW PAGE } } else if (action.equalsIgnoreCase("confirm")) {// confirming the signed // status String username = request.getParameter("j_user"); String password = request.getParameter("j_pass"); if (username == null) username = ""; if (password == null) password = ""; // tring encodedUserPass = // org.akaza.openclinica.core.SecurityManager.getInstance().encrytPassword(password); UserAccountBean ub = (UserAccountBean) session.getAttribute("userBean"); StudyEventBean seb = (StudyEventBean) session.getAttribute("eventSigned"); Auth0UserService auth0UserService = ctx.getBean("auth0UserService", Auth0UserServiceImpl.class); boolean isAuthenticated = auth0UserService.authenticateAuth0User(username, password); if (isAuthenticated && ub.getName().equals(username)) { Date date = new Date(); seb.setUpdater(ub); seb.setUpdatedDate(date); seb.setAttestation("The eCRFs that are part of this event were signed by " + ub.getFirstName() + " " + ub.getLastName() + " (" + ub.getName() + ") " + "on Date Time " + date + " under the following attestation:\n\n" + resword.getString("sure_to_sign_subject3")); sedao.update(seb); // If all the StudyEvents become signed we will make the // StudySubject signed as well List studyEvents = sedao.findAllByStudySubject(ssub); boolean allSigned = true; for (Iterator iterator = studyEvents.iterator(); iterator.hasNext();) { StudyEventBean temp = (StudyEventBean) iterator.next(); if (!temp.getSubjectEventStatus().equals(SubjectEventStatus.SIGNED)) { allSigned = false; break; } } if (allSigned) { logger.debug("Signing StudySubject [" + ssub.getSubjectId() + "]"); ssub.setStatus(Status.SIGNED); ssub.setUpdater(ub); ssdao.update(ssub); } // save discrepancy notes into DB FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource()); AddNewSubjectServlet.saveFieldNotes(INPUT_LOCATION, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); session.removeAttribute("eventSigned"); request.setAttribute("id", new Integer(studySubjectId).toString()); addPageMessage(respage.getString("study_event_updated")); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); } else { request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); request.setAttribute("studyEvent", seb); // ------------------- ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssb = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); // prepare to figure out what the display should look like EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource()); ArrayList<EventCRFBean> eventCRFs = ecdao.findAllByStudyEvent(studyEvent); ArrayList<Boolean> doRuleSetsExist = new ArrayList<Boolean>(); RuleSetDAO ruleSetDao = new RuleSetDAO(sm.getDataSource()); StudyBean study = (StudyBean) sdao.findByPK(ssb.getStudyId()); ArrayList eventDefinitionCRFs = (ArrayList) edcdao.findAllActiveByEventDefinitionId(study, studyEvent.getStudyEventDefinitionId()); ArrayList uncompletedEventDefinitionCRFs = getUncompletedCRFs(eventDefinitionCRFs, eventCRFs); populateUncompletedCRFsWithCRFAndVersions(uncompletedEventDefinitionCRFs); ArrayList<DisplayEventCRFBean> displayEventCRFs = ViewStudySubjectServlet.getDisplayEventCRFs( sm.getDataSource(), eventCRFs, eventDefinitionCRFs, ub, currentRole, studyEvent.getSubjectEventStatus(), study); DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil(); DisplayStudyEventBean displayEvBean = new DisplayStudyEventBean(); List<DisplayStudyEventBean> displayEvents = new ArrayList<DisplayStudyEventBean>(); displayEvBean.setDisplayEventCRFs(displayEventCRFs); displayEvBean.setStudyEvent(studyEvent); displayEvents.add(displayEvBean); discNoteUtil.injectParentDiscNotesIntoDisplayStudyEvents(displayEvents, new HashSet(), sm.getDataSource(), 0); Map discNoteByEventCRFid = discNoteUtil.createDiscNoteMapByEventCRF(displayEvents); request.setAttribute("discNoteByEventCRFid", discNoteByEventCRFid); request.setAttribute("studySubject", ssb); request.setAttribute("uncompletedEventDefinitionCRFs", uncompletedEventDefinitionCRFs); request.setAttribute("displayEventCRFs", displayEventCRFs); // ------------------ request.setAttribute("studyEvent", session.getAttribute("eventSigned")); addPageMessage(restext.getString("password_match")); String originationUrl = "UpdateStudyEvent?action=" + action + "%26event_id=" + studyEventId + "%26ss_id=" + studySubjectId + "%26startDate=" + start_date + "%26startHour=" + fp.getString(INPUT_STARTDATE_PREFIX + "Hour") + "%26startMinute=" + fp.getString(INPUT_STARTDATE_PREFIX + "Minute") + "%26startHalf=" + fp.getString(INPUT_STARTDATE_PREFIX + "Half") + "%26endDate=" + end_date + "%26endHour=" + fp.getString(INPUT_ENDDATE_PREFIX + "Hour") + "%26endMinute=" + fp.getString(INPUT_ENDDATE_PREFIX + "Minute") + "%26endHalf=" + fp.getString(INPUT_ENDDATE_PREFIX + "Half") + "%26statusId=" + studyEvent.getSubjectEventStatus().getId(); request.setAttribute(ORIGINATING_PAGE, originationUrl); forwardPage(Page.UPDATE_STUDY_EVENT_SIGNED); } } else { logger.debug("no action, go to update page"); DiscrepancyNoteDAO discrepancyNoteDAO = new DiscrepancyNoteDAO(sm.getDataSource()); StudySubjectBean studySubjectBean = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); int studyId = studySubjectBean.getStudyId(); boolean subjectStudyIsCurrentStudy = studyId == currentStudy.getId(); boolean isParentStudy = studyBean.getParentStudyId() < 1; ArrayList<DiscrepancyNoteBean> allNotesforSubjectAndEvent = new ArrayList<DiscrepancyNoteBean>(); allNotesforSubjectAndEvent = discrepancyNoteDAO.findExistingNoteForStudyEvent(studyEvent); if (!allNotesforSubjectAndEvent.isEmpty()) { setRequestAttributesForNotes(allNotesforSubjectAndEvent); } HashMap presetValues = new HashMap(); // YW 08-17-2007 << if (studyEvent.getDateStarted() != null) { if (studyEvent.getStartTimeFlag() == true) { Calendar c = new GregorianCalendar(); c.setTime(studyEvent.getDateStarted()); presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(c.get(Calendar.HOUR_OF_DAY))); presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(c.get(Calendar.MINUTE))); // Later it could be put to somewhere as a static method if // necessary. switch (c.get(Calendar.AM_PM)) { case 0: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", "am"); break; case 1: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", "pm"); break; default: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", ""); break; } } else { presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(-1)); presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(-1)); presetValues.put(INPUT_STARTDATE_PREFIX + "Half", ""); } // YW >> String dateValue = local_df.format(studyEvent.getDateStarted()); presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue); // YW 3-12-2008, add end datetime for 2220 fix<< presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(-1)); presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(-1)); presetValues.put(INPUT_ENDDATE_PREFIX + "Half", ""); } if (studyEvent.getDateEnded() != null) { if (studyEvent.getEndTimeFlag() == true) { Calendar c = new GregorianCalendar(); c.setTime(studyEvent.getDateEnded()); presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(c.get(Calendar.HOUR_OF_DAY))); presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(c.get(Calendar.MINUTE))); // Later it could be put to somewhere as a static method if // necessary. switch (c.get(Calendar.AM_PM)) { case 0: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", "am"); break; case 1: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", "pm"); break; default: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", ""); break; } } presetValues.put(INPUT_ENDDATE_PREFIX + "Date", local_df.format(studyEvent.getDateEnded())); } // YW >> setPresetValues(presetValues); request.setAttribute("studyEvent", studyEvent); request.setAttribute("studySubject", studySubjectBean); discNotes = new FormDiscrepancyNotes(); session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes); forwardPage(Page.UPDATE_STUDY_EVENT); } // else }
From source file:org.motechproject.server.svc.impl.RegistrarBeanImpl.java
private void createScheduledMessage(Integer recipientId, MessageDefinition messageDefinition, MessageProgramEnrollment enrollment, Date messageDate, Date currentDate) { List<ScheduledMessage> scheduledMessages = motechService().getScheduledMessages(recipientId, messageDefinition, enrollment, messageDate); // Add scheduled message and message attempt is none matching exists if (scheduledMessages.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Creating ScheduledMessage: recipient: " + recipientId + ", enrollment: " + enrollment.getId() + ", message key: " + messageDefinition.getMessageKey() + ", date: " + messageDate);/* w ww. j av a 2 s .c om*/ } ScheduledMessage scheduledMessage = new ScheduledMessage(messageDate, recipientId, messageDefinition, enrollment); Message message = messageDefinition.createMessage(scheduledMessage); message.setAttemptDate(messageDate); scheduledMessage.getMessageAttempts().add(message); motechService().saveScheduledMessage(scheduledMessage); } else { if (scheduledMessages.size() > 1 && log.isWarnEnabled()) { log.warn("Multiple matching scheduled messages: recipient: " + recipientId + ", enrollment: " + enrollment.getId() + ", message key: " + messageDefinition.getMessageKey() + ", date: " + messageDate); } // Add message attempt to existing scheduled message if not exist boolean matchFound = false; ScheduledMessage scheduledMessage = scheduledMessages.get(0); for (Message message : scheduledMessage.getMessageAttempts()) { if ((MessageStatus.SHOULD_ATTEMPT == message.getAttemptStatus() || MessageStatus.ATTEMPT_PENDING == message.getAttemptStatus() || MessageStatus.DELIVERED == message.getAttemptStatus() || MessageStatus.REJECTED == message.getAttemptStatus()) && messageDate.equals(message.getAttemptDate())) { matchFound = true; break; } } if (!matchFound && !currentDate.after(messageDate)) { if (log.isDebugEnabled()) { log.debug("Creating Message: recipient: " + recipientId + ", enrollment: " + enrollment.getId() + ", message key: " + messageDefinition.getMessageKey() + ", date: " + messageDate); } Message message = messageDefinition.createMessage(scheduledMessage); message.setAttemptDate(messageDate); scheduledMessage.getMessageAttempts().add(message); motechService().saveScheduledMessage(scheduledMessage); } } }
From source file:org.etudes.jforum.view.admin.CategoryAction.java
/** * save categiry start and end dates//w w w . jav a 2s .com */ protected void saveCategoryDates() throws Exception { boolean isfacilitator = JForumUserUtil.isJForumFacilitator(UserDirectoryService.getCurrentUser().getId()) || SecurityService.isSuperUser(); if (!isfacilitator) { this.context.put("message", I18n.getMessage("User.NotAuthorizedToManage")); this.setTemplateName(TemplateKeys.MANAGE_NOT_AUTHORIZED); return; } List<String> errors = new ArrayList<String>(); boolean errFlag = false; StringBuffer categoryNameList = new StringBuffer(); Enumeration<?> paramNames = this.request.getParameterNames(); JForumCategoryService jforumCategoryService = (JForumCategoryService) ComponentManager .get("org.etudes.api.app.jforum.JForumCategoryService"); List<org.etudes.api.app.jforum.Category> existingCategories = jforumCategoryService.getManageCategories( ToolManager.getInstance().getCurrentPlacement().getContext(), UserDirectoryService.getCurrentUser().getId()); Map<Integer, org.etudes.api.app.jforum.Category> exisCatMap = new HashMap<Integer, org.etudes.api.app.jforum.Category>(); for (org.etudes.api.app.jforum.Category exisCat : existingCategories) { exisCatMap.put(Integer.valueOf(exisCat.getId()), exisCat); } while (paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); if (paramName.startsWith("startdate_")) { // paramName is in the format startdate_forumId String id[] = paramName.split("_"); String categoryId = null; categoryId = id[1]; org.etudes.api.app.jforum.Category existingCategory = exisCatMap.get(Integer.valueOf(categoryId)); if (existingCategory == null) { continue; } //startdate_forumId String startDateParam = null; startDateParam = this.request.getParameter("startdate_" + id[1]); Date startDate = null; Boolean hideUntilOpen = Boolean.FALSE; if (startDateParam != null && startDateParam.trim().length() > 0) { try { startDate = DateUtil.getDateFromString(startDateParam.trim()); //hideuntilopen_categoryId String hideUntilOpenStr = this.request.getParameter("hideuntilopen_" + id[1]); if (hideUntilOpenStr != null && "1".equals(hideUntilOpenStr)) { hideUntilOpen = Boolean.TRUE; } } catch (ParseException e) { errFlag = true; categoryNameList.append(existingCategory.getTitle()); categoryNameList.append(","); continue; } } //enddate_categoryId String endDateParam = null; endDateParam = this.request.getParameter("enddate_" + id[1]); Date endDate = null; //boolean lockCategory = false; if (endDateParam != null && endDateParam.trim().length() > 0) { try { endDate = DateUtil.getDateFromString(endDateParam.trim()); } catch (ParseException e) { errFlag = true; categoryNameList.append(existingCategory.getTitle()); categoryNameList.append(","); continue; } //lockcategory_categoryId /*String lockCategoryStr = this.request.getParameter("lockcategory_"+ id[1]); if (lockCategoryStr != null && "1".equals(lockCategoryStr)) { lockCategory = true; }*/ } //allowuntildate_categoryId String allowUntilDateParam = null; allowUntilDateParam = this.request.getParameter("allowuntildate_" + id[1]); Date allowUntilDate = null; if (allowUntilDateParam != null && allowUntilDateParam.trim().length() > 0) { try { allowUntilDate = DateUtil.getDateFromString(allowUntilDateParam.trim()); } catch (ParseException e) { errFlag = true; categoryNameList.append(existingCategory.getTitle()); categoryNameList.append(","); continue; } } // update if there are date changes boolean datesChanged = false; // open date if (existingCategory.getAccessDates().getOpenDate() == null) { if (startDate != null) { datesChanged = true; } } else { if (startDate == null) { datesChanged = true; } else if (!startDate.equals(existingCategory.getAccessDates().getOpenDate())) { datesChanged = true; } else if (startDate.equals(existingCategory.getAccessDates().getOpenDate())) { if (!existingCategory.getAccessDates().isHideUntilOpen().equals(hideUntilOpen)) { datesChanged = true; } } } // due date if (!datesChanged) { if (existingCategory.getAccessDates().getDueDate() == null) { if (endDate != null) { datesChanged = true; } } else { if (endDate == null) { datesChanged = true; } else if (!endDate.equals(existingCategory.getAccessDates().getDueDate())) { datesChanged = true; } } } // allow until date if (!datesChanged) { if (existingCategory.getAccessDates().getAllowUntilDate() == null) { if (allowUntilDate != null) { datesChanged = true; } } else { if (allowUntilDate == null) { datesChanged = true; } else if (!allowUntilDate.equals(existingCategory.getAccessDates().getAllowUntilDate())) { datesChanged = true; } } } if (datesChanged) { /*int topicDatesCount = DataAccessDriver.getInstance().newTopicDAO().getTopicDatesCountByCategory(existingCategory.getId()); int forumDatesCount = DataAccessDriver.getInstance().newForumDAO().getForumDatesCount(existingCategory.getId()); if ((topicDatesCount > 0) || (forumDatesCount > 0)) { existingCategory.getAccessDates().setOpenDate(null); existingCategory.getAccessDates().setDueDate(null); existingCategory.getAccessDates().setLocked(false); }*/ //DataAccessDriver.getInstance().newCategoryDAO().updateDates(c); if (startDate != null) { existingCategory.getAccessDates().setOpenDate(startDate); existingCategory.getAccessDates().setHideUntilOpen(hideUntilOpen); } else { existingCategory.getAccessDates().setOpenDate(null); existingCategory.getAccessDates().setHideUntilOpen(null); } if (endDate != null) { existingCategory.getAccessDates().setDueDate(endDate); //existingCategory.getAccessDates().setLocked(Boolean.valueOf(lockCategory)); } else { existingCategory.getAccessDates().setDueDate(null); //existingCategory.getAccessDates().setLocked(Boolean.FALSE); } if (allowUntilDate != null) { existingCategory.getAccessDates().setAllowUntilDate(allowUntilDate); } else { existingCategory.getAccessDates().setAllowUntilDate(null); } jforumCategoryService.updateDates(existingCategory, Type.CATEGORY); // update gradable categories with date changes in the gradebook /*if (c.isGradeCategory()) { Grade catGrade = DataAccessDriver.getInstance().newGradeDAO().selectByCategoryId(c.getId()); boolean addToGradeBook = false; if (catGrade != null && catGrade.isAddToGradeBook()) { addToGradeBook = updateGradebook(catGrade); catGrade.setAddToGradeBook(addToGradeBook); DataAccessDriver.getInstance().newGradeDAO().updateAddToGradeBookStatus(catGrade.getId(), addToGradeBook); } } else { // update gradable forum and topic dates in the gradebook updateGradebookForumsTopics(c); }*/ } /* // paramName is in the format startdate_forumId String id[] = paramName.split("_"); String categoryId = null; categoryId = id[1]; Category existingCategory = DataAccessDriver.getInstance().newCategoryDAO().selectById(Integer.parseInt(categoryId)); Category c = new Category(existingCategory); //startdate_forumId String startDateParam = null; startDateParam = this.request.getParameter("startdate_"+ id[1]); if (startDateParam != null && startDateParam.trim().length() > 0) { Date startDate; try { startDate = DateUtil.getDateFromString(startDateParam.trim()); } catch (ParseException e) { errFlag = true; categoryNameList.append(c.getName()); categoryNameList.append(","); continue; } c.setStartDate(startDate); } else { c.setStartDate(null); } //enddate_forumId String endDateParam = null; endDateParam = this.request.getParameter("enddate_"+ id[1]); if (endDateParam != null && endDateParam.trim().length() > 0) { Date endDate; try { endDate = DateUtil.getDateFromString(endDateParam.trim()); } catch (ParseException e) { errFlag = true; categoryNameList.append(c.getName()); categoryNameList.append(","); continue; } c.setEndDate(endDate); //lockforum_forumId String lockForum = this.request.getParameter("lockcategory_"+ id[1]); if (lockForum!= null && "1".equals(lockForum)){ c.setLockCategory(true); } else { c.setLockCategory(false); } } else { c.setEndDate(null); c.setLockCategory(false); } // update if there are date changes boolean datesChanged = false; if (existingCategory.getStartDate() == null) { if (c.getStartDate() != null) { datesChanged = true; } } else { if (c.getStartDate() == null) { datesChanged = true; } else if (!c.getStartDate().equals(existingCategory.getStartDate())) { datesChanged = true; } } if (!datesChanged) { if (existingCategory.getEndDate() == null) { if (c.getEndDate() != null) { datesChanged = true; } } else { if (c.getEndDate() == null) { datesChanged = true; } else if (!c.getEndDate().equals(existingCategory.getStartDate())) { datesChanged = true; } } } if (datesChanged) { int topicDatesCount = DataAccessDriver.getInstance().newTopicDAO().getTopicDatesCountByCategory(c.getId()); int forumDatesCount = DataAccessDriver.getInstance().newForumDAO().getForumDatesCount(c.getId()); if ((topicDatesCount > 0) || (forumDatesCount > 0)) { c.setStartDate(null); c.setEndDate(null); c.setLockCategory(false); } DataAccessDriver.getInstance().newCategoryDAO().updateDates(c); // update gradable categories with date changes in the gradebook if (c.isGradeCategory()) { Grade catGrade = DataAccessDriver.getInstance().newGradeDAO().selectByCategoryId(c.getId()); boolean addToGradeBook = false; if (catGrade != null && catGrade.isAddToGradeBook()) { addToGradeBook = updateGradebook(catGrade); catGrade.setAddToGradeBook(addToGradeBook); DataAccessDriver.getInstance().newGradeDAO().updateAddToGradeBookStatus(catGrade.getId(), addToGradeBook); } } else { // update gradable forum and topic dates in the gradebook updateGradebookForumsTopics(c); } } */ } } if (errFlag == true) { String categoryNameListStr = categoryNameList.toString(); if (categoryNameListStr.endsWith(",")) { categoryNameListStr = categoryNameListStr.substring(0, categoryNameListStr.length() - 1); } errors.add(I18n.getMessage("Forums.List.CannotUpdateForumDates", new Object[] { categoryNameListStr })); } if (errors.size() > 0) { this.context.put("errorMessage", errors); } }
From source file:org.ow2.bonita.persistence.db.DbSessionImpl.java
@Override public List<Integer> getNumberOfOpenStepsPerDay(Date since, final Date to) { final List<Integer> finishedCases = new ArrayList<Integer>(); while (since.before(to) || since.equals(to)) { final Date nextDayBegining = DateUtil.getBeginningOfTheDay(DateUtil.getNextDay(since)); final Query query = getSession().getNamedQuery("getNumberOfOpenSteps2"); query.setLong("date", nextDayBegining.getTime()); finishedCases.add(((Long) query.uniqueResult()).intValue()); since = DateUtil.getNextDay(since); }/*from w w w.j a v a 2 s . com*/ return finishedCases; }
From source file:org.ow2.bonita.persistence.db.DbSessionImpl.java
@Override public List<Integer> getNumberOfExecutingCasesPerDay(Date since, final Date to) { final List<Integer> executingCases = new ArrayList<Integer>(); while (since.before(to) || since.equals(to)) { final Date nextDayBegining = DateUtil.getBeginningOfTheDay(DateUtil.getNextDay(since)); final Query query = getSession().getNamedQuery("getNumberOfExecutingCases"); query.setLong("date", nextDayBegining.getTime()); executingCases.add(((Long) query.uniqueResult()).intValue()); since = DateUtil.getNextDay(since); }// w w w. j a v a 2 s . c o m return executingCases; }