List of usage examples for java.util Date equals
public boolean equals(Object obj)
From source file:org.motechproject.server.svc.impl.RegistrarBeanImpl.java
public void verifyMessageAttemptDate(ScheduledMessage scheduledMessage, boolean userPreferenceBased, Date currentDate) {/* w ww. ja v a 2 s . c o m*/ Person recipient = personService.getPerson(scheduledMessage.getRecipientId()); List<Message> messages = scheduledMessage.getMessageAttempts(); if (!messages.isEmpty()) { Message recentMessage = messages.get(0); if (recentMessage.getAttemptStatus() == MessageStatus.SHOULD_ATTEMPT) { Date attemptDate = recentMessage.getAttemptDate(); // Check if current message date is valid for user // preferences or blackout in case these have changed attemptDate = adjustDateForBlackout(attemptDate); if (!attemptDate.equals(recentMessage.getAttemptDate())) { // Recompute from original scheduled message date // Allows possibly adjusting to an earlier week or day Date adjustedMessageDate = adjustCareMessageDate(recipient, scheduledMessage.getScheduledFor(), userPreferenceBased, currentDate); if (log.isDebugEnabled()) { log.debug("Updating message id=" + recentMessage.getId() + " date from=" + recentMessage.getAttemptDate() + " to=" + adjustedMessageDate); } recentMessage.setAttemptDate(adjustedMessageDate); scheduledMessage.getMessageAttempts().set(0, recentMessage); motechService().saveScheduledMessage(scheduledMessage); } } } }
From source file:org.motechproject.server.svc.impl.RegistrarBeanImpl.java
@Transactional public void editPatient(User staff, Date date, Patient patient, Patient mother, String phoneNumber, ContactNumberType phoneOwnership, String nhis, Date nhisExpires, Date expectedDeliveryDate, Boolean stopEnrollment) { if (expectedDeliveryDate != null) { Obs pregnancy = getActivePregnancy(patient.getPatientId()); Obs dueDateObs = getActivePregnancyDueDateObs(patient.getPatientId(), pregnancy); if (dueDateObs != null) { if (!expectedDeliveryDate.equals(dueDateObs.getValueDatetime())) { updatePregnancyDueDateObs(pregnancy, dueDateObs, expectedDeliveryDate, dueDateObs.getEncounter()); }//from w w w . j a va2 s . co m } } setPatientAttributes(patient, phoneNumber, phoneOwnership, null, null, null, null, null, null, null, nhis, nhisExpires); patientService.savePatient(patient); relationshipService.saveOrUpdateMotherRelationship(mother, patient, false); if (Boolean.TRUE.equals(stopEnrollment)) { stopEnrollmentFor(patient.getPatientId()); } }
From source file:org.apache.lens.cube.metadata.CubeMetastoreClient.java
public boolean isStorageTablePartitionACandidate(String storageTableName, Date partDate) throws LensException { List<Date> storageStartDates = getStorageTimes(storageTableName, MetastoreUtil.getStoragetableStartTimesKey()); for (Date startDate : storageStartDates) { if (partDate.before(startDate)) { log.info("part date {} is before validity start time: {}, hence discarding {}", partDate, startDate, storageTableName);/*from w w w.j a v a 2 s .com*/ return false; } } List<Date> storageEndDates = getStorageTimes(storageTableName, MetastoreUtil.getStoragetableEndTimesKey()); for (Date endDate : storageEndDates) { // end date should be exclusive if (partDate.after(endDate) || partDate.equals(endDate)) { log.info("part date {} is after validity end time: {}, hence discarding {}", partDate, endDate, storageTableName); return false; } } return true; }
From source file:edu.byu.mpn.test.DeviceControllerUnitTest.java
@Test public void testUpdateDevice() { deviceDao.saveOrUpdateDevice(new Device(null, "deviceId", "personId", VALID_TOKEN, "deviceName", "Apple", new Date(), null, null), "what"); Device device = deviceDao.getDeviceById(1); Date dateRegistered = device.getDateRegistered(); Date dateTimeUpdated = device.getDateTimeUpdated(); try {/*w w w. j a v a 2s. co m*/ Thread.sleep(100); } catch (InterruptedException e) { LOG.error(e); } // Tests that the proper error responses are returned Response response = controller.updateDevice(1, "personId", null); assertEquals(400, response.getStatus()); assertTrue(DeviceController.EX_EMPTY_REQUEST.equals(((ResponseMessage) response.getEntity()).getMessage())); response = controller.updateDevice(1, "personId", new Device()); assertEquals(400, response.getStatus()); assertTrue(DeviceController.EX_MISSING_ID.equals(((ResponseMessage) response.getEntity()).getMessage())); response = controller.updateDevice(1, "personId", new Device(null, "personId", VALID_TOKEN, dateTimeUpdated)); assertEquals(400, response.getStatus()); assertTrue(DeviceController.EX_MISSING_ID.equals(((ResponseMessage) response.getEntity()).getMessage())); response = controller.updateDevice(1, "personId", new Device(2, "personId", VALID_TOKEN, dateTimeUpdated)); assertEquals(400, response.getStatus()); assertTrue(DeviceController.EX_ID_CONFLICT.equals(((ResponseMessage) response.getEntity()).getMessage())); response = controller.updateDevice(1, "personId", new Device(1, null, VALID_TOKEN, dateTimeUpdated)); assertEquals(400, response.getStatus()); assertTrue( DeviceController.EX_PERSONID_MISSING.equals(((ResponseMessage) response.getEntity()).getMessage())); response = controller.updateDevice(1, "personId", new Device(1, "personId", null, dateTimeUpdated)); assertEquals(400, response.getStatus()); assertTrue(DeviceController.EX_TOKEN_MISSING.equals(((ResponseMessage) response.getEntity()).getMessage())); assertEquals(400, controller.updateDevice(1, "personId", new Device(1, "personId", "invalid token", dateTimeUpdated)) .getStatus()); response = controller.updateDevice(1, "notPersonId", new Device(1, "notPersonId", VALID_TOKEN, dateTimeUpdated)); assertEquals(403, response.getStatus()); assertTrue(DeviceController.EX_NACHO_DEVICE.equals(((ResponseMessage) response.getEntity()).getMessage())); response = controller.updateDevice(1, "notPersonId", new Device(1, "personId", VALID_TOKEN, dateTimeUpdated)); assertEquals(403, response.getStatus()); assertTrue( DeviceController.EX_NACHO_PERSONID.equals(((ResponseMessage) response.getEntity()).getMessage())); assertEquals(404, controller.updateDevice(2, "personId", new Device(2, "what", "what", new Date())).getStatus()); // When personId is changed, dateRegistered is updated device.setPersonId(null); assertEquals(200, controller .updateDevice(1, "notPersonId", new Device(1, "notPersonId", VALID_TOKEN, dateTimeUpdated)) .getStatus()); assertFalse(dateRegistered.equals(device.getDateRegistered())); assertFalse(dateTimeUpdated.equals(device.getDateTimeUpdated())); // When device is edited but personId is not changed, dateRegistered stays the same dateRegistered = device.getDateRegistered(); dateTimeUpdated = device.getDateTimeUpdated(); try { Thread.sleep(100); } catch (InterruptedException e) { LOG.error(e); } assertEquals(200, controller .updateDevice(1, "notPersonId", new Device(1, "notPersonId", VALID_TOKEN, dateTimeUpdated)) .getStatus()); assertTrue(dateRegistered.equals(device.getDateRegistered())); assertFalse(dateTimeUpdated.equals(device.getDateTimeUpdated())); dateTimeUpdated = device.getDateTimeUpdated(); // Extra fields included in device aren't updated, deviceId and deviceName are device = deviceDao.getDeviceById(1); Device device1 = new Device(device); assertEquals(200, controller .updateDevice(1, "notPersonId", new Device(1, "deviceId", "notPersonId", VALID_TOKEN, "what", "what", "deviceName", "what", new Date(), dateTimeUpdated, "who")) .getStatus()); assertTrue(device1.equals(deviceDao.getDeviceById(1))); dateTimeUpdated = deviceDao.getDeviceById(1).getDateTimeUpdated(); assertEquals(200, controller.updateDevice(1, "notPersonId", new Device(1, "notDeviceId", "notPersonId", VALID_TOKEN, null, null, "notDeviceName", null, null, dateTimeUpdated, null)).getStatus()); assertFalse(device1.equals(deviceDao.getDeviceById(1))); }
From source file:org.egov.ptis.domain.service.property.PropertyExternalService.java
/** * API to update property - used in Mobile App * //from w w w .j a v a 2s . c o m * @param viewPropertyDetails * @return NewPropertyDetails * @throws ParseException */ public NewPropertyDetails updateProperty(ViewPropertyDetails viewPropertyDetails) throws ParseException { NewPropertyDetails newPropertyDetails = null; BigDecimal activeTax = BigDecimal.ZERO; final PropertyService propService = beanProvider.getBean(PROP_SERVICE, PropertyService.class); BasicProperty basicProperty = updateBasicProperty(viewPropertyDetails, propService); PropertyImpl property = (PropertyImpl) basicProperty.getWFProperty(); PropertyImpl activeProperty = basicProperty.getActiveProperty(); property.getPropertyDetail().setCategoryType(viewPropertyDetails.getCategory()); basicProperty.setUnderWorkflow(Boolean.TRUE); basicProperty.setParcelId(viewPropertyDetails.getParcelId()); basicProperty.setLatitude(viewPropertyDetails.getLatitude()); basicProperty.setLongitude(viewPropertyDetails.getLongitude()); property.setReferenceId(viewPropertyDetails.getReferenceId()); /* * Duplicate GIS property will be persisted, which will be used for generating comparison reports */ PropertyImpl gisProperty = (PropertyImpl) property.createPropertyclone(); if (!gisProperty.getPropertyDetail().getFloorDetails().isEmpty()) { for (Floor floor : gisProperty.getPropertyDetail().getFloorDetails()) { floor.setPropertyDetail(gisProperty.getPropertyDetail()); basicPropertyService.applyAuditing(floor); } } gisProperty.setStatus('G'); gisProperty.setSource(SOURCE_SURVEY); Ptdemand ptdemand = property.getPtDemandSet().iterator().next(); Ptdemand gisPtdemand = gisProperty.getPtDemandSet().iterator().next(); if (gisPtdemand != null) gisPtdemand.getDmdCalculations().setAlv(ptdemand.getDmdCalculations().getAlv()); basicProperty.addProperty(gisProperty); basicPropertyService.applyAuditing(gisPtdemand.getDmdCalculations()); transitionWorkFlow(property, propService, PROPERTY_MODE_MODIFY); basicPropertyService.applyAuditing(property.getState()); propService.updateIndexes(property, PropertyTaxConstants.APPLICATION_TYPE_ALTER_ASSESSENT); if (SOURCE_SURVEY.equalsIgnoreCase(property.getSource())) { SurveyBean surveyBean = new SurveyBean(); surveyBean.setProperty(property); BigDecimal totalTax = propService.getSurveyTax(gisProperty, gisPtdemand.getEgInstallmentMaster().getFromDate()); surveyBean.setGisTax(totalTax); surveyBean.setApplicationTax(totalTax); surveyBean.setAgeOfCompletion(propService.getSlaValue(APPLICATION_TYPE_ALTER_ASSESSENT)); if (activeProperty != null) { Ptdemand activePtDemand = ptDemandDAO.getNonHistoryCurrDmdForProperty(activeProperty); Map<String, Installment> yearwiseInstMap = propertyTaxUtil .getInstallmentsForCurrYear(gisPtdemand.getEgInstallmentMaster().getFromDate()); Date firstInstStartDate = yearwiseInstMap.get(PropertyTaxConstants.CURRENTYEAR_FIRST_HALF) .getFromDate(); Date secondInstStartDate = yearwiseInstMap.get(PropertyTaxConstants.CURRENTYEAR_SECOND_HALF) .getFromDate(); for (EgDemandDetails demandDetail : activePtDemand.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())) activeTax = activeTax.add(demandDetail.getAmount()); } surveyBean.setSystemTax(activeTax); } surveyService.updateSurveyIndex(APPLICATION_TYPE_ALTER_ASSESSENT, surveyBean); } if (basicProperty.getWFProperty() != null && basicProperty.getWFProperty().getPtDemandSet() != null && !basicProperty.getWFProperty().getPtDemandSet().isEmpty()) { for (Ptdemand ptDemand : basicProperty.getWFProperty().getPtDemandSet()) { basicPropertyService.applyAuditing(ptDemand.getDmdCalculations()); } } basicProperty = basicPropertyService.update(basicProperty); if (basicProperty != null) { newPropertyDetails = new NewPropertyDetails(); newPropertyDetails.setApplicationNo(basicProperty.getWFProperty().getApplicationNo()); final ErrorDetails errorDetails = new ErrorDetails(); errorDetails.setErrorCode(THIRD_PARTY_ERR_CODE_SUCCESS); errorDetails.setErrorMessage(THIRD_PARTY_ERR_MSG_SUCCESS); newPropertyDetails.setErrorDetails(errorDetails); } return newPropertyDetails; }
From source file:com.krawler.spring.hrms.common.hrmsCommonController.java
public ModelAndView rehireEmp(HttpServletRequest request, HttpServletResponse response) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy"); JSONObject msg = new JSONObject(); //Create transaction DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("JE_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED); TransactionStatus status = txnManager.getTransaction(def); try {/* w ww . ja v a 2 s . com*/ Empprofile e = null; String ids[] = request.getParameterValues("ids"); String deptid = request.getParameter("dept"); String desgid = request.getParameter("desg"); String salary = (request.getParameter("salary")); String reldate = request.getParameter("joindate"); String tempid = request.getParameter("templateid"); Date rvdate = fmt.parse(reldate); Date now = new Date(); for (int i = 0; i < ids.length; i++) { e = (Empprofile) kwlCommonTablesDAOObj.getObject("com.krawler.hrms.ess.Empprofile", ids[i]); if (e != null) { if (e.getRelievedate() != null) { if (e.getRelievedate().after(rvdate)) { msg.put("msg", "invalidjoindate"); msg.put("success", true); txnManager.commit(status); return new ModelAndView("jsonView", "model", msg.toString()); } } } HashMap<String, Object> requestParams = new HashMap<String, Object>(); if (rvdate.before(now) || rvdate.equals(now)) { requestParams.put("termnd", false); } requestParams.put("userid", ids[i]); requestParams.put("joindate", request.getParameter("joindate")); requestParams.put("confirmdate", null); requestParams.put("relievedate", null); hrmsCommonDAOObj.addEmpprofile(requestParams); requestParams.clear(); requestParams.put("UserID", ids[i]); requestParams.put("Department", deptid); requestParams.put("Designationid", desgid); requestParams.put("Salary", salary); requestParams.put("Templateid", tempid); hrmsCommonDAOObj.addUseraccount(requestParams); if (rvdate.before(now) || rvdate.equals(now)) { requestParams.clear(); requestParams.put("UserID", ids[i]); requestParams.put("Deleteflag", 0); hrmsCommonDAOObj.adduser(requestParams); } // User u=(User)session.get(User.class,ids[i]); // Empprofile emp=(Empprofile)session.get(Empprofile.class,ids[i]); // Useraccount ua = (Useraccount) session.get(Useraccount.class, u.getUserID()); // ua.setDepartment((dept)); // ua.setDesignationid(desg); // ua.setSalary(salary); // u.setDeleteflag(0); // if (StringUtil.isNullOrEmpty(tempid) == false) { // ua.setTemplateid(tempid); // } // emp.setJoindate(rvdate); // emp.setTermnd(false); // emp.setRelievedate(null); // session.saveOrUpdate(emp); // session.saveOrUpdate(u); // session.saveOrUpdate(ua); //@@ProfileHandler.insertAuditLog(session, AuditAction.REHIRE_EMPLOYEE, "User " + AuthHandler.getFullName(session, AuthHandler.getUserid(request)) + " has rehired employee " + AuthHandler.getFullName(u) ,request); } msg.put("success", true); txnManager.commit(status); } catch (Exception e) { e.printStackTrace(); txnManager.rollback(status); } finally { //return new ModelAndView("jsonView","model","{\"success\":\"true\"}"); return new ModelAndView("jsonView", "model", msg.toString()); } }
From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java
private void updateToolList(Set<Map.Entry<String, ArrayList<ToolEntry>>> tools, final LinearLayout toolContainer) { if (fiskInfoUtility.isNetworkAvailable(getActivity())) { List<ToolEntry> localTools = new ArrayList<>(); final List<ToolEntry> unconfirmedRemovedTools = new ArrayList<>(); final List<ToolEntry> synchedTools = new ArrayList<>(); for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) { for (final ToolEntry toolEntry : dateEntry.getValue()) { if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) { continue; } else if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED) { synchedTools.add(toolEntry); } else if (!(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED)) { localTools.add(toolEntry); } else { unconfirmedRemovedTools.add(toolEntry); }// ww w . ja v a 2 s . co m } } barentswatchApi.setAccesToken(user.getToken()); Response response = barentswatchApi.getApi().geoDataDownload("fishingfacility", "JSON"); if (response == null) { Log.d(TAG, "RESPONSE == NULL"); } byte[] toolData; try { toolData = FiskInfoUtility.toByteArray(response.getBody().in()); JSONObject featureCollection = new JSONObject(new String(toolData)); JSONArray jsonTools = featureCollection.getJSONArray("features"); JSONArray matchedTools = new JSONArray(); UserSettings settings = user.getSettings(); for (int i = 0; i < jsonTools.length(); i++) { JSONObject tool = jsonTools.getJSONObject(i); boolean hasCopy = false; for (int j = 0; j < localTools.size(); j++) { if (localTools.get(j).getToolId() .equals(tool.getJSONObject("properties").getString("toolid"))) { SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat( getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss), Locale.getDefault()); SimpleDateFormat sdfMilliSecondsRemote = new SimpleDateFormat( getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss), Locale.getDefault()); SimpleDateFormat sdfRemote = new SimpleDateFormat( getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss), Locale.getDefault()); sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC")); /* Timestamps from BW seem to be one hour earlier than UTC/GMT? */ sdfMilliSecondsRemote.setTimeZone(TimeZone.getTimeZone("GMT-1")); sdfRemote.setTimeZone(TimeZone.getTimeZone("GMT-1")); Date localLastUpdatedDateTime; Date localUpdatedBySourceDateTime; Date serverUpdatedDateTime; Date serverUpdatedBySourceDateTime = null; try { localLastUpdatedDateTime = sdfMilliSeconds .parse(localTools.get(j).getLastChangedDateTime()); localUpdatedBySourceDateTime = sdfMilliSeconds .parse(localTools.get(j).getLastChangedBySource()); serverUpdatedDateTime = tool.getJSONObject("properties") .getString("lastchangeddatetime").length() == getResources() .getInteger(R.integer.datetime_without_milliseconds_length) ? sdfRemote.parse(tool.getJSONObject("properties") .getString("lastchangeddatetime")) : sdfMilliSecondsRemote .parse(tool.getJSONObject("properties") .getString("lastchangeddatetime")); if (tool.getJSONObject("properties").has("lastchangedbysource")) { serverUpdatedBySourceDateTime = tool.getJSONObject("properties") .getString("lastchangedbysource").length() == getResources() .getInteger(R.integer.datetime_without_milliseconds_length) ? sdfRemote.parse(tool.getJSONObject("properties") .getString("lastchangedbysource")) : sdfMilliSecondsRemote .parse(tool.getJSONObject("properties") .getString("lastchangedbysource")); } if ((localLastUpdatedDateTime.equals(serverUpdatedDateTime) || localLastUpdatedDateTime.before(serverUpdatedDateTime)) && serverUpdatedBySourceDateTime != null && (localUpdatedBySourceDateTime.equals(serverUpdatedBySourceDateTime) || localUpdatedBySourceDateTime .before(serverUpdatedBySourceDateTime))) { localTools.get(j).updateFromGeoJson(tool, getActivity()); localTools.get(j).setToolStatus(ToolEntryStatus.STATUS_RECEIVED); } else if (serverUpdatedBySourceDateTime != null && localUpdatedBySourceDateTime.after(serverUpdatedBySourceDateTime)) { // TODO: Do nothing, local changes should be reported. } else { // TODO: what gives? } } catch (ParseException e) { e.printStackTrace(); } localTools.remove(j); j--; hasCopy = true; break; } } for (int j = 0; j < unconfirmedRemovedTools.size(); j++) { if (unconfirmedRemovedTools.get(j).getToolId() .equals(tool.getJSONObject("properties").getString("toolid"))) { hasCopy = true; unconfirmedRemovedTools.remove(j); j--; } } for (int j = 0; j < synchedTools.size(); j++) { if (synchedTools.get(j).getToolId() .equals(tool.getJSONObject("properties").getString("toolid"))) { hasCopy = true; synchedTools.remove(j); j--; } } if (!hasCopy && settings != null) { if ((!settings.getVesselName().isEmpty() && (FiskInfoUtility.ReplaceRegionalCharacters(settings.getVesselName()) .equalsIgnoreCase(tool.getJSONObject("properties").getString("vesselname")) || settings.getVesselName().equalsIgnoreCase( tool.getJSONObject("properties").getString("vesselname")))) && ((!settings.getIrcs().isEmpty() && settings.getIrcs().toUpperCase() .equals(tool.getJSONObject("properties").getString("ircs"))) || (!settings.getMmsi().isEmpty() && settings.getMmsi() .equals(tool.getJSONObject("properties").getString("mmsi"))) || (!settings.getImo().isEmpty() && settings.getImo() .equals(tool.getJSONObject("properties").getString("imo"))))) { matchedTools.put(tool); } } } if (matchedTools.length() > 0) { final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button addToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); final List<ToolConfirmationRow> matchedToolsList = new ArrayList<>(); for (int i = 0; i < matchedTools.length(); i++) { ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), matchedTools.getJSONObject(i)); linearLayoutToolContainer.addView(confirmationRow.getView()); matchedToolsList.add(confirmationRow); } addToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolConfirmationRow row : matchedToolsList) { if (row.isChecked()) { ToolEntry newTool = row.getToolEntry(); user.getToolLog().addTool(newTool, newTool.getSetupDateTime().substring(0, 10)); ToolLogRow newRow = new ToolLogRow(v.getContext(), newTool, utilityOnClickListeners.getToolEntryEditDialogOnClickListener( getActivity(), getFragmentManager(), mGpsLocationTracker, newTool, user)); row.getView().setTag(newTool.getToolId()); toolContainer.addView(newRow.getView()); } } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog)); dialog.show(); } if (unconfirmedRemovedTools.size() > 0) { final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); infoTextView.setText(R.string.removed_tools_information_text); archiveToolsButton.setText(R.string.ok); cancelButton.setVisibility(View.GONE); for (ToolEntry removedEntry : unconfirmedRemovedTools) { ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null); removedToolRow.setToolNotificationImageViewVisibility(false); removedToolRow.setEditToolImageViewVisibility(false); linearLayoutToolContainer.addView(removedToolRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry removedEntry : unconfirmedRemovedTools) { removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); for (int i = 0; i < toolContainer.getChildCount(); i++) { if (removedEntry.getToolId() .equals(toolContainer.getChildAt(i).getTag().toString())) { toolContainer.removeViewAt(i); break; } } } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); dialog.show(); } if (synchedTools.size() > 0) { final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); infoTextView.setText(R.string.unexpected_tool_removal_info_text); archiveToolsButton.setText(R.string.archive); for (ToolEntry removedEntry : synchedTools) { ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null); removedToolRow.setToolNotificationImageViewVisibility(false); removedToolRow.setEditToolImageViewVisibility(false); linearLayoutToolContainer.addView(removedToolRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry removedEntry : synchedTools) { removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); for (int i = 0; i < toolContainer.getChildCount(); i++) { if (removedEntry.getToolId() .equals(toolContainer.getChildAt(i).getTag().toString())) { toolContainer.removeViewAt(i); break; } } } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog)); dialog.show(); } if (unconfirmedRemovedTools.size() > 0) { // TODO: If not found server side, tool is assumed to be removed. Inform user. final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.reported_tools_removed_title); TextView informationTextView = (TextView) dialog .findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); informationTextView.setText(getString(R.string.removed_tools_information_text)); cancelButton.setVisibility(View.GONE); archiveToolsButton.setText(getString(R.string.ok)); for (ToolEntry toolEntry : unconfirmedRemovedTools) { ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry); linearLayoutToolContainer.addView(confirmationRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry toolEntry : unconfirmedRemovedTools) { toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); dialog.show(); } if (synchedTools.size() > 0) { // // TODO: Prompt user: Tool was confirmed, now is no longer at BW, remove or archive? final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); TextView informationTextView = (TextView) dialog .findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); informationTextView.setText(getString(R.string.unexpected_tool_removal_info_text)); archiveToolsButton.setText(getString(R.string.ok)); for (ToolEntry toolEntry : synchedTools) { ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry); linearLayoutToolContainer.addView(confirmationRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry toolEntry : synchedTools) { toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog)); dialog.show(); } user.writeToSharedPref(getActivity()); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }
From source file:org.exoplatform.calendar.webui.popup.UIEventForm.java
protected boolean isEventDetailValid(CalendarSetting calendarSetting) throws Exception { String dateFormat = calendarSetting.getDateFormat(); String timeFormat = calendarSetting.getTimeFormat(); Date from = null; Date to = null;/*from w w w.j a va 2 s . co m*/ if (CalendarUtils.isEmpty(getCalendarId())) { errorMsg_ = getId() + ".msg.event-calendar-required"; return false; } if (CalendarUtils.isEmpty(getEventCategory())) { errorMsg_ = getId() + ".msg.event-category-required"; return false; } if (CalendarUtils.isEmpty(getEventFormDateValue())) { errorMsg_ = getId() + ".msg.event-fromdate-required"; return false; } if (CalendarUtils.isEmpty(getEventToDateValue())) { errorMsg_ = getId() + ".msg.event-todate-required"; return false; } try { from = getEventFromDate(dateFormat, timeFormat); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Faile to get event from date", e); } errorMsg_ = getId() + ".msg.event-fromdate-notvalid"; return false; } if (from == null) { errorMsg_ = getId() + ".msg.event-fromdate-notvalid"; return false; } try { to = getEventToDate(dateFormat, timeFormat); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Fail to get event to date", e); } errorMsg_ = getId() + ".msg.event-fromdate-notvalid"; return false; } if (to == null) { errorMsg_ = getId() + ".msg.event-fromdate-notvalid"; return false; } if (from.after(to) || from.equals(to)) { errorMsg_ = "UIEventForm.msg.event-date-time-logic"; return false; } errorMsg_ = null; return true; }
From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java
private void resolveLogConflicts(List wgLogs, List conflictLogs) { // Reverse the sort order so we have the maximum logtimes at the beginning Collections.reverse(conflictLogs); // Get the operations having the maximum logtime WGUpdateLog maxUpdateLog = null;/*from w w w . j a va 2s . c om*/ WGUpdateLog maxDeletionLog = null; Iterator logsIt = conflictLogs.iterator(); Date maxDate = null; while (logsIt.hasNext()) { WGUpdateLog log = (WGUpdateLog) logsIt.next(); if (maxDate == null) { maxDate = log.getDate(); } else if (!maxDate.equals(log.getDate())) { break; } if (log.getType() == WGUpdateLog.TYPE_UPDATE) { maxUpdateLog = log; } else if (log.getType() == WGUpdateLog.TYPE_DELETE) { maxDeletionLog = log; } } // Now lets see what we have - If there is only one type of log we have no problem if (maxDeletionLog != null && maxUpdateLog == null) { } else if (maxUpdateLog != null && maxDeletionLog == null) { } else if (maxUpdateLog != null && maxDeletionLog != null) { // So we have an update and a deletion at the same time. // We cannot determine by log which was before the other. // Therefor we look if the document exists. // If so we use the update log, else the deletion log. // The nonused log is therefor removed from the log list WGDocument doc = null; WGDocumentKey documentKey = new WGDocumentKey(maxUpdateLog.getDocumentKey()); if (documentKey.isRealDocumentKey()) { try { doc = _db.getDocumentByKey(documentKey); if (doc != null && !doc.isDeleted()) { WGFactory.getLogger().info("Resolving log conflict about document " + maxUpdateLog.getDocumentKey() + ": Relevant log type determined as update"); wgLogs.remove(maxDeletionLog); } else { WGFactory.getLogger().info("Resolving log conflict about document " + maxUpdateLog.getDocumentKey() + ": Relevant log type determined as deletion"); wgLogs.remove(maxUpdateLog); } } catch (WGAPIException e) { WGFactory.getLogger().error( "Exception resolving log conflict for document " + maxUpdateLog.getDocumentKey(), e); } } } }
From source file:org.etudes.jforum.view.admin.SpecialAccessAction.java
/** * Add new special access to forum with group * @param forum//from ww w . ja va 2 s . com * @throws Exception */ protected void addForumGroupSpecialAccess(Forum forum) throws Exception { SpecialAccess specialAccess = new SpecialAccess(); specialAccess.setForumId(forum.getId()); String groupId = this.request.getParameter("group_id"); if ((groupId == null) || (groupId.trim().length() == 0)) { this.showForumList(); return; } // start/visible date String startDateParam = this.request.getParameter("startdate_" + groupId); if (startDateParam != null && startDateParam.trim().length() > 0) { Date startDate; try { startDate = DateUtil.getDateFromString(startDateParam.trim()); specialAccess.setStartDate(startDate); SimpleDateFormat df = new SimpleDateFormat( SakaiSystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT)); specialAccess.setStartDateFormatted(df.format(startDate)); // check with forum dates if (forum.getStartDate() == null) { specialAccess.setOverrideStartDate(true); } else if (startDate.equals(forum.getStartDate())) { specialAccess.setOverrideStartDate(false); specialAccess.setStartDate(null); } else { specialAccess.setOverrideStartDate(true); } } catch (ParseException e) { this.context.put("errorMessage", I18n.getMessage("Forums.Forum.DateParseError")); this.insertForum(); return; } } else { specialAccess.setStartDate(null); if (forum.getStartDate() != null) { specialAccess.setOverrideStartDate(true); } } // due date String endDateParam = this.request.getParameter("enddate_" + groupId); if (endDateParam != null && endDateParam.trim().length() > 0) { Date endDate; try { endDate = DateUtil.getDateFromString(endDateParam.trim()); specialAccess.setEndDate(endDate); SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT)); specialAccess.setEndDateFormatted(df.format(endDate)); // lock on due String lockOnDue = this.request.getParameter("lock_on_due"); // check with forum dates if (forum.getEndDate() == null) { specialAccess.setOverrideEndDate(true); specialAccess.setOverrideLockEndDate(true); if (lockOnDue != null && "1".equals(lockOnDue)) { specialAccess.setLockOnEndDate(true); } else { specialAccess.setLockOnEndDate(false); } } else { if (endDate.equals(forum.getEndDate())) { specialAccess.setEndDate(null); specialAccess.setOverrideEndDate(false); } else { specialAccess.setOverrideEndDate(true); } // lock on due if (specialAccess.isOverrideEndDate()) { /*ignore lock on due setting of forum*/ specialAccess.setOverrideLockEndDate(true); if (lockOnDue != null && "1".equals(lockOnDue)) { specialAccess.setLockOnEndDate(true); } else { specialAccess.setLockOnEndDate(false); } } else { /*consider lock on due setting of forum and override if not selected for special access*/ if (forum.isLockForum()) { if (lockOnDue != null && "1".equals(lockOnDue)) { specialAccess.setLockOnEndDate(false); specialAccess.setOverrideLockEndDate(false); } else { specialAccess.setLockOnEndDate(false); specialAccess.setOverrideLockEndDate(true); } } else { if (lockOnDue != null && "1".equals(lockOnDue)) { specialAccess.setLockOnEndDate(true); specialAccess.setOverrideLockEndDate(true); } else { specialAccess.setLockOnEndDate(false); specialAccess.setOverrideLockEndDate(false); } } } } } catch (ParseException e) { this.context.put("errorMessage", I18n.getMessage("Forums.Forum.DateParseError")); this.insertForum(); return; } } else { /*no special access end date*/ specialAccess.setEndDate(null); if (forum.getEndDate() != null) { specialAccess.setOverrideEndDate(true); specialAccess.setOverrideLockEndDate(true); specialAccess.setLockOnEndDate(false); } else { specialAccess.setOverrideEndDate(false); specialAccess.setOverrideLockEndDate(false); specialAccess.setLockOnEndDate(false); } } List<Integer> users = new ArrayList<Integer>(); String userIds[] = (String[]) this.request.getObjectParameter("toUsername" + "ParamValues"); if (userIds != null) { for (int i = 0; i < userIds.length; i++) { if (userIds[i] != null && userIds[i].trim().length() > 0) { int userId; try { userId = Integer.parseInt(userIds[i]); users.add(new Integer(userId)); } catch (NumberFormatException e) { if (logger.isWarnEnabled()) logger.warn(this.getClass().getName() + ".addForumGroupSpecialAccess() : Error while parsing the userId.", e); } } } } else { try { int userId = Integer.parseInt(this.request.getParameter("toUsername")); users.add(new Integer(userId)); } catch (NumberFormatException e) { if (logger.isWarnEnabled()) logger.warn(this.getClass().getName() + ".addForumGroupSpecialAccess() : Error while parsing the userId.", e); } } specialAccess.setUserIds(users); // delete any existing special access for the selected users List<SpecialAccess> categorySpecialAccessList = DataAccessDriver.getInstance().newSpecialAccessDAO() .selectByForumId(forum.getId()); for (SpecialAccess exiSpecialAccess : categorySpecialAccessList) { List<Integer> exisUserIds = exiSpecialAccess.getUserIds(); if (exisUserIds.removeAll(users)) { if (exisUserIds.size() > 0) { exiSpecialAccess.setUserIds(exisUserIds); DataAccessDriver.getInstance().newSpecialAccessDAO().update(exiSpecialAccess); } else { DataAccessDriver.getInstance().newSpecialAccessDAO().delete(exiSpecialAccess.getId()); } } } if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideLockEndDate())) && (users.size() > 0)) { DataAccessDriver.getInstance().newSpecialAccessDAO().addNew(specialAccess); } }