List of usage examples for java.util Date before
public boolean before(Date when)
From source file:com.relecotech.common.controller.AcceptParameterController.java
@RequestMapping(value = "/{name}", method = RequestMethod.GET) //public String getMovie(@PathVariable String name, ModelMap model) { public @ResponseBody ModelAndView getParameter(@PathVariable String name) throws ParserConfigurationException { //String param =name; try {/*from www .j av a2 s . c om*/ Map<String, String> valueMap = new HashMap<String, String>(); String[] data = name.split("&"); for (String str : data) { String[] mapPair = str.split("="); valueMap.put(mapPair[0], mapPair[1]); } String logoutUrl = "https://" + valueMap.get("URL") + ".com"; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); SAMLCredential credential = (SAMLCredential) authentication.getCredentials(); TimeZone timeZone = TimeZone.getTimeZone(valueMap.get("timeZone").replace("*", "/")); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm a"); dateFormat.setTimeZone(timeZone); Calendar calobj = Calendar.getInstance(timeZone); String SystemCurrentTime = dateFormat.format(calobj.getTime()); Date SystemCurrentDateTime = dateFormat.parse(SystemCurrentTime); // Date SystemCurrentDateTime = calobj.getTime(); //SFDC Meeting DATE/TIME String sfdcMeetingTime = valueMap.get("d").replace("*", "/"); System.out.println("sfdcMeetingTime=" + sfdcMeetingTime); Date sfdcMeetingDateTime = dateFormat.parse(sfdcMeetingTime); //TIME Before Meeting can satarted Date sfdcMeetingBeforeDateTime = dateFormat .parse(AddSubtractTime.getSubtractedTime(sfdcMeetingTime, timeZone)); //TIME after Meeting cannot be satarted Date sfdcMeetingAfterDateTime = dateFormat .parse(AddSubtractTime.getAddedTime(sfdcMeetingTime, timeZone)); System.out.println("SystemCurrentDateTime=" + SystemCurrentDateTime); System.out.println("sfdcMeetingDateTime=" + sfdcMeetingDateTime); System.out.println("sfdcMeetingAfterDateTime=" + sfdcMeetingAfterDateTime); System.out.println("sfdcMeetingBeforeDateTime=" + sfdcMeetingBeforeDateTime); if (SystemCurrentDateTime.after(sfdcMeetingBeforeDateTime) && SystemCurrentDateTime.before(sfdcMeetingAfterDateTime)) { APIGenerator aPIGenerator = new APIGenerator(); System.out.println("converted id=" + SalesforceIDConverter.convertID(valueMap.get("code"))); System.out.println((credential.getAttributeAsString("ContactId"))); if (valueMap.get("code") .matches(SalesforceIDConverter.convertID(credential.getAttributeAsString("ContactId")))) { System.out.println("valuemap=" + valueMap); System.out.println("logout url=" + logoutUrl); String create = "attendeePW=ap" + "&meetingID=" + valueMap.get("name") + "&moderatorPW=newuser" + "&name=" + valueMap.get("name") + "&logoutURL=" + logoutUrl; System.out.println("create parameter=" + create); XmlParser.runAPI(aPIGenerator.createAPI("create", create)); // String join = "fullName=" + valueMap.get("fullName") + "&meetingID=" + valueMap.get("meetingID") + "&password=newuser"; String join = "fullName=" + credential.getAttributeAsString("username") + "&meetingID=" + valueMap.get("name") + "&password=newuser"; System.out.println("joinparam=" + join); aPIGenerator.createAPI("join", join); return new ModelAndView("redirect:" + aPIGenerator.apiWithChecksum); } else { Map<String, String> responceMap = XmlParser.runAPI( aPIGenerator.createAPI("isMeetingRunning", "meetingID=" + valueMap.get("name"))); String join = "fullName=" + credential.getAttributeAsString("username") + "&meetingID=" + valueMap.get("name") + "&password=ap"; if (responceMap.get("running").matches("true")) { aPIGenerator.createAPI("join", join); return new ModelAndView("redirect:" + aPIGenerator.apiWithChecksum); } else { String student = "<center> <h1>Wait! Presenter has not joined meeting yet!</h1>\n" // +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> " + " <h2>\n" + " Please try after few minutes.\n" + " \n" + "<br>Meeting Date/Time:" + dateFormat.format(sfdcMeetingDateTime) + "<br><a href=" + logoutUrl + ">Back</a>" + " </h2></center> "; // return new ModelAndView("redirect:" + "/student.jsp"); return new ModelAndView("student", "student", student); } } } else { // if (SystemCurrentDateTime.compareTo(sfdcMeetingDateTime) == -1) { String wait = "<center> <h1>Too Early for Meeting!</h1><br></center>\n" // +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> " + " <center> <h2>Meeting is not yet open.<br>\n" + " Please check meeting schedule time. \n<br>" + "<br>Meeting Date/Time:" + dateFormat.format(sfdcMeetingDateTime) + "</h2><h3>System Current Date/Time:" + dateFormat.format(SystemCurrentDateTime) + "<br>*Meeting will open 15 minutes before scheduled time</h3><a href=" + logoutUrl + ">Back</a>" + " </center> "; return new ModelAndView("wait", "wait", wait); } //for Past Date if (SystemCurrentDateTime.compareTo(sfdcMeetingDateTime) == 1) { String wait = "<center> <h1>Meeting is Over!</h1><br></center>\n" // +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> " + " <center> <h2>Meeting can not open.<br>\n" + " Meeting was scheduled on - \n<br>" + "<br>Meeting Date/Time:" + dateFormat.format(sfdcMeetingDateTime) + "</h2><h3><br>System Current Date/Time:" + dateFormat.format(SystemCurrentDateTime) + "<br><a href=" + logoutUrl + ">Back</a>" + " </h3> </center> "; return new ModelAndView("wait", "wait", wait); } // } } catch (Exception ex) { System.out.println("Exception=" + ex); } return null; }
From source file:com.aurel.track.exchange.track.importer.TrackImportBL.java
/** * add/upgrade of the workItem and the history * //from w ww . j a va 2 s .c o m * @param exchangeWorkItem * @param internalWorkItemBean * @param transactionUuidsForInternalWorkitem * @param dropDownMatcherMap */ private static int addUpgradeWorkItem(ExchangeWorkItem exchangeWorkItem, ReportBeanWithHistory reportBeanWithHistory, WorkItemContext workItemContext, Set<String> transactionUuidsForInternalWorkitem, Map<String, Map<Integer, Integer>> dropDownMatcherMap, List<String> externalWorkItemUuidsWithLink, List<String> externalTransactionUuidsWithLink, Map<Integer, String> externalWorkItemNrToInternalWkItemNr) throws ImportExceptionList { int result = NOSAVE; TWorkItemBean internalWorkItemBean = workItemContext.getWorkItemBean(); boolean isNew = true; if (internalWorkItemBean.getObjectID() != null) { isNew = false; } Map<Integer, Integer> fieldsMatcherMap = dropDownMatcherMap.get(ExchangeFieldNames.FIELD); /** * sets/updates the workItem actual values */ Map<String, Object> actualFieldValuesMap = exchangeWorkItem.getActualFieldValuesMap(); Integer externalWorkItemID = exchangeWorkItem.getWorkItemID(); String externalUUID = exchangeWorkItem.getUuid(); if (internalWorkItemBean.getUuid() == null) { // set the uuid of the internal workItem to the external workItem's // uuid (for new workItems) internalWorkItemBean.setUuid(externalUUID); } String strExteranalLastEditDate = (String) actualFieldValuesMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_LASTMODIFIEDDATE, null)); Date externalLastEdit = DateTimeUtils.getInstance().parseISODateTime(strExteranalLastEditDate); if (actualFieldValuesMap != null && externalIsMoreRecent(externalLastEdit, internalWorkItemBean.getLastEdit(), "workItem", externalWorkItemID)) { for (String externalKey : actualFieldValuesMap.keySet()) { Integer[] parts = MergeUtil.getParts(externalKey); Integer externalFieldID = parts[0]; Integer parameterCode = parts[1]; if (!SystemFields.INTEGER_ISSUENO.equals(externalFieldID) && !SystemFields.INTEGER_SUPERIORWORKITEM.equals(externalFieldID)) { // do not set the issueNo and parentNo values because they // will be different from the external values Integer internalFieldID; if (fieldsMatcherMap.get(externalFieldID) != null) { // replace the external fieldID with the internal // fieldID internalFieldID = fieldsMatcherMap.get(externalFieldID); } else { LOGGER.warn("No internal fieldID found for external fieldID " + externalFieldID + " and external workItem " + externalWorkItemID + ". The field cannot be saved"); continue; } // the issue number shouldn't be set! Object exchangeAttribut = actualFieldValuesMap.get(externalKey); // do not set the issue number (because it either exists or // will be generated) IFieldTypeRT internalFieldTypeRT = FieldTypeManager.getFieldTypeRT(internalFieldID, parameterCode); if (internalFieldTypeRT != null) { if (exchangeAttribut != null && (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION || internalFieldTypeRT.getValueType() == ValueType.SYSTEMOPTION)) { // lookup value String internalKey; if (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION) { // custom option: we do not differentiate by // fieldID_parameterCode between // the different custom option fields because if // a "not compatible" (assigned to naother list) // optionsettings is already present it will be // leaved as it is // but the options should be set to the imported // values independently of the optionsettings internalKey = ExchangeFieldNames.OPTION; } else { // system option internalKey = MergeUtil.mergeKey(internalFieldID, parameterCode); ILookup lookup = (ILookup) internalFieldTypeRT; Integer dropdownFieldKey = lookup.getDropDownMapFieldKey(internalFieldID); if (!dropdownFieldKey.equals(internalFieldID)) { internalKey = MergeUtil.mergeKey(dropdownFieldKey, parameterCode); } } Map<Integer, Integer> dropDownMap = dropDownMatcherMap.get(internalKey); if (dropDownMap != null) { Integer externalDropDown = null; if (internalFieldTypeRT.isMultipleValues()) { // custom select List<String> multipleValuesList = (List<String>) exchangeAttribut; Integer[] internalDropDownArr = null; if (multipleValuesList != null) { internalDropDownArr = new Integer[multipleValuesList.size()]; Iterator<String> itrMultiple = multipleValuesList.iterator(); int i = 0; while (itrMultiple.hasNext()) { String externalStringValue = itrMultiple.next(); Integer parsedExternalDropDownValue = (Integer) internalFieldTypeRT .parseISOValue(externalStringValue); Integer internalDropDownValue = dropDownMap .get(parsedExternalDropDownValue); internalDropDownArr[i++] = internalDropDownValue; } } exchangeAttribut = internalDropDownArr; } else { // system select externalDropDown = (Integer) internalFieldTypeRT .parseISOValue(exchangeAttribut); exchangeAttribut = dropDownMap.get(externalDropDown); } internalWorkItemBean.setAttribute(internalFieldID, parameterCode, exchangeAttribut); } } else { // direct value internalWorkItemBean.setAttribute(internalFieldID, parameterCode, internalFieldTypeRT.parseISOValue(exchangeAttribut)); if (internalFieldTypeRT.getValueType() == ValueType.LONGTEXT) { String longText = (String) exchangeAttribut; if (longText != null) { List<Integer> issueIDsInNew = TagReplacer .gatherIssueLinks(new StringBuilder(longText)); // if the description contains issue links // the workItem should be post-processed // later // now it contains the wrong (external) // issue links // mark it as post processing needed if (!issueIDsInNew.isEmpty()) { externalWorkItemUuidsWithLink.add(externalUUID); } } } } } } else { if (SystemFields.INTEGER_SUPERIORWORKITEM.equals(externalFieldID)) { // if the parentID is specified the workItem should be // post-processed later // the external parentID is not set at all because by // saving the // issue it could cause foreign key problems // mark it as post processing needed Object exchangeAttribut = actualFieldValuesMap.get(externalKey); if (exchangeAttribut != null) { externalWorkItemUuidsWithLink.add(externalUUID); } } } } List<ErrorData> workItemErrorList = new ArrayList<ErrorData>(); if (isNew) { addOldValueAsCustomAttribute(workItemContext, externalWorkItemID.toString()); } boolean saveNeeded = FieldsManagerRT.performSave(workItemContext, workItemErrorList, false, false/*, false*/); if (workItemErrorList.isEmpty()) { if (saveNeeded) { LOGGER.info("WorkItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemBean.getObjectID() + " was " + (isNew ? "created" : "updated")); if (isNew) { result = CREATED; externalWorkItemNrToInternalWkItemNr.put(internalWorkItemBean.getObjectID(), externalWorkItemID + "," + internalWorkItemBean.getSynopsis()); } else { result = UPGRADED; } } } else { ImportExceptionList importExceptionList = new ImportExceptionList(); importExceptionList.setErrorDataList(workItemErrorList); throw importExceptionList; } } // add the workItemIDs to the matcherMap Integer internalWorkItemID = internalWorkItemBean.getObjectID(); if (internalWorkItemID == null) { return result; } Map<Integer, Integer> workItemIDsMatcherMap = dropDownMatcherMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_ISSUENO, null)); workItemIDsMatcherMap.put(externalWorkItemID, internalWorkItemID); Map<Integer, Integer> personMap = dropDownMatcherMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_PERSON, null)); /** * add history values */ Set<Integer> pseudoHistoryFields = HistoryLoaderBL.getPseudoHistoryFields(); List<ExchangeHistoryTransactionEntry> historyValuesList = exchangeWorkItem.getHistoryValues(); if (historyValuesList != null) { for (ExchangeHistoryTransactionEntry exchangeHistoryTransactionEntry : historyValuesList) { String externalTransactionUuid = exchangeHistoryTransactionEntry.getUuid(); String strChangedAt = exchangeHistoryTransactionEntry.getChangedAt(); Date changedAt = null; if (strChangedAt != null) { changedAt = DateTimeUtils.getInstance().parseISODateTime(strChangedAt); } List<ExchangeHistoryFieldEntry> externalFieldChanges = exchangeHistoryTransactionEntry .getHistoryFieldChanges(); if (externalFieldChanges != null) { if (transactionUuidsForInternalWorkitem != null && transactionUuidsForInternalWorkitem.contains(externalTransactionUuid)) { // found external and internal transaction with the same // uuid: // the only possible modification is by the comment // in the reportBeanWithHistory only the comments are // loaded for (ExchangeHistoryFieldEntry exchangeHistoryFieldEntry : externalFieldChanges) { Integer fieldID = new Integer(exchangeHistoryFieldEntry.getFieldID()); if (fieldID.equals(SystemFields.INTEGER_COMMENT)) { List<HistoryValues> internalComments = reportBeanWithHistory.getComments(); if (internalComments != null) { Iterator<HistoryValues> itrInternalComments = internalComments.iterator(); while (itrInternalComments.hasNext()) { HistoryValues historyValues = itrInternalComments.next(); if (historyValues != null) { String internalComment = historyValues.getNewShowValue(); Integer internalTimesEdited = historyValues.getTimesEdited(); String internalTransactionUUID = historyValues.getTransactionUuid(); if (externalTransactionUuid.equals(internalTransactionUUID)) { String externalComment = exchangeHistoryFieldEntry .getNewStringValue(); String strExternalTimesEdited = exchangeHistoryFieldEntry .getTimesEdited(); Integer externalTimesEdited = null; if (strExternalTimesEdited != null) { externalTimesEdited = new Integer(strExternalTimesEdited); } if (EqualUtils.notEqual(internalComment, externalComment) && externalTimesEdited != null && (internalTimesEdited == null || externalTimesEdited .intValue() > internalTimesEdited.intValue())) { try { HistoryDAOUtils.updateFieldChange( FieldChangeBL.loadByPrimaryKey( historyValues.getObjectID()), externalComment, ValueType.LONGTEXT); } catch (ItemPersisterException e) { LOGGER.warn( "Updating the comment for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID + ", historyTransactionID " + internalTransactionUUID + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } LOGGER.info("Comment modified for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID); if (externalComment != null) { List<Integer> issueIDsInComment = TagReplacer .gatherIssueLinks( new StringBuilder(externalComment)); if (!issueIDsInComment.isEmpty()) { // remember the // transactionUUID // for the comment externalTransactionUuidsWithLink .add(externalTransactionUuid); } } } } } } } } } } else { // the external transaction uuid is not found in the // internal history Integer externalPerson = new Integer(exchangeHistoryTransactionEntry.getChangedBy()); Integer historyTransactionID = HistoryTransactionBL.saveHistoryTransaction( internalWorkItemID, personMap.get(externalPerson), changedAt, externalTransactionUuid); if (historyTransactionID != null) { for (ExchangeHistoryFieldEntry exchangeHistoryFieldEntry : externalFieldChanges) { Integer externalFieldID = new Integer(exchangeHistoryFieldEntry.getFieldID()); Integer internalFieldID; if (fieldsMatcherMap.get(externalFieldID) != null) { // replace the external fieldID with the // internal fieldID for the custom fields internalFieldID = fieldsMatcherMap.get(externalFieldID); } else { // for the system fields the internal and // external fieldIDs are the same and does // not appear in this map internalFieldID = externalFieldID; } Integer parameterCode = null; if (exchangeHistoryFieldEntry.getParameterCode() != null) { parameterCode = new Integer(exchangeHistoryFieldEntry.getParameterCode()); } IFieldTypeRT internalFieldTypeRT = null; if (pseudoHistoryFields.contains(internalFieldID)) { internalFieldTypeRT = FieldTypeManager .getFieldTypeRT(SystemFields.INTEGER_DESCRIPTION, null); } else { internalFieldTypeRT = FieldTypeManager.getFieldTypeRT(internalFieldID, parameterCode); } if (internalFieldTypeRT != null) { String newStringValue = exchangeHistoryFieldEntry.getNewStringValue(); Object newValue = internalFieldTypeRT.parseISOValue(newStringValue); String oldStringValue = exchangeHistoryFieldEntry.getOldStringValue(); Object oldValue = internalFieldTypeRT.parseISOValue(oldStringValue); if (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION || (internalFieldTypeRT.getValueType() == ValueType.SYSTEMOPTION && !SystemFields.INTEGER_SUPERIORWORKITEM .equals(externalFieldID))) { // exclude the parent item because it // will be set at the end String internalKey; if (internalFieldTypeRT.getValueType() == ValueType.CUSTOMOPTION) { // custom option: we do not // differentiate by // fieldID_parameterCode between // the different custom option // fields because if a // "not compatible" (assigned to // naother list) // optionsettings is already present // it will be leaved as it is // but the options should be set to // the imported values independently // of the optionsettings internalKey = ExchangeFieldNames.OPTION; } else { /* * if * (SystemFields.INTEGER_ISSUENO.equals * (externalFieldID) || * SystemFields. * INTEGER_SUPERIORWORKITEM * .equals(externalFieldID)) { * //superior workitem explicit * history: //TODO it does not work * if the parent is not yet added in * the dropDownMatcherMap * internalKey = * MergeUtil.mergeKey(SystemFields * .INTEGER_ISSUENO, parameterCode); * } else { */ // system option internalKey = MergeUtil.mergeKey(internalFieldID, parameterCode); ILookup lookup = (ILookup) internalFieldTypeRT; Integer dropdownFieldKey = lookup .getDropDownMapFieldKey(internalFieldID); if (!dropdownFieldKey.equals(internalFieldID)) { internalKey = MergeUtil.mergeKey(dropdownFieldKey, parameterCode); } // } } // the history values are always stored // one by one (no multiple values as in // actual values) Map<Integer, Integer> dropDownMap = dropDownMatcherMap.get(internalKey); if (dropDownMap != null) { newValue = dropDownMap.get(newValue); oldValue = dropDownMap.get(oldValue); } } // save the fieldChange try { HistoryDAOUtils.insertFieldChange(internalFieldID, parameterCode, historyTransactionID, newValue, oldValue, internalFieldTypeRT.getValueType(), internalFieldTypeRT.getSystemOptionType()); } catch (ItemPersisterException e) { LOGGER.warn("Inserting the fieldChange for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID + " for field " + internalFieldID + ", historyTransactionID " + historyTransactionID + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } LOGGER.debug("History added for workItem externalWorkItemID " + externalWorkItemID + " and internalWorkItemID " + internalWorkItemID + " and field " + internalFieldID); // remember the transactionUUIDs for the // descriptions/comments/common // history/other long texts // which contain issueIDs because they // should be replaced later if (internalFieldTypeRT.getValueType() == ValueType.LONGTEXT) { if (newStringValue != null) { List<Integer> issueIDsInNew = TagReplacer .gatherIssueLinks(new StringBuilder(newStringValue)); if (!issueIDsInNew.isEmpty()) { externalTransactionUuidsWithLink.add(externalTransactionUuid); } else { if (oldStringValue != null) { List<Integer> issueIDsInOld = TagReplacer .gatherIssueLinks(new StringBuilder(oldStringValue)); if (!issueIDsInOld.isEmpty()) { externalTransactionUuidsWithLink .add(externalTransactionUuid); } } } } } else { // explicit history for parent // remember the transactionUUIDs with // parentIDs because they should be // replaced later // now the wrong (external) value is // saved but it does not cause foreign // key problems because // the system fields from history are // not linked with foreign keys if (SystemFields.INTEGER_SUPERIORWORKITEM.equals(externalFieldID)) { if (newValue != null) { externalTransactionUuidsWithLink.add(externalTransactionUuid); } } } } } } } } } } /** * add consultants/informants */ addRaciRole(exchangeWorkItem.getConsultedList(), reportBeanWithHistory.getConsultedList(), internalWorkItemID, RaciRole.CONSULTANT, personMap); addRaciRole(exchangeWorkItem.getInformedList(), reportBeanWithHistory.getInformedList(), internalWorkItemID, RaciRole.INFORMANT, personMap); /** * add budget values */ List<TBudgetBean> externalBudgetBeanList = exchangeWorkItem.getBudgetBeanList(); List<TBudgetBean> internalBudgetBeanList = reportBeanWithHistory.getBudgetHistory(); Map<String, TBudgetBean> internalBudgetBeanMap = new HashMap<String, TBudgetBean>(); if (externalBudgetBeanList != null) { Date lastBudget = null; if (internalBudgetBeanList != null) { for (TBudgetBean budgetBean : internalBudgetBeanList) { if (lastBudget == null || lastBudget.before(budgetBean.getLastEdit())) { lastBudget = budgetBean.getLastEdit(); } internalBudgetBeanMap.put(budgetBean.getUuid(), budgetBean); } } for (TBudgetBean externalBudgetBean : externalBudgetBeanList) { String uuid = externalBudgetBean.getUuid(); TBudgetBean internalBudgetBean = internalBudgetBeanMap.get(uuid); if (internalBudgetBean == null) { // it is a new object externalBudgetBean.setObjectID(null); externalBudgetBean.saveBean(externalBudgetBean, dropDownMatcherMap); LOGGER.info("Budget added"); if (externalIsMoreRecent(externalBudgetBean.getLastEdit(), lastBudget, "budget", externalBudgetBean.getObjectID())) { lastBudget = externalBudgetBean.getLastEdit(); // actualize the computed values table if more recent ComputedValueBL.computeBudgetOrPlan(externalBudgetBean); LOGGER.info("Budget recomputed"); } } } } /** * add plan values */ List<TBudgetBean> externalPlanBeanList = exchangeWorkItem.getPlannedValueBeanList(); List<TBudgetBean> internalPlanBeanList = reportBeanWithHistory.getPlannedValueHistory(); Map<String, TBudgetBean> internalPlanBeanMap = new HashMap<String, TBudgetBean>(); if (externalPlanBeanList != null) { Date lastBudget = null; if (internalPlanBeanList != null) { for (TBudgetBean budgetBean : internalPlanBeanList) { if (lastBudget == null || lastBudget.before(budgetBean.getLastEdit())) { lastBudget = budgetBean.getLastEdit(); } internalPlanBeanMap.put(budgetBean.getUuid(), budgetBean); } } for (TBudgetBean externalBudgetBean : externalPlanBeanList) { String uuid = externalBudgetBean.getUuid(); TBudgetBean internalBudgetBean = internalPlanBeanMap.get(uuid); if (internalBudgetBean == null) { // it is a new object externalBudgetBean.setObjectID(null); externalBudgetBean.saveBean(externalBudgetBean, dropDownMatcherMap); LOGGER.info("Plan added"); if (externalIsMoreRecent(externalBudgetBean.getLastEdit(), lastBudget, "plan", externalBudgetBean.getObjectID())) { lastBudget = externalBudgetBean.getLastEdit(); // actualize the computed values table if more recent ComputedValueBL.computeBudgetOrPlan(externalBudgetBean); LOGGER.info("Plan recomputed"); } } } } /** * add/modify remaining budget */ TActualEstimatedBudgetBean externalRemainingBudget = exchangeWorkItem.getActualEstimatedBudgetBean(); TActualEstimatedBudgetBean internalRemainingBudget = reportBeanWithHistory.getActualEstimatedBudgetBean(); if (externalRemainingBudget != null) { if (internalRemainingBudget == null) { // it is a new object externalRemainingBudget.setObjectID(null); externalRemainingBudget.saveBean(externalRemainingBudget, dropDownMatcherMap); LOGGER.info("Remaining budget added"); } else { // remaining budget found if (externalIsMoreRecent(externalRemainingBudget.getLastEdit(), internalRemainingBudget.getLastEdit(), "remaining budget", externalRemainingBudget.getObjectID())) { externalRemainingBudget.replaceLookup(dropDownMatcherMap); if (externalRemainingBudget.hasChanged(internalRemainingBudget)) { // modify if changed externalRemainingBudget.copy(internalRemainingBudget); RemainingPlanBL.save(internalRemainingBudget); LOGGER.info("Remaining budget modified"); } } } } /** * add/modify cost values */ List<TCostBean> externalCostBeanList = exchangeWorkItem.getExpenseBeanList(); List<TCostBean> internalCostBeanList = reportBeanWithHistory.getCosts(); Map<String, ISerializableLabelBean> internalCostBeanMap = new HashMap<String, ISerializableLabelBean>(); if (externalCostBeanList != null) { if (internalCostBeanList != null) { internalCostBeanMap = GeneralUtils.createUUIDMapFromSerializableBean((List) internalCostBeanList); } Iterator<TCostBean> itrExternalCostBeans = externalCostBeanList.iterator(); while (itrExternalCostBeans.hasNext()) { TCostBean externalCostBean = itrExternalCostBeans.next(); String uuid = externalCostBean.getUuid(); TCostBean internalCostBean = (TCostBean) internalCostBeanMap.get(uuid); if (internalCostBean == null) { // it is a new object externalCostBean.setObjectID(null); externalCostBean.saveBean(externalCostBean, dropDownMatcherMap); // TODO do not recompute always but only the last for each // person ComputedValueBL.computeExpenses(externalCostBean.getWorkitem(), externalCostBean.getPerson()); LOGGER.info("Expense added and recomputed"); } else { // cost found if (externalIsMoreRecent(externalCostBean.getLastEdit(), internalCostBean.getLastEdit(), "expense", externalCostBean.getObjectID())) { externalCostBean.replaceLookup(dropDownMatcherMap); if (externalCostBean.hasChanged(internalCostBean)) { // modify if changed externalCostBean.copy(internalCostBean); ExpenseBL.saveCostBean(internalCostBean); // TODO do not recompute always but only the last // for each person ComputedValueBL.computeExpenses(internalCostBean.getWorkitem(), internalCostBean.getPerson()); LOGGER.info("Expense modified and recomputed"); } } } } } /** * add/modify the attachments */ List<TAttachmentBean> externalAttachmentBeanList = exchangeWorkItem.getAttachmentBeanList(); List<TAttachmentBean> internalAttachmentBeanList = reportBeanWithHistory.getAttachments(); if (externalAttachmentBeanList != null) { Map<String, ISerializableLabelBean> internalAttachmentBeanMap = new HashMap<String, ISerializableLabelBean>(); if (internalAttachmentBeanList != null) { internalAttachmentBeanMap = GeneralUtils .createUUIDMapFromSerializableBean((List) internalAttachmentBeanList); } Iterator<TAttachmentBean> itrExternalAttachmentBeans = externalAttachmentBeanList.iterator(); while (itrExternalAttachmentBeans.hasNext()) { TAttachmentBean externalAttachmentBean = itrExternalAttachmentBeans.next(); String uuid = externalAttachmentBean.getUuid(); TAttachmentBean internalAttachmentBean = (TAttachmentBean) internalAttachmentBeanMap.get(uuid); boolean foundMatch = false; if (internalAttachmentBean == null) { // not found by uuid, try by considerAsSame if (internalAttachmentBeanList != null) { Iterator<TAttachmentBean> tAttachmentBean = internalAttachmentBeanList.iterator(); while (tAttachmentBean.hasNext()) { internalAttachmentBean = tAttachmentBean.next(); if (externalAttachmentBean.considerAsSame(internalAttachmentBean, dropDownMatcherMap)) { foundMatch = true; break; } } } } else { foundMatch = true; } if (foundMatch) { // attachment found if (internalAttachmentBean != null && externalIsMoreRecent(externalAttachmentBean.getLastEdit(), internalAttachmentBean.getLastEdit(), "attachment", externalAttachmentBean.getObjectID())) { if (externalAttachmentBean.hasChanged(internalAttachmentBean)) { internalAttachmentBean.setDescription(externalAttachmentBean.getDescription()); internalAttachmentBean.setLastEdit(externalAttachmentBean.getLastEdit()); AttachBL.save(internalAttachmentBean); LOGGER.info("Attachment description modified: " + externalAttachmentBean.getFileName()); } } } else { // new attachment Integer internalAttachmentNo; Integer externalAttachmentNo = externalAttachmentBean.getObjectID(); externalAttachmentBean.setObjectID(null); internalAttachmentNo = externalAttachmentBean.saveBean(externalAttachmentBean, dropDownMatcherMap); LOGGER.info("Attachment added: " + externalAttachmentBean.getFileName()); String attachmentsPath = AttachBL.getAttachDirBase(); String tempDirectoryPath = attachmentsPath + File.separator + AttachBL.tmpAttachments; String workItemAttachmentPath = attachmentsPath + File.separator + internalWorkItemID; // add also the files File attachmentFile = new File(tempDirectoryPath, AttachBL.getFileNameAttachment(externalAttachmentNo, externalWorkItemID)); // parent directory File workItemAttachmentFile = new File(workItemAttachmentPath); if (!workItemAttachmentFile.exists()) { workItemAttachmentFile.mkdirs(); } // Move file to new directory boolean success = attachmentFile.renameTo(new File(workItemAttachmentFile, AttachBL.getFileNameAttachment(internalAttachmentNo, externalWorkItemID))); if (!success) { LOGGER.error("Moving the file " + externalAttachmentBean.getFileName() + " failed"); } } } } return result; }
From source file:com.jaspersoft.jasperserver.api.engine.scheduling.ReportSchedulingFacade.java
public List<ReportJobSummary> getJobsByNextFireTime(ExecutionContext context, List<ReportJob> searchList, Date startNextTriggerFireDate, Date endNextTriggerFireDate, List<Byte> includeTriggerStates) { ////from w w w . j a v a 2 s . c o m // Review / todo: 2012-03-07 thorick: it may yield some benefit to have the underlying Hibernate // query exclude any jobs whose Calendar start and end dates // lie OUTSIDE of our nextTriggerFire time dates // // get the big list for starters p("getJobsByNextFireTime START"); List<ReportJobSummary> list = null; if (searchList != null && searchList.size() > 0) { list = persistenceService.listJobs(context, searchList); } else { p("about to do persistenceService.listJobs(context)"); // THORICK CATCH ANYTHING try { list = persistenceService.listJobs(context); p("DONE. about to do persistenceService.listJobs(context)"); } catch (Throwable th) { p("ERROR GOT THROWABLE " + th.getClass().getName() + " FROM persistenceService " + th.getMessage()); th.printStackTrace(); throw new RuntimeException(th); } } // apply filters record by record p("getJobsByNextFireTime List has " + list.size() + " candidate ReportJobSummary entries"); p("current time is " + new Date()); p("startDate=" + (startNextTriggerFireDate == null ? "NULL" : startNextTriggerFireDate.toString())); p("endDate=" + (endNextTriggerFireDate == null ? "NULL" : endNextTriggerFireDate.toString())); if (startNextTriggerFireDate == null && endNextTriggerFireDate == null && includeTriggerStates == null) return list; // prepare filtering setSummaryRuntimeInformation(context, list); List<ReportJobSummary> filteredList = new LinkedList<ReportJobSummary>(list); Iterator<ReportJobSummary> it = list.iterator(); while (it.hasNext()) { ReportJobSummary rjs = it.next(); //p("next ReportJobSummary "+rjs.getId()); ReportJobRuntimeInformation rjr = rjs.getRuntimeInformation(); if (rjr != null) { Date nextFireTime = rjr.getNextFireTime(); if (nextFireTime != null) { if (startNextTriggerFireDate != null) { //p("startDate="+startNextTriggerFireDate+", nextFireTime="+nextFireTime); if (nextFireTime.before(startNextTriggerFireDate)) { //p(rjs.getId()+" remove from list."); filteredList.remove(rjs); continue; } } if (endNextTriggerFireDate != null) { //p("endDate="+endNextTriggerFireDate+", nextFireTime="+nextFireTime); if (nextFireTime.after(endNextTriggerFireDate)) { //p(rjs.getId()+"remove from list."); filteredList.remove(rjs); continue; } } } if (includeTriggerStates != null && includeTriggerStates.size() > 0) { Byte triggerState = rjr.getStateCode(); //p("check TriggerStates state of this trigger == '"+triggerState+"'"); if (!includeTriggerStates.contains(triggerState)) { filteredList.remove(rjs); //p(rjs.getId()+"remove from list."); continue; } //p("trigger state OK, keep "+rjs.getId()+" in list."); } } } return filteredList; }
From source file:com.enonic.vertical.adminweb.handlers.xmlbuilders.ContentBaseXMLBuilder.java
public final String buildXML(ExtendedMap formItems, User user, boolean create, boolean excludeContendataXML, boolean usePersistedContendataXML) throws VerticalAdminException { boolean published = formItems.getBoolean("published", false); boolean sentToApproval = formItems.getBoolean("senttoapproval", false); boolean rejected = formItems.getBoolean("rejected", false); int categoryKey; if (formItems.containsKey("cat")) { categoryKey = formItems.getInt("cat"); } else {// w w w.j av a 2 s . com categoryKey = formItems.getInt("category_key"); } int unitKey = -1; if (formItems.containsKey("selectedunitkey")) { unitKey = formItems.getInt("selectedunitkey"); } else if (formItems.containsKey("unitkey")) { unitKey = formItems.getInt("unitkey"); } int contenttypekey = ContentBaseHandlerServlet.getContentTypeKey(formItems); Document doc = XMLTool.createDocument("content"); Element content = doc.getDocumentElement(); // General content attributes if (!create) { int key = formItems.getInt("key"); // @key content.setAttribute("key", String.valueOf(key)); // version/@key int versionKey = formItems.getInt("versionkey"); content.setAttribute("versionkey", String.valueOf(versionKey)); } // owner/@key if (!create && formItems.containsKey("_pubdata_owner")) { Element ownerElem = XMLTool.createElement(doc, content, "owner"); ownerElem.setAttribute("key", formItems.getString("_pubdata_owner")); } // assignee/@key if (formItems.containsKey(ASSIGNEE_FORMITEM_KEY)) { Element assigneeElem = XMLTool.createElement(doc, content, ASSIGNEE_XML_KEY); assigneeElem.setAttribute("key", formItems.getString(ASSIGNEE_FORMITEM_KEY)); } if (formItems.containsKey(ASSIGNER_FORMITEM_KEY)) { Element assignerElem = XMLTool.createElement(doc, content, ASSIGNER_XML_KEY); assignerElem.setAttribute("key", formItems.getString(ASSIGNER_FORMITEM_KEY)); } // DueDate buildDueDateElement(formItems, doc, content); // Comment if (formItems.containsKey(COMMENT_FORMITEM_KEY)) { XMLTool.createElement(doc, content, COMMENT_XML_KEY, formItems.getString(COMMENT_FORMITEM_KEY)); } // Assignment comment if (formItems.containsKey(ASSIGNMENT_DESCRIPTION_FORMITEM_KEY)) { XMLTool.createElement(doc, content, ASSIGNMENT_DESCRIPTION_XML_KEY, formItems.getString(ASSIGNMENT_DESCRIPTION_FORMITEM_KEY)); } // modifier/@key Element modifierElem = XMLTool.createElement(doc, content, "modifier"); modifierElem.setAttribute("key", String.valueOf(user.getKey())); if (unitKey >= 0) { content.setAttribute("unitkey", String.valueOf(unitKey)); } content.setAttribute("contenttypekey", String.valueOf(contenttypekey)); content.setAttribute("priority", formItems.getString("_pubdata_priority", "0")); // language int languageKey; if (formItems.containsKey("_pubdata_languagekey")) { languageKey = formItems.getInt("_pubdata_languagekey"); } else { languageKey = admin.getUnitLanguageKey(unitKey); } content.setAttribute("languagekey", String.valueOf(languageKey)); // status int status = formItems.getInt("_pubdata_status", 0); if (rejected) { status = 0; } else if (sentToApproval) { status = 1; } else if (published) { status = 2; } content.setAttribute("status", String.valueOf(status)); try { // record the publish dates if set Date publishFrom = null; Date publishTo = null; Date now = new Date(); if (formItems.containsKey("date_pubdata_publishfrom")) { StringBuffer date = new StringBuffer(formItems.getString("date_pubdata_publishfrom")); date.append(' '); date.append(formItems.getString("time_pubdata_publishfrom", "00:00")); publishFrom = DateUtil.parseDateTime(date.toString()); } if (formItems.containsKey("date_pubdata_publishto")) { StringBuffer date = new StringBuffer(formItems.getString("date_pubdata_publishto")); date.append(' '); date.append(formItems.getString("time_pubdata_publishto", "00:00")); publishTo = DateUtil.parseDateTime(date.toString()); } if (published && publishFrom == null) { publishFrom = now; } if (published && publishTo != null && publishTo.before(now)) { publishTo = null; } if (publishFrom != null) { content.setAttribute("publishfrom", DateUtil.formatISODateTime(publishFrom)); } if (publishTo != null) { content.setAttribute("publishto", DateUtil.formatISODateTime(publishTo)); } } catch (ParseException e) { VerticalAdminLogger.errorAdmin(ContentBaseHandlerServlet.class, 10, "Error parsing dates: %t", e); } // created: if (!create) { content.setAttribute("created", formItems.getString("_pubdata_created")); } String contentTitle; if (usePersistedContendataXML || excludeContendataXML) { int versionKey = formItems.getInt("versionkey"); contentTitle = admin.getContentTitle(versionKey); if (contentTitle == null || contentTitle.length() == 0) { Document contentDoc = XMLTool.domparse(admin.getContentVersion(user, versionKey)); Element contentElem = (Element) contentDoc.getDocumentElement().getFirstChild(); Element contentDataElem = XMLTool.getElement(contentElem, "contentdata"); contentTitle = getContentTitle(contentDataElem, contenttypekey); } } else { contentTitle = getContentTitle(formItems); } // Content title XMLTool.createElement(doc, content, "title", contentTitle); String contentName = formItems.getString("_name", null); if (StringUtils.isBlank(contentName)) { contentName = PrettyPathNameCreator.generatePrettyPathName(contentTitle); } XMLTool.createElement(doc, content, "name", contentName); // create the units root Element contentdata = XMLTool.createElement(doc, content, "contentdata"); // category Element categoryname; // Not sure if category_name is present in all situations if (formItems.containsKey("category_name")) { categoryname = XMLTool.createElement(doc, content, "categoryname", formItems.getString("category_name")); } else { categoryname = XMLTool.createElement(doc, content, "categoryname"); } categoryname.setAttribute("key", String.valueOf(categoryKey)); if (!excludeContendataXML) { if (usePersistedContendataXML) { Document contentXML = XMLTool .domparse(admin.getContentXMLField(user, formItems.getInt("versionkey"))); XMLTool.replaceElement(contentdata, contentXML.getDocumentElement()); } else { // Create the content type specific XML buildContentTypeXML(user, doc, contentdata, formItems); } } // add access rights to content xml AdminHandlerBaseServlet.buildAccessRightsXML(content, null, formItems, AccessRight.CONTENT); return XMLTool.documentToString(doc); }
From source file:com.example.android.rowanparkingpass.Activities.PassActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pass); i = 0;/*from ww w . jav a 2 s . co m*/ Intent pastIntent = getIntent(); currentMode = pastIntent.getStringExtra(MODE); db = new DatabaseHandlerPasses(getApplicationContext()); Pass pass = (Pass) pastIntent.getSerializableExtra("Pass"); if (pass == null) { driver = (Driver) pastIntent.getSerializableExtra("Driver"); vehicle = (Vehicle) pastIntent.getSerializableExtra("Vehicle"); } else { driver = pass.getDriver(); vehicle = pass.getVehicle(); } setDriverView(); setVehicleView(); dateFormatter = new SimpleDateFormat("MM/dd/yyyy"); startDate = (EditText) findViewById(R.id.createstartdatefield); startDate.setInputType(InputType.TYPE_NULL); startDate.setOnClickListener(this); endDate = (EditText) findViewById(R.id.createenddatefield); endDate.setInputType(InputType.TYPE_NULL); endDate.setOnClickListener(this); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(year, month, day); startDate.setText(dateFormatter.format(calendar.getTime())); calendar.add(Calendar.DAY_OF_MONTH, 1); endDate.setText(dateFormatter.format(calendar.getTime())); startDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); startDate.setText(dateFormatter.format(newDate.getTime())); try { Date d = newDate.getTime(); Date d2 = dateFormatter.parse(endDate.getText().toString()); if (d.after(d2)) { newDate.add(Calendar.DAY_OF_MONTH, 1); endDate.setText(dateFormatter.format(newDate.getTime())); } } catch (ParseException pe) { pe.printStackTrace(); } } }, year, month, day); endDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); endDate.setText(dateFormatter.format(newDate.getTime())); try { Date d = newDate.getTime(); Date d2 = dateFormatter.parse(startDate.getText().toString()); if (d.before(d2)) { newDate.add(Calendar.DAY_OF_MONTH, -1); startDate.setText(dateFormatter.format(newDate.getTime())); } } catch (ParseException pe) { pe.printStackTrace(); } } }, year, month, day); createPass = (Button) findViewById(R.id.createPassButton); mainMenu = (Button) findViewById(R.id.goMainMenuButton); createPass.setOnClickListener(this); mainMenu.setOnClickListener(this); }
From source file:ucar.unidata.idv.control.chart.TimeSeriesChart.java
/** * Make the plot/* w w w . j a v a2 s . c om*/ * * @return The plot_ */ public Plot doMakePlot() { IdvPreferenceManager pref = control.getControlContext().getIdv().getPreferenceManager(); TimeZone timeZone = pref.getDefaultTimeZone(); NumberAxis valueAxis = new FixedWidthNumberAxis(""); final SimpleDateFormat sdf = new SimpleDateFormat( ((dateFormat != null) ? dateFormat : pref.getDefaultDateFormat())); sdf.setTimeZone(timeZone); DateAxis timeAxis = new DateAxis("Time (" + timeZone.getID() + ")", timeZone) { protected List xxxxxrefreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { List ticks = super.refreshTicksHorizontal(g2, dataArea, edge); List<Tick> result = new java.util.ArrayList<Tick>(); Font tickLabelFont = getTickLabelFont(); g2.setFont(tickLabelFont); if (isAutoTickUnitSelection()) { selectAutoTickUnit(g2, dataArea, edge); } DateTickUnit unit = getTickUnit(); Date tickDate = calculateLowestVisibleTickValue(unit); Date upperDate = getMaximumDate(); Date firstDate = null; while (tickDate.before(upperDate)) { if (!isHiddenValue(tickDate.getTime())) { // work out the value, label and position String tickLabel; DateFormat formatter = getDateFormatOverride(); if (firstDate == null) { if (formatter != null) { tickLabel = formatter.format(tickDate); } else { tickLabel = getTickUnit().dateToString(tickDate); } firstDate = tickDate; } else { double msdiff = tickDate.getTime() - firstDate.getTime(); int hours = (int) (msdiff / 1000 / 60 / 60); tickLabel = hours + "H"; } // tickLabel = tickLabel; TextAnchor anchor = null; TextAnchor rotationAnchor = null; double angle = 0.0; if (isVerticalTickLabels()) { anchor = TextAnchor.CENTER_RIGHT; rotationAnchor = TextAnchor.CENTER_RIGHT; if (edge == RectangleEdge.TOP) { angle = Math.PI / 2.0; } else { angle = -Math.PI / 2.0; } } else { if (edge == RectangleEdge.TOP) { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; } else { anchor = TextAnchor.TOP_CENTER; rotationAnchor = TextAnchor.TOP_CENTER; } } Tick tick = new DateTick(tickDate, tickLabel, anchor, rotationAnchor, angle); result.add(tick); tickDate = unit.addToDate(tickDate, getTimeZone()); } else { tickDate = unit.rollDate(tickDate, getTimeZone()); continue; } // could add a flag to make the following correction optional... switch (unit.getUnit()) { case (DateTickUnit.MILLISECOND): case (DateTickUnit.SECOND): case (DateTickUnit.MINUTE): case (DateTickUnit.HOUR): case (DateTickUnit.DAY): break; case (DateTickUnit.MONTH): tickDate = calculateDateForPositionX(new Month(tickDate, getTimeZone()), getTickMarkPosition()); break; case (DateTickUnit.YEAR): tickDate = calculateDateForPositionX(new Year(tickDate, getTimeZone()), getTickMarkPosition()); break; default: break; } } return result; } private Date calculateDateForPositionX(RegularTimePeriod period, DateTickMarkPosition position) { if (position == null) { throw new IllegalArgumentException("Null 'position' argument."); } Date result = null; if (position == DateTickMarkPosition.START) { result = new Date(period.getFirstMillisecond()); } else if (position == DateTickMarkPosition.MIDDLE) { result = new Date(period.getMiddleMillisecond()); } else if (position == DateTickMarkPosition.END) { result = new Date(period.getLastMillisecond()); } return result; } }; timeAxis.setDateFormatOverride(sdf); final XYPlot[] xyPlotHolder = { null }; xyPlotHolder[0] = new MyXYPlot(new TimeSeriesCollection(), timeAxis, valueAxis, null) { public void drawBackground(Graphics2D g2, Rectangle2D area) { super.drawBackground(g2, area); drawSunriseSunset(g2, xyPlotHolder[0], area); } }; if (animationTimeAnnotation != null) { xyPlotHolder[0].addAnnotation(animationTimeAnnotation); } return xyPlotHolder[0]; }
From source file:com.virtusa.akura.student.controller.StudentTemporaryLeaveController.java
/** * save extended temporary leave student , when he is on temporary leave. * * @param studentTemporaryLeave - containing studentTemporaryLeave attribute to which data was bound * @param request - request of type HttpServletRequest * @param model - model./*w ww . ja v a 2s .co m*/ * @param session - session of user. * @return viewPage - viewPage of jsp. * @throws AkuraAppException - The exception details that occurred when re join temporary leave student * instance. */ @RequestMapping(value = REQUEST_MAP_SAVE_EXTENDED_STUDENT_TEMP_HTM) public String saveExtendedTemporaryStudent(HttpServletRequest request, final ModelMap model, @ModelAttribute(MODEL_TEMP_LEAVE_LIST_COMMAND) final StudentTemporaryLeave studentTemporaryLeave, final HttpSession session) throws AkuraAppException { String viewPage = VIEW_PAGE_STUDENT_ACTIVE_STUDENT_TEMPORARY_LEAVE; Date getToDate = null; Date getFromDate = null; if (studentTemporaryLeave != null) { getToDate = studentTemporaryLeave.getToDate(); getFromDate = studentTemporaryLeave.getFromDate(); } if (getToDate == null) { String dateError = new ErrorMsgLoader() .getErrorMessage(STUDENT_TEMPEPORY_LEAVE_EXTEND_TO_DATE_ERROR_MESSAGE); model.addAttribute(MODEL_MESSAGE, dateError); request.setAttribute(REQUEST_STATE, Boolean.TRUE); model.addAttribute(MODEL_ATT_SUCCESS_ACTIVE_MSG, Boolean.TRUE); } else { Date dateToDate = DateUtil.getParseDate(DateUtil.getFormatDate(getToDate)); Date dateFromdate = DateUtil.getParseDate(DateUtil.getFormatDate(getFromDate)); if (dateToDate.before(dateFromdate)) { String message = new ErrorMsgLoader().getErrorMessage(REF_UI_DATE_FIELD_INCORRECT); model.addAttribute(MODEL_MESSAGE, message); request.setAttribute(REQUEST_STATE, Boolean.TRUE); model.addAttribute(MODEL_ATT_SUCCESS_ACTIVE_MSG, Boolean.TRUE); } else { int studentId = Integer.parseInt(request.getParameter(REQUEST_SELECTED_STUDENT_ID)); Student student = studentService.findStudent(studentId); List<StudentTemporaryLeave> studentTemporaryLeavelist = SortUtil .sorttemporaryLeaveStudentListByDate( studentService.getStudentTempLeaveListByStudentId(studentId)); Date extendToDate = studentTemporaryLeavelist.get(0).getToDate(); Calendar fromDate = Calendar.getInstance(); fromDate.setTime(getFromDate); Calendar toDate = Calendar.getInstance(); toDate.setTime(getToDate); // get holiday list List<Holiday> holidayList = getHolidayList(getFromDate, getToDate); // get number of working days int workingDays = HolidayUtil.countWorkingDays(fromDate, toDate, holidayList); // save extended student temporary lave object studentService.saveExtendedTemporaryStudent(studentId, workingDays, getToDate); List<StudentTemporaryLeave> studentTempLeaveList = studentService .getStudentTempLeaveListByStudentId(studentId); model.addAttribute(REQUEST_MAP_TEMP_LEAVE_LIST, studentTempLeaveList); // student leave object StudentLeave studentLeave = null; // get student leave list List<StudentLeave> studentLeaveList = studentService.getStudentLeaveListByStudentId(studentId); if (!studentLeaveList.isEmpty()) { // take the last record of student leave - to be updated this record studentLeave = studentLeaveList.get(studentLeaveList.size() - 1); } // update student leave object if (studentLeave != null) { studentLeave.setToDate(getToDate); studentLeave.setNoOfDays(workingDays); // update student leave object with to date ,number of working days. studentService.updateStudentLeave(studentLeave); } if (dateToDate.before(extendToDate)) { model.addAttribute(EXTENDED_MSG, new ErrorMsgLoader().getErrorMessage(THE_TEMPERORY_LEAVE_IS_CURTAILED_SUCCESSFULLY)); // send a mail to the student's parent by the logged user - Administrator. this.sendConfirmationMail(studentId, model, session, student, EXTEND_TEMPORARY_LEAVE, studentTemporaryLeave); } if (dateToDate.after(extendToDate)) { model.addAttribute(EXTENDED_MSG, new ErrorMsgLoader().getErrorMessage(THE_TEMPERATURE_LEAVE_IS_EXTENDED_SUCCESSFULLY)); // send a mail to the student's parent by the logged user - Administrator. this.sendConfirmationMail(studentId, model, session, student, EXTEND_TEMPORARY_LEAVE, studentTemporaryLeave); } request.setAttribute(REQUEST_STATE, Boolean.TRUE); request.setAttribute(REQUEST_SUCCESS_MSG, Boolean.TRUE); model.addAttribute(MODEL_ATT_SUCCESS_ACTIVE_MSG, Boolean.FALSE); request.setAttribute(REQUEST_SUCCESS, Boolean.TRUE); } } return viewPage; }
From source file:com.aurel.track.item.ItemDetailAction.java
/** * Deletes the selected comments// w w w . j a v a 2 s. com * @return */ public String deleteComments() { Date originalLastModifiedDate = null; Date lastModifiedDate = DateTimeUtils.getInstance().parseISODateTime(lastModified); TWorkItemBean workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID); if (workItemBean != null) { originalLastModifiedDate = workItemBean.getLastEdit(); } Integer[] commentsToDelete = ItemDetailBL.getIntegerTokens(deletedItems); for (int i = 0; i < commentsToDelete.length; i++) { HistorySaverBL.deleteComment(workItemID, person.getObjectID(), locale, commentsToDelete[i]); } StringBuilder sb = new StringBuilder(); sb.append("{"); JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true); JSONUtility.appendFieldName(sb, JSONUtility.JSON_FIELDS.DATA).append(":{"); if (originalLastModifiedDate != null && lastModifiedDate != null) { if (!lastModifiedDate.before(originalLastModifiedDate)) { workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID); Date lastModified = null; if (workItemBean != null) { lastModified = workItemBean.getLastEdit(); } JSONUtility.appendStringValue(sb, "lastModified", DateTimeUtils.getInstance().formatISODateTime(lastModified), true); } } sb.append("}}"); try { JSONUtility.prepareServletResponseJSON(ServletActionContext.getResponse()); PrintWriter out = ServletActionContext.getResponse().getWriter(); out.println(sb); } catch (IOException e) { // TODO Auto-generated catch block LOGGER.error(ExceptionUtils.getStackTrace(e)); } return null; }
From source file:com.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public void processExpired4Warranty(Object row) { Map rowMap = (HashMap) row; Date t_timeEnd = (Date) rowMap.get("c_warranty_end"); Date t_timeBegin = (Date) rowMap.get("c_warranty_begin"); if (null != t_timeEnd && null != t_timeBegin) { long timeBetween = (DateUtils.truncate(t_timeEnd, Calendar.DAY_OF_MONTH).getTime() - DateUtils.truncate(t_timeBegin, Calendar.DAY_OF_MONTH).getTime()) / 86400000; // / 1000 / 60 / 60 / 24 timeBetween = (long) Math.ceil(((timeBetween + 1) / 30f)); rowMap.put("c_warranty", String.valueOf(timeBetween)); rowMap.put("c_is_expired", t_timeEnd.before(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH))); }/*from w w w . j a va 2 s .c o m*/ }
From source file:com.ibm.xsp.webdav.resource.DAVResourceDominoCategorizedDocuments.java
private void fetchChildrenForNotesView() { // LOGGER.info(getCallingMethod()+":"+"Start fetchChildrenForNotesView; Fetching children for " // +/* w w w. ja va2 s . co m*/ // this.getName()+" with internal address= "+this.getInternalAddress()+" and public href= "+this.getPublicHref()); Document curDoc = null; View curView = null; Database curDb = null; Vector<IDAVResource> resMembers = new Vector<IDAVResource>(); this.setMembers(resMembers); String notesURL = this.getInternalAddress(); curView = DominoProxy.getView(notesURL); if (curView == null) { LOGGER.error("Could not retrieve view: " + notesURL); return; } DAVRepositoryDominoCategorizedDocuments repository = (DAVRepositoryDominoCategorizedDocuments) this .getRepository(); // Read the repository list to get the view try { // LOGGER.info(getCallingMethod()+":"+"Openend view " + // curView.getName()); // Initialize an empty vector at the right size // We might need to enlarge it if we have more attachments // LOGGER.info( "View num doc is "+new // Integer(curView.getEntryCount()).toString()); DocumentCollection docColl = repository.getAllDocumentsByKey("/"); curDoc = docColl.getFirstDocument(); while (curDoc != null) { // LOGGER.info( "Start processing doc no "+ new // Integer(i).toString()); // LOGGER.info(getCallingMethod()+":"+"Start process view "); DAVResourceDominoCategorizedDocuments docRes = null; if (curDoc.hasEmbedded()) { // LOGGER.info(getCallingMethod()+":"+"Document "+curDoc.getUniversalID()+ // " has embedded; Start Add Attachments"); // docRes = this.addAttachmentsFromDocument(curDoc); docRes = new DAVResourceDominoCategorizedDocuments(this.getRepository()); docRes.setup(curDoc); // docRes.setCollection(false); // docRes.setMember(true); // LOGGER.info(getCallingMethod()+":"+"Successfully create attachments for "+curDoc.getUniversalID()); } else { // LOGGER.info(getCallingMethod()+":"+"Document "+ // curDoc.getUniversalID()+ // " has no attachment; try to get a resource"); docRes = new DAVResourceDominoCategorizedDocuments(this.getRepository()); docRes.setup(curDoc); docRes.setCollection(true); docRes.setMember(false); // LOGGER.info(getCallingMethod()+":"+"Successfully create resource from doc "+docRes.getName()); } // TODO: Fix this! if (docRes != null) { // LOGGER.info(getCallingMethod()+":"+"Resource "+docRes.getName()+"created OK; Try to add to resMembers"); if (docRes.filter()) { this.getMembers().add(docRes); } // LOGGER.info(getCallingMethod()+":"+"Resources added OK;"); // Capture last modified based on the latest date of the // documents in view Date viewDate = this.getLastModified(); Date docDate = docRes.getLastModified(); if (viewDate == null || (docDate != null && viewDate.before(docDate))) { this.setLastModified(docDate); } // LOGGER.info(getCallingMethod()+":"+"Resource processes OK"); } // // // LOGGER.info(getCallingMethod()+":"+"Try recycle and find the next for "+curDoc.getUniversalID()+"...."); // Document oldDoc=curDoc; // curDoc = curView.getNextDocument(curDoc); // oldDoc.recycle(); // // LOGGER.info(getCallingMethod()+":"+"Recycle OK!"); // // // LOGGER.info("Next doc is "+((curDoc!=null)?"Not null":"null")); curDoc = docColl.getNextDocument(); } // end for } catch (NotesException ne) { LOGGER.error(ne); } catch (Exception e) { LOGGER.error(e); } finally { try { // LOGGER.info(getCallingMethod()+":"+"Final recycle...."); if (curDoc != null) { // curDoc.recycle(); } if (curView != null) { curView.recycle(); } if (curDb != null) { curDb.recycle(); } // LOGGER.info(getCallingMethod()+":"+"Final recycle OK!"); } catch (Exception e) { LOGGER.error(e); } // LOGGER.info(getCallingMethod()+":"+"Completed reading file resources from Domino view"); // LOGGER.info(getCallingMethod()+":"+"Start to setMembers..."); // this.setMembers(resMembers); // LOGGER.info(getCallingMethod()+":"+"SetMembers OK! Exit fetchChildrenforNotesView"); } // Now save back the members to the main object }