Example usage for java.util Date equals

List of usage examples for java.util Date equals

Introduction

In this page you can find the example usage for java.util Date equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares two dates for equality.

Usage

From source file:org.craftercms.studio.impl.v1.service.workflow.WorkflowServiceImpl.java

protected List<DmDependencyTO> getRefAndChildOfDiffDateFromParent(String site,
        List<DmDependencyTO> submittedItems, boolean removeInPages) {
    List<DmDependencyTO> childAndReferences = new ArrayList<>();
    for (DmDependencyTO submittedItem : submittedItems) {
        List<DmDependencyTO> children = submittedItem.getChildren();
        Date date = submittedItem.getScheduledDate();
        if (children != null) {
            Iterator<DmDependencyTO> childItr = children.iterator();
            while (childItr.hasNext()) {
                DmDependencyTO child = childItr.next();
                Date pageDate = child.getScheduledDate();
                if ((date == null && pageDate != null) || (date != null && !date.equals(pageDate))) {
                    if (!submittedItem.isNow()) {
                        child.setNow(false);
                        if (date != null && (pageDate != null && pageDate.before(date))) {
                            child.setScheduledDate(date);
                        }//from   w w w.  j a  v a 2s . c om
                    }
                    childAndReferences.add(child);
                    List<DmDependencyTO> childDeps = child.flattenChildren();
                    for (DmDependencyTO childDep : childDeps) {
                        if (objectStateService.isUpdatedOrNew(site, childDep.getUri())) {
                            childAndReferences.add(childDep);
                        }
                    }
                    child.setReference(false);
                    childItr.remove();
                    if (removeInPages) {
                        String uri = child.getUri();
                        List<DmDependencyTO> pages = submittedItem.getPages();
                        if (pages != null) {
                            Iterator<DmDependencyTO> pagesIter = pages.iterator();
                            while (pagesIter.hasNext()) {
                                DmDependencyTO page = pagesIter.next();
                                if (page.getUri().equals(uri)) {
                                    pagesIter.remove();
                                }
                            }
                        }
                    }
                }
            }
        }

        Set<String> dependenciesPaths = deploymentDependencyRule.applyRule(site, submittedItem.getUri());
        for (String depPath : dependenciesPaths) {
            childAndReferences.add(dmDependencyService.getDependenciesNoCalc(site, depPath, false, true, null));
        }
    }
    return childAndReferences;
}

From source file:org.craftercms.studio.impl.v1.service.workflow.WorkflowServiceImpl.java

protected void doDelete(String site, List<DmDependencyTO> submittedItems, String approver)
        throws ServiceException {
    long start = System.currentTimeMillis();
    String user = securityService.getCurrentUser();
    // get web project information
    //String assignee = getAssignee(site, sub);
    // Don't make go live an item if it is new and to be deleted
    final Date now = new Date();
    List<String> itemsToDelete = new ArrayList<>();
    List<DmDependencyTO> deleteItems = new ArrayList<>();
    List<DmDependencyTO> scheItems = new ArrayList<>();
    for (DmDependencyTO submittedItem : submittedItems) {
        String uri = submittedItem.getUri();
        Date schDate = submittedItem.getScheduledDate();
        boolean isItemForSchedule = false;
        if (schDate == null || schDate.before(now)) {
            // Sending Notification
            if (StringUtils.isNotEmpty(approver)) {
                // immediate delete
                if (submittedItem.isSendEmail()) {
                    sendDeleteApprovalNotification(site, submittedItem, approver);//TODO move it after delete actually happens
                }/* www  .  j a v  a 2 s  .co m*/
            }
            if (submittedItem.getUri().endsWith(DmConstants.INDEX_FILE)) {
                submittedItem.setUri(submittedItem.getUri().replace("/" + DmConstants.INDEX_FILE, ""));
            }
            itemsToDelete.add(uri);
        } else {
            scheItems.add(submittedItem);
            isItemForSchedule = true;
        }
        submittedItem.setDeleted(true);
        // replace with the folder name
        boolean isNew = objectStateService.isNew(site, uri);
        if (!isNew || isItemForSchedule) {
            deleteItems.add(submittedItem);
        }
        ContentItemTO itemToDelete = contentService.getContentItem(site, uri);
        /* TODO: if item is renamed
        if(persistenceManagerService.hasAspect(itemToDelete, CStudioContentModel.ASPECT_RENAMED)){
        String oldPath = (String) persistenceManagerService.getProperty(itemToDelete, CStudioContentModel.PROP_RENAMED_OLD_URL);
        if(oldPath!=null){
            itemsToDelete.add(oldPath);//Make sure old path is going to be deleted
        }
        }*/
    }
    //List<String> deletedItems = deleteInTransaction(site, itemsToDelete);
    GoLiveContext context = new GoLiveContext(approver, site);
    //final String pathPrefix = getSiteRoot(site, null);
    final String pathPrefix = "/wem-projects/" + site + "/" + site + "/work-area";
    Map<Date, List<DmDependencyTO>> groupedPackages = groupByDate(deleteItems, now);
    if (groupedPackages.isEmpty()) {
        groupedPackages.put(now, Collections.<DmDependencyTO>emptyList());
    }
    for (Date scheduledDate : groupedPackages.keySet()) {
        List<DmDependencyTO> deletePackage = groupedPackages.get(scheduledDate);
        SubmitPackage submitpackage = new SubmitPackage(pathPrefix);
        Set<String> rescheduledUris = new HashSet<String>();
        if (deletePackage != null) {
            Date launchDate = scheduledDate.equals(now) ? null : scheduledDate;
            for (DmDependencyTO dmDependencyTO : deletePackage) {
                if (launchDate != null) {
                    handleReferences(site, submitpackage, dmDependencyTO, true, null, "", rescheduledUris);
                } else {
                    applyDeleteDependencyRule(site, submitpackage, dmDependencyTO);
                }
            }
            String label = submitpackage.getLabel();
            //String workFlowName = _submitDirectWorkflowName;

            SubmitLifeCycleOperation deleteOperation = null;
            Set<String> liveDependencyItems = new HashSet<String>();
            Set<String> allItems = new HashSet<String>();
            for (String uri : itemsToDelete) {//$ToDO $ remove this case and keep the item in go live queue
                GoLiveDeleteCandidates deleteCandidate = contentService.getDeleteCandidates(context.getSite(),
                        uri);
                allItems.addAll(deleteCandidate.getAllItems());
                //get all dependencies that has to be removed as well
                liveDependencyItems.addAll(deleteCandidate.getLiveDependencyItems());
            }

            List<String> submitPackPaths = submitpackage.getPaths();
            if (launchDate != null) {
                deleteOperation = new PreScheduleDeleteOperation(this, submitpackage.getUris(), launchDate,
                        context, rescheduledUris);
                label = DmConstants.DM_SCHEDULE_SUBMISSION_FLOW + ":" + label;
                //workFlowName = _reviewWorkflowName;
                /*
                for (String submitPackPath : submitpackage.getUris()) {
                String fullpath = dmContentService.getContentFullPath(site, submitPackPath);
                _cacheManager.invalidateAndRemoveFromQueue(fullpath, site);
                }*/
            } else {
                //add dependencies to submitPackage
                for (String liveDependency : liveDependencyItems) {
                    DmPathTO pathTO = new DmPathTO(liveDependency);
                    submitpackage.addToPackage(pathTO.getRelativePath());
                }
                submitPackPaths = submitpackage.getPaths();

                deleteOperation = new PreSubmitDeleteOperation(this, new HashSet<String>(itemsToDelete),
                        context, rescheduledUris);
                removeChildFromSubmitPackForDelete(submitPackPaths);
                for (String deleteCandidate : allItems) {
                    //_cacheManager.invalidateAndRemoveFromQueue(deleteCandidate, site);
                }
            }
            Map<String, String> submittedBy = new HashMap<>();

            /* TODO: add to submitted by mapping
            for (String longPath : submitPackPaths) {
            String uri = longPath.substring(pathPrefix.length());
            //DmUtils.addToSubmittedByMapping(persistenceManagerService, dmContentService, searchService, site, uri, submittedBy, approver);
            }*/

            workflowProcessor.addToWorkflow(site, new ArrayList<String>(), launchDate, label, deleteOperation,
                    approver, null);
        }
    }
    long end = System.currentTimeMillis();
    logger.debug("Submitted deleted items to queue time = " + (end - start));
}

From source file:org.alfresco.module.vti.handler.alfresco.AlfrescoMeetingServiceHandler.java

/**
 * @see org.alfresco.module.vti.handler.MeetingServiceHandler#updateMeetingFromICal(String, MeetingBean, boolean)
 *//* w  ww.j a v  a2  s .  c  o m*/
@SuppressWarnings("deprecation")
public void updateMeetingFromICal(final String siteName, MeetingBean meeting, boolean ignoreAttendees) {
    NodeRef calendarContainer = null;

    calendarContainer = siteService.getContainer(siteName, CALENDAR_CONTAINER_NAME);
    if (calendarContainer == null) {
        throw new VtiHandlerException(getMessage("vti.meeting.error.no_site_update"));
    }

    // Tweak things on the meeting bean as needed
    adjustMeetingProperties(meeting);

    // Get the current event object to update
    final CalendarEntry entry = getEvent(siteName, meeting.getId());
    if (entry == null) {
        throw new VtiHandlerException(getMessage("vti.meeting.error.no_meeting_update"));
    }

    if (meeting.getReccurenceIdDate() != null) {
        // it is occurrence instance update, not series
        final Date updateDate = meeting.getReccurenceIdDate();
        final Date newStart = meeting.getStart();
        final Date newEnd = meeting.getEnd();
        final String newWhat = meeting.getTitle();
        final String newWhere = meeting.getLocation();

        transactionService.getRetryingTransactionHelper()
                .doInTransaction(new RetryingTransactionCallback<Object>() {
                    public Object execute() {
                        HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
                        properties.put(CalendarModel.PROP_UPDATED_EVENT_DATE, updateDate);
                        properties.put(CalendarModel.PROP_UPDATED_START, newStart);
                        properties.put(CalendarModel.PROP_UPDATED_END, newEnd);
                        properties.put(CalendarModel.PROP_UPDATED_WHAT, newWhat);
                        properties.put(CalendarModel.PROP_UPDATED_WHERE, newWhere);

                        QName childName = QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX,
                                "updatedEvent_" + ISO8601DateFormat.format(updateDate).replaceAll("[:\\.]", "_")
                                        + "_" + GUID.generate());
                        NodeRef meetingNodeRef = entry.getNodeRef();

                        // find if occurrence has already been updated before
                        Set<QName> childNodeTypeQNames = new HashSet<QName>();
                        childNodeTypeQNames.add(CalendarModel.TYPE_UPDATED_EVENT);
                        List<ChildAssociationRef> updatedEventList = nodeService
                                .getChildAssocs(entry.getNodeRef(), childNodeTypeQNames);
                        for (ChildAssociationRef updatedEvent : updatedEventList) {
                            NodeRef updatedEventRef = updatedEvent.getChildRef();
                            Date updatedDateProp = (Date) nodeService.getProperty(updatedEventRef,
                                    CalendarModel.PROP_UPDATED_EVENT_DATE);
                            if (updateDate.equals(updatedDateProp)) {
                                nodeService.setProperties(updatedEventRef, properties);
                                return null;
                            }
                        }

                        // create node for edited separate event
                        nodeService.createNode(meetingNodeRef, CalendarModel.ASSOC_UPDATED_EVENT_LIST,
                                childName, CalendarModel.TYPE_UPDATED_EVENT, properties);
                        return null;
                    }
                });

        return;
    }

    // Copy everything onto it
    // TODO It would be better if the caller asked us for the
    //  MeetingBean rather than creating a new one...
    entry.setTitle(meeting.getTitle());
    entry.setDescription(meeting.getDescription());
    entry.setLocation(meeting.getLocation());

    // Cancel all updated occurrences, when recurrence is going to change  
    if ((entry.getRecurrenceRule() != null
            && (!StringUtils.equals(entry.getRecurrenceRule(), meeting.getRecurrenceRule())
                    || !entry.getStart().equals(meeting.getStart()))
            || !entry.getEnd().equals(meeting.getEnd()))
            || (entry.getLastRecurrence() != null
                    && !ObjectUtils.equals(entry.getLastRecurrence(), meeting.getLastRecurrence()))) {
        Set<QName> childNodeTypeQNames = new HashSet<QName>();
        childNodeTypeQNames.add(CalendarModel.TYPE_UPDATED_EVENT);
        childNodeTypeQNames.add(CalendarModel.TYPE_IGNORE_EVENT);
        List<ChildAssociationRef> updatedEventList = nodeService.getChildAssocs(entry.getNodeRef(),
                childNodeTypeQNames);
        for (ChildAssociationRef updatedEvent : updatedEventList) {
            nodeService.deleteNode(updatedEvent.getChildRef());
        }
    }

    entry.setStart(meeting.getStart());
    entry.setEnd(meeting.getEnd());
    entry.setRecurrenceRule(meeting.getRecurrenceRule());
    entry.setLastRecurrence(meeting.getLastRecurrence());
    entry.setOutlookUID(meeting.getOutlookUID());
    entry.setSharePointDocFolder(meeting.getSharePointDocFolder());

    // Do the attendees
    // TODO Update this to be more efficient
    final List<String> usersToAdd = new ArrayList<String>();
    Set<NodeRef> peoples = personService.getAllPeople();
    final Set<String> siteMembers = siteService.listMembers(siteName, null, null, -1, true).keySet();

    for (String email : meeting.getAttendees()) {

        for (NodeRef peopleRef : peoples) {
            String personEmail = (String) nodeService.getProperty(peopleRef, ContentModel.PROP_EMAIL);

            if (personEmail == null || !personEmail.equalsIgnoreCase(email)) {
                continue;
            }

            String userName = (String) nodeService.getProperty(peopleRef, ContentModel.PROP_USERNAME);

            if (siteMembers.contains(userName)) {
                siteMembers.remove(userName);
            }

            if (siteService.isMember(siteName, userName)) {
                String memberRole = siteService.getMembersRole(siteName, userName);
                if (memberRole.equals(SiteModel.SITE_CONSUMER)
                        || memberRole.equals(SiteModel.SITE_CONTRIBUTOR)) {
                    usersToAdd.add(userName);
                }
            } else {
                usersToAdd.add(userName);
            }
        }
    }

    transactionService.getRetryingTransactionHelper()
            .doInTransaction(new RetryingTransactionCallback<Object>() {
                public Object execute() {
                    calendarService.updateCalendarEntry(entry);

                    SiteInfo siteInfo = siteService.getSite(siteName);
                    String siteCreator = (String) nodeService.getProperty(siteInfo.getNodeRef(),
                            ContentModel.PROP_CREATOR);

                    for (String member : siteMembers) {
                        if (member.equalsIgnoreCase(siteCreator)) {
                            continue;
                        }
                        siteService.removeMembership(siteName, member);
                    }
                    for (String userName : usersToAdd) {
                        siteService.setMembership(siteName, userName, SiteModel.SITE_COLLABORATOR);
                    }

                    return null;
                }
            });

    if (logger.isDebugEnabled()) {
        logger.debug("Meeting with Outlook UID = '" + meeting.getId() + "' was updated.");
    }
}

From source file:org.exoplatform.calendar.webui.popup.UIEventForm.java

public void saveAndNoAsk(Event<UIEventForm> event, boolean isSend, boolean updateSeries) throws Exception {
    UIEventForm uiForm = event.getSource();
    UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class);
    UIPopupAction uiPopupAction = uiForm.getAncestorOfType(UIPopupAction.class);
    UICalendarViewContainer uiViewContainer = calendarPortlet
            .findFirstComponentOfType(UICalendarViewContainer.class);
    CalendarSetting calSetting = calendarPortlet.getCalendarSetting();
    CalendarService calService = CalendarUtils.getCalendarService();
    String summary = uiForm.getEventSumary().trim();
    summary = CalendarUtils.enCodeTitle(summary);
    String location = uiForm.getEventPlace();
    if (!CalendarUtils.isEmpty(location))
        location = location.replaceAll(CalendarUtils.GREATER_THAN, "").replaceAll(CalendarUtils.SMALLER_THAN,
                "");
    String description = uiForm.getEventDescription();
    if (!CalendarUtils.isEmpty(description))
        description = description.replaceAll(CalendarUtils.GREATER_THAN, "")
                .replaceAll(CalendarUtils.SMALLER_THAN, "");
    if (!uiForm.isEventDetailValid(calSetting)) {
        event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(uiForm.errorMsg_, null));
        uiForm.setSelectedTab(TAB_EVENTDETAIL);
        event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class));
        return;/*from  w w  w.j  a  va 2 s  .co  m*/
    }
    if (!uiForm.isReminderValid()) {
        event.getRequestContext().getUIApplication()
                .addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] { uiForm.errorValues }));
        uiForm.setSelectedTab(TAB_EVENTREMINDER);
        event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class));
        return;
    }
    if (!uiForm.isParticipantValid()) {
        event.getRequestContext().getUIApplication()
                .addMessage(new ApplicationMessage(uiForm.errorMsg_, new String[] { uiForm.errorValues }));
        uiForm.setSelectedTab(TAB_EVENTSHARE);
        event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class));
        return;
    }
    Date from = uiForm.getEventFromDate(calSetting.getDateFormat(), calSetting.getTimeFormat());
    Date to = uiForm.getEventToDate(calSetting.getDateFormat(), calSetting.getTimeFormat());
    if (from.after(to)) {
        event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage(
                uiForm.getId() + ".msg.event-date-time-logic", null, ApplicationMessage.WARNING));
        return;
    }
    String username = CalendarUtils.getCurrentUser();
    String calendarId = uiForm.getCalendarId();
    if (from.equals(to)) {
        to = CalendarUtils.getEndDay(from).getTime();
    }
    if (uiForm.getEventAllDate()) {
        java.util.Calendar tempCal = CalendarUtils.getInstanceOfCurrentCalendar();
        tempCal.setTime(to);
        tempCal.add(java.util.Calendar.MILLISECOND, -1);
        to = tempCal.getTime();
    }
    Calendar currentCalendar = CalendarUtils.getCalendar(uiForm.calType_, calendarId);
    if (currentCalendar == null) {
        uiPopupAction.deActivate();
        event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction);
        event.getRequestContext().getUIApplication()
                .addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
        return;
    }
    boolean canEdit = false;
    if (uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)) {
        canEdit = CalendarUtils.canEdit(null,
                org.exoplatform.calendar.service.Utils.getEditPerUsers(currentCalendar), username);
    } else if (uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)) {
        // cs-4429: fix for group calendar permission
        canEdit = CalendarUtils.canEdit(CalendarUtils.getOrganizationService(),
                currentCalendar.getEditPermission(), username);
    }
    if (!canEdit && !uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE)) {
        uiPopupAction.deActivate();
        event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction);
        event.getRequestContext().getUIApplication()
                .addMessage(new ApplicationMessage("UICalendars.msg.have-no-permission-to-edit", null, 1));
        return;
    }
    CalendarEvent calendarEvent = null;
    CalendarEvent oldCalendarEvent = null;
    String[] pars = uiForm.getParticipantValues().split(CalendarUtils.BREAK_LINE);
    String eventId = null;
    if (uiForm.isAddNew_) {
        calendarEvent = new CalendarEvent();
    } else {
        calendarEvent = uiForm.calendarEvent_;
        oldCalendarEvent = new CalendarEvent();
        oldCalendarEvent.setSummary(calendarEvent.getSummary());
        oldCalendarEvent.setDescription(calendarEvent.getDescription());
        oldCalendarEvent.setLocation(calendarEvent.getLocation());
        oldCalendarEvent.setFromDateTime(calendarEvent.getFromDateTime());
        oldCalendarEvent.setToDateTime(calendarEvent.getToDateTime());
    }
    calendarEvent.setFromDateTime(from);
    calendarEvent.setToDateTime(to);

    calendarEvent.setSendOption(uiForm.getSendOption());
    calendarEvent.setMessage(uiForm.getMessage());
    String[] parStatus = uiForm.getParticipantStatusValues().split(CalendarUtils.BREAK_LINE);

    calendarEvent.setParticipantStatus(parStatus);

    calendarEvent.setParticipant(pars);
    if (CalendarUtils.isEmpty(uiForm.getInvitationEmail()))
        calendarEvent.setInvitation(ArrayUtils.EMPTY_STRING_ARRAY);
    else if (CalendarUtils.isValidEmailAddresses(uiForm.getInvitationEmail())) {
        String addressList = uiForm.getInvitationEmail().replaceAll(CalendarUtils.SEMICOLON,
                CalendarUtils.COMMA);
        Map<String, String> emails = new LinkedHashMap<String, String>();
        for (String email : addressList.split(CalendarUtils.COMMA)) {
            String address = email.trim();
            if (!emails.containsKey(address))
                emails.put(address, address);
        }
        if (!emails.isEmpty())
            calendarEvent.setInvitation(emails.keySet().toArray(new String[emails.size()]));
    } else {
        event.getRequestContext().getUIApplication()
                .addMessage(new ApplicationMessage("UIEventForm.msg.event-email-invalid",
                        new String[] { CalendarUtils.invalidEmailAddresses(uiForm.getInvitationEmail()) }));
        uiForm.setSelectedTab(TAB_EVENTSHARE);
        event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupAction.class));

        return;
    }
    calendarEvent.setCalendarId(uiForm.getCalendarId());
    calendarEvent.setEventType(CalendarEvent.TYPE_EVENT);
    calendarEvent.setSummary(summary);
    calendarEvent.setDescription(description);
    calendarEvent.setCalType(uiForm.calType_);
    calendarEvent.setCalendarId(calendarId);
    calendarEvent.setEventCategoryId(uiForm.getEventCategory());
    UIFormSelectBox selectBox = ((UIFormInputWithActions) uiForm.getChildById(TAB_EVENTDETAIL))
            .getUIFormSelectBox(UIEventDetailTab.FIELD_CATEGORY);
    for (SelectItemOption<String> o : selectBox.getOptions()) {
        if (o.getValue().equals(selectBox.getValue())) {
            calendarEvent.setEventCategoryName(o.getLabel());
            break;
        }
    }
    //}
    calendarEvent.setLocation(location);

    if (uiForm.getEventIsRepeat()) {
        if (repeatEvent != null) {
            // copy repeat properties from repeatEvent to calendarEvent
            calendarEvent.setRepeatType(repeatEvent.getRepeatType());
            calendarEvent.setRepeatInterval(repeatEvent.getRepeatInterval());
            calendarEvent.setRepeatCount(repeatEvent.getRepeatCount());
            calendarEvent.setRepeatUntilDate(repeatEvent.getRepeatUntilDate());
            calendarEvent.setRepeatByDay(repeatEvent.getRepeatByDay());
            calendarEvent.setRepeatByMonthDay(repeatEvent.getRepeatByMonthDay());
        }
    } else {
        calendarEvent.setRepeatType(CalendarEvent.RP_NOREPEAT);
        calendarEvent.setRepeatInterval(0);
        calendarEvent.setRepeatCount(0);
        calendarEvent.setRepeatUntilDate(null);
        calendarEvent.setRepeatByDay(null);
        calendarEvent.setRepeatByMonthDay(null);
    }

    calendarEvent.setPriority(uiForm.getEventPriority());
    calendarEvent.setPrivate(UIEventForm.ITEM_PRIVATE.equals(uiForm.getShareType()));
    calendarEvent.setEventState(uiForm.getEventState());
    calendarEvent.setAttachment(uiForm.getAttachments(calendarEvent.getId(), uiForm.isAddNew_));
    calendarEvent.setReminders(uiForm.getEventReminders(from, calendarEvent.getReminders()));
    eventId = calendarEvent.getId();
    CalendarView calendarView = (CalendarView) uiViewContainer.getRenderedChild();
    this.isChangedSignificantly = this.isSignificantChanged(calendarEvent, oldCalendarEvent);

    try {
        if (calendarEvent != null && isSend) {
            try {
                CalendarEvent tempCal = sendInvitation(event, calSetting, calendarEvent);
                calendarEvent = tempCal != null ? tempCal : calendarEvent;
            } catch (Exception e) {
                if (log.isWarnEnabled())
                    log.warn("Sending invitation failed!", e);
            }
        }
        if (uiForm.isAddNew_) {
            if (uiForm.calType_.equals(CalendarUtils.PRIVATE_TYPE)) {
                calService.saveUserEvent(username, calendarId, calendarEvent, uiForm.isAddNew_);
            } else if (uiForm.calType_.equals(CalendarUtils.SHARED_TYPE)) {
                calService.saveEventToSharedCalendar(username, calendarId, calendarEvent, uiForm.isAddNew_);
            } else if (uiForm.calType_.equals(CalendarUtils.PUBLIC_TYPE)) {
                calService.savePublicEvent(calendarId, calendarEvent, uiForm.isAddNew_);
            }
        } else {
            String fromCal = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[1].trim();
            String toCal = uiForm.newCalendarId_.split(CalendarUtils.COLON)[1].trim();
            String fromType = uiForm.oldCalendarId_.split(CalendarUtils.COLON)[0].trim();
            String toType = uiForm.newCalendarId_.split(CalendarUtils.COLON)[0].trim();
            List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
            listEvent.add(calendarEvent);

            // if the event (before change) is a virtual occurrence
            if (!uiForm.calendarEvent_.getRepeatType().equals(CalendarEvent.RP_NOREPEAT)
                    && !CalendarUtils.isEmpty(uiForm.calendarEvent_.getRecurrenceId())) {
                if (!updateSeries) {
                    calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
                } else {
                    // update series:

                    if (CalendarUtils.isSameDate(oldCalendarEvent.getFromDateTime(),
                            calendarEvent.getFromDateTime())) {
                        calService.updateRecurrenceSeries(fromCal, toCal, fromType, toType, calendarEvent,
                                username);
                    } else {
                        //calService.updateRecurrenceSeries(fromCal, toCal, fromType, toType, calendarEvent, username);
                        calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
                    }
                }
            } else {
                if (org.exoplatform.calendar.service.Utils.isExceptionOccurrence(calendarEvent_))
                    calService.updateOccurrenceEvent(fromCal, toCal, fromType, toType, listEvent, username);
                else
                    calService.moveEvent(fromCal, toCal, fromType, toType, listEvent, username);
            }
            UITaskForm.updateListView(calendarView, calendarEvent, calService, username);
        }

        if (calendarView instanceof UIListContainer) {
            UIListContainer uiListContainer = (UIListContainer) calendarView;
            if (!uiListContainer.isDisplaySearchResult()) {
                uiViewContainer.refresh();
            }
        } else {
            uiViewContainer.refresh();
        }
        calendarView.setLastUpdatedEventId(eventId);
        event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer);
        UIMiniCalendar uiMiniCalendar = calendarPortlet.findFirstComponentOfType(UIMiniCalendar.class);
        event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar);
        uiPopupAction.deActivate();
        event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupAction);
    } catch (Exception e) {
        event.getRequestContext().getUIApplication()
                .addMessage(new ApplicationMessage("UIEventForm.msg.add-event-error", null));
        if (log.isDebugEnabled()) {
            log.debug("Fail to add the event", e);
        }
    }

    UIEventDetailTab uiDetailTab = uiForm.getChildById(TAB_EVENTDETAIL);
    for (Attachment att : uiDetailTab.getAttachments()) {
        UIAttachFileForm.removeUploadTemp(uiForm.getApplicationComponent(UploadService.class),
                att.getResourceId());
    }
}

From source file:autoInsurance.BeiJPiccImpl.java

public String queryBaseData(String in, Map<String, String> map) {
    // TODO Auto-generated method stub
    JSONObject jsonObject = JSONObject.fromObject(in);
    String chepNu = jsonObject.getString("chepNu");
    String chejh = jsonObject.getString("chejh");
    String fadjh = jsonObject.getString("fadjh");

    String enrollDate1, enrollDate2;

    Map<String, Object> outMap = new HashMap<String, Object>();
    outMap.put("uuid", map.get("uuid"));
    if (chepNu != null && !chepNu.equals(""))
        chepNu = chepNu.toUpperCase();// www .ja v  a2s . c o m
    else
        return queryBaseData2(chejh, fadjh, map);

    map2map(templateData, map);

    map.put("prpCitemCar.licenseNo", chepNu);
    outMap.put("licenseNo", chepNu);

    String url = "http://10.134.136.48:8000/prpall/carInf/getDataFromCiCarInfo.do";
    String respStr = httpClientUtil.doPost(url, map, "gbk");
    System.out.println(respStr);
    Map carMap = JackJson.fromJsonToObject(respStr, Map.class);
    if (((List) carMap.get("data")).size() > 0) {
        Map data = (Map) ((List) carMap.get("data")).get(0);
        map.put("prpCitemCar.frameNo", (String) data.get("rackNo"));
        outMap.put("frameNo", data.get("rackNo"));
        map.put("prpCitemCar.vinNo", (String) data.get("rackNo"));
        outMap.put("vinNo", data.get("rackNo"));
        map.put("prpCitemCar.engineNo", (String) data.get("engineNo"));
        outMap.put("engineNo", data.get("engineNo"));
        map.put("prpCitemCar.enrollDate",
                timeStamp2Date("" + (Long) ((Map) data.get("enrollDate")).get("time"), "yyyy-M-d"));
        outMap.put("enrollDate", map.get("prpCitemCar.enrollDate"));

        // 
        enrollDate1 = map.get("prpCitemCar.enrollDate");

        int eny = 0;
        try {
            eny = new SimpleDateFormat("yyyy-M-d").parse(map.get("prpCitemCar.enrollDate")).getYear();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        map.put("prpCitemCar.useYears", "" + (new Date().getYear() - eny));
        outMap.put("useYears", map.get("prpCitemCar.useYears"));

        map.put("prpCcarShipTax.prePayTaxYear", "" + (Calendar.getInstance().get(Calendar.YEAR) - 1));
        map.put("prpCitemCar.carKindCode", "A01");
        //map.put("prpCitemCar.carKindCode", (String)data.get("carKindCode"));
        map.put("CarKindCodeDes", carTypeMap.get((String) data.get("carKindCode")));
        if (StringUtils.startsWith(((String) data.get("carKindCode")), "K")) {
            map.put("prpCitemCar.licenseType", "80");
        } else if (StringUtils.startsWith(((String) data.get("carKindCode")), "M")) {
            map.put("prpCitemCar.licenseType", "81");
        } else {
            map.put("prpCitemCar.licenseType", (String) ((Map) data.get("id")).get("licenseType"));
        }
        outMap.put("licenseType", map.get("prpCitemCar.licenseType"));

        String carOwner = (String) data.get("carOwner");
        if (null != carOwner) {
            map.put("insuredCarOwner", carOwner);
            outMap.put("insuredCarOwner", map.get("insuredCarOwner"));
            map.put("prpCinsureds[0].insuredName", carOwner);
            outMap.put("insuredName", map.get("prpCinsureds[0].insuredName"));
            map.put("owner", carOwner);
            outMap.put("owner", map.get("owner"));
            map.put("prpCcarShipTax.taxPayerName", carOwner);
        }

        String tonCount = data.get("tonCount") == null ? "0" : data.get("tonCount") + "";
        map.put("prpCitemCar.tonCount", tonCount);
        //         outMap.put("tonCount", map.get("prpCitemCar.tonCount"));

        String seatCount = "" + (Integer) data.get("seatCount");
        if (StringUtils.isNotBlank(seatCount)) {
            map.put("prpCitemCar.seatCount", seatCount);
            outMap.put("seatCount", map.get("prpCitemCar.seatCount"));
        }

    } else
        return "{\"success\": flase, \"msg\": \"" + chepNu + "\"}";
    ;

    url = "http://10.134.136.48:8000/prpall/carInf/getCarModelInfo.do";
    respStr = httpClientUtil.doPost(url, map, "gbk");
    System.out.println(respStr);

    Map car2Map = JackJson.fromJsonToObject(respStr, Map.class);

    List<Map> dataList = (List<Map>) car2Map.get("data");
    if (dataList.size() > 0) {
        Map itemMap = dataList.get(0);
        if (itemMap.get("refCode2") != null && !itemMap.get("refCode2").equals(""))
            return "{\"success\": flase, \"msg\": \"" + itemMap.get("refCode2") + "\"}";

        map.put("prpCitemCar.brandName", (String) itemMap.get("modelName"));
        outMap.put("brandName", map.get("prpCitemCar.brandName"));
        map.put("prpCitemCar.countryNature", (String) itemMap.get("vehicleType"));
        map.put("prpCitemCar.modelCode", (String) itemMap.get("modelCode"));
        outMap.put("modelCode", map.get("prpCitemCar.modelCode"));
        map.put("CarActualValueTrue", "" + itemMap.get("replaceMentValue"));
        map.put("prpCitemCar.purchasePrice", "" + itemMap.get("replaceMentValue"));
        map.put("purchasePriceOld", "" + itemMap.get("replaceMentValue"));

        if (itemMap.get("disPlaceMent") != null) {
            map.put("prpCitemCar.exhaustScale",
                    "" + Integer.parseInt(itemMap.get("disPlaceMent") + "") / 1000.00);
        } else {
            map.put("prpCitemCar.exhaustScale", "");
        }
        outMap.put("exhaustScale", map.get("prpCitemCar.exhaustScale"));

        if (!map.get("comCode").startsWith("11")) {
            System.out.println("comCode 11");
            return null;
        } else {
            String seatCount = map.get("prpCitemCar.seatCount");
            String l = "" + itemMap.get("rateDPassengercapacity");
            String w = map.get("riskCode");
            if (seatCount.equals("0") || seatCount.equals("") && l != null) {
                map.put("prpCitemCar.seatCount", l);
            }
            if ("DAV".equals(w) && Integer.parseInt(seatCount) >= 9) {
                map.put("prpCitemCar.brandName", "");
                map.put("prpCitemCar.modelCode", "");
            }
            String F = itemMap.get("tonnage") == null ? "0" : itemMap.get("tonnage") + "";
            if (F != null && (map.get("prpCitemCar.tonCount").equals("0")
                    || map.get("prpCitemCar.tonCount").equals(""))) {
                map.put("prpCitemCar.tonCount", F);
            }
            map.put("prpCitemCar.modelDemandNo", (String) itemMap.get("modelCode"));
            map.put("prpCitemCar.modelDemandNo", (String) ((Map) itemMap.get("id")).get("pmQueryNo"));
            map.put("isQueryCarModelFlag", "1");
        }
        map.put("_insuredName", (String) itemMap.get("owner"));

        url = "http://10.134.136.48:8000/prpall/business/calActualValue.do";
        respStr = httpClientUtil.doPost(url, map, "gbk");
        System.out.println(respStr);

        map.put("prpCitemCar.actualValue", respStr);
        outMap.put("actualValue", respStr);
        map.put("premiumChangeFlag", "1");

    } else {
        System.out.println("getCarModelInfo ");
        return null;
    }

    // 
    url = "http://10.134.136.48:8000/prpall/business/selectRenewal.do";
    Map<String, String> map4xub = null;
    try {
        map4xub = parse2Map("prpCrenewalVo.licenseNo=" + chepNu + "&prpCrenewalVo.licenseType=02");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    respStr = httpClientUtil.doPost(url, map4xub, "GBK");

    String lastPolicyNo = "";
    JSONObject jObj = JSONObject.fromObject(respStr);
    JSONArray jdatas = jObj.getJSONArray("data");
    Iterator<Object> it = jdatas.iterator();
    while (it.hasNext()) {
        JSONObject obj = (JSONObject) it.next();
        lastPolicyNo = obj.getString("policyNo");
    }

    //outMap.put("lastPolicyNo", lastPolicyNo);
    System.out.println("lastPolicyNo: " + lastPolicyNo);

    Map<String, Object> xubCopyMap = new HashMap<String, Object>();
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    if (!lastPolicyNo.equals("")) {
        url = "http://10.134.136.48:8000/prpall/business/quickProposalEditRenewalCopy.do?bizNo=" + lastPolicyNo;
        System.out.println(": " + url);
        respStr = httpClientUtil.doPost(url, new HashMap<String, String>(), "GBK");

        //         PrintWriter out;
        //         try {
        //            out = new PrintWriter("d:\\1.html");
        //            out.write(respStr);
        //            respStr2 = readFile2Strng("d:\\1.html");
        //            
        //         } catch (Exception e) {
        //            // TODO Auto-generated catch block
        //            e.printStackTrace();
        //         }

        //         write2Html(respStr);

        Document doc = Jsoup.parse(respStr);

        //if(doc.getElementById("prpCitemCar.licenseNo") != null) {
        //return "{\"success\": flase, \"msg\": \"\"}";

        if (doc.getElementById("prpCmainHeadInput") != null) {
            String lastYearBaoQi = "";
            Elements elements = doc.select("#prpCmainHeadInput strong");
            for (Element element : elements) {
                if (element.toString().contains("")) {
                    lastYearBaoQi = element.text();
                    break;
                }
            }
            System.out.println(": " + lastYearBaoQi);
            xubCopyMap.put("lastYearBaoQi", lastYearBaoQi);
        }

        if (doc.getElementById("prpCitemCar.licenseNo") != null) {
            String licenseNo = doc.getElementById("prpCitemCar.licenseNo").attr("value");
            System.out.println(": " + licenseNo);
            xubCopyMap.put("licenseNo", licenseNo);
        }

        if (doc.getElementById("prpCitemCar.modelCodeAlias") != null) {
            String modelCodeAlias = doc.getElementById("prpCitemCar.modelCodeAlias").attr("value");
            System.out.println(": " + modelCodeAlias);
            xubCopyMap.put("modelCodeAlias", modelCodeAlias);
        }

        String new_engineNo = "";
        if (doc.getElementById("prpCitemCar.engineNo") != null) {
            String engineNo = doc.getElementById("prpCitemCar.engineNo").attr("value");
            System.out.println(": " + engineNo);
            xubCopyMap.put("engineNo", engineNo);
            new_engineNo = engineNo;
        }

        String new_frameNo = "";
        if (doc.getElementById("prpCitemCar.frameNo") != null) {
            String frameNo = doc.getElementById("prpCitemCar.frameNo").attr("value");
            System.out.println(": " + frameNo);
            xubCopyMap.put("frameNo", frameNo);
            new_frameNo = frameNo;
        }

        if (doc.getElementById("prpCitemCar.useNatureCode") != null) {
            String useNatureCode = doc.getElementById("prpCitemCar.useNatureCode").attr("title");
            System.out.println(": " + useNatureCode);
            xubCopyMap.put("useNatureCode", useNatureCode);
        }

        if (doc.getElementById("prpCitemCar.enrollDate") != null) {
            String enrollDate = doc.getElementById("prpCitemCar.enrollDate").attr("value");
            System.out.println(": " + enrollDate);
            xubCopyMap.put("enrollDate", enrollDate);

            // 
            enrollDate2 = enrollDate;

            try {
                Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(enrollDate1);
                Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(enrollDate2);

                if (!date1.equals(date2)) {
                    System.out.println("");
                    System.out.println(": " + new_frameNo + "\t: " + new_engineNo);

                    return queryBaseData2(new_frameNo, new_engineNo, map);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (doc.getElementById("prpCitemCar.modelCode") != null) {
            String modelCode = doc.getElementById("prpCitemCar.modelCode").attr("value");
            System.out.println(": " + modelCode);
            xubCopyMap.put("modelCode", modelCode);
        }

        if (doc.getElementById("prpCitemCar.purchasePrice") != null) {
            String purchasePrice = doc.getElementById("prpCitemCar.purchasePrice").attr("value");
            System.out.println(": " + purchasePrice);
            xubCopyMap.put("purchasePrice", purchasePrice);
        }

        if (doc.getElementById("prpCitemCar.seatCount") != null) {
            String seatCount = doc.getElementById("prpCitemCar.seatCount").attr("value");
            System.out.println("(): " + seatCount);
            xubCopyMap.put("seatCount", seatCount);
        }

        if (doc.getElementById("prpCitemCar.exhaustScale") != null) {
            String exhaustScale = doc.getElementById("prpCitemCar.exhaustScale").attr("value");
            System.out.println("/(): " + exhaustScale);
            xubCopyMap.put("exhaustScale", exhaustScale);
        }

        if (doc.getElementById("prpCinsureds[0].insuredName") != null) {
            String insuredName = doc.getElementById("prpCinsureds[0].insuredName").attr("value");
            System.out.println(": " + insuredName);
            xubCopyMap.put("insuredName", insuredName);
        }

        if (doc.getElementById("prpCinsureds[0].identifyNumber") != null) {
            String identifyNumber = doc.getElementById("prpCinsureds[0].identifyNumber").attr("value");
            System.out.println(": " + identifyNumber);
            xubCopyMap.put("identifyNumber", identifyNumber);
        }

        if (doc.getElementById("prpCinsureds[0].insuredAddress") != null) {
            String insuredAddress = doc.getElementById("prpCinsureds[0].insuredAddress").attr("value");
            System.out.println(": " + insuredAddress);
            xubCopyMap.put("insuredAddress", insuredAddress);
        }

        if (doc.getElementById("prpCinsureds[0].mobile") != null) {
            String mobile = doc.getElementById("prpCinsureds[0].mobile").attr("value");
            System.out.println(": " + mobile);
            xubCopyMap.put("mobile", mobile);
        }

        System.out.println();

        Element element = null;
        for (int i = 0; i < 11; i++) {
            Map<String, String> xianzMap = new HashMap<String, String>();

            element = doc.getElementById("prpCitemKindsTemp[" + i + "].chooseFlag");
            //            System.out.println(element.toString());
            String xianz = "";
            if (element != null)
                xianz = element.attr("checked");

            //            if(xianz.equals(""))
            //               continue;

            if (i == 0)
                xianzMap.put("A", xianz);
            if (i == 1)
                xianzMap.put("G", xianz);
            if (i == 2)
                xianzMap.put("B", xianz);
            if (i == 3)
                xianzMap.put("D11", xianz);
            if (i == 4)
                xianzMap.put("D12", xianz);
            if (i == 5)
                xianzMap.put("L", xianz);
            if (i == 6)
                xianzMap.put("F", xianz);
            if (i == 8)
                xianzMap.put("Z", xianz);
            if (i == 9)
                xianzMap.put("X1", xianz);

            element = doc.getElementById("prpCitemKindsTemp[" + i + "].specialFlag");
            String bujmp = "";
            if (element != null)
                bujmp = element.attr("checked");
            xianzMap.put("bujmp", bujmp);

            element = doc.getElementById("prpCitemKindsTemp[" + i + "].amount");
            String amount = "";
            if (element != null)
                amount = element.attr("value");
            xianzMap.put("amount", amount);

            element = doc.getElementById("prpCitemKindsTemp[" + i + "].modeCode");
            String modeCode = "";
            if (element != null) {
                Elements tmp = element.select("option");
                for (Element et : tmp) {
                    System.out.println(et.toString());
                    if (et.hasAttr("selected")) {
                        modeCode = tmp.get(0).attr("value");
                        break;
                    }
                }
            }
            xianzMap.put("modeCode", modeCode);

            System.out.print(i + ": " + xianz);
            System.out.print("\t\tbujmp: " + bujmp);
            System.out.println("\t\tamount: " + amount);
            System.out.println("\t\tmodeCode: " + modeCode);

            list.add(xianzMap);
        }
    }

    xubCopyMap.put("xianZDetail", list);

    outMap.put("xubCopy", xubCopyMap);
    //      map2mapEx(map, outMap);

    return JSONObject.fromObject(outMap) + "";
}

From source file:org.sakaiproject.signup.tool.jsf.NewSignupMeetingBean.java

/**
 * This is a validator to make sure that the event/meeting starting time is
 * before ending time./*www  .ja va2 s .c o  m*/
 * 
 * @param e
 *            an ActionEvent object.
 */

public void validateNewMeeting(ActionEvent e) {
    if (currentStepHiddenInfo == null)
        return;

    String step = (String) currentStepHiddenInfo.getValue();

    if (step.equals("step1")) {

        boolean locationSet = false;

        //Set Location      
        if (StringUtils.isNotBlank(customLocation)) {
            logger.debug("custom location set: " + customLocation);
            this.signupMeeting.setLocation(customLocation);
            locationSet = true;
        }

        if (!locationSet && StringUtils.isNotBlank(selectedLocation)
                && !StringUtils.equals(selectedLocation, Utilities.rb.getString("select_location"))) {
            this.signupMeeting.setLocation(selectedLocation);
            logger.debug("chose a location: " + selectedLocation);
            locationSet = true;
        }

        if (!locationSet) {
            validationError = true;
            Utilities.addErrorMessage(Utilities.rb.getString("event.location_not_assigned"));
            return;
        }

        //Set Category   
        //custom
        if (StringUtils.isNotBlank(customCategory)) {
            this.signupMeeting.setCategory(customCategory);
        } else {
            //or from the dropdown, but if we don't choose one or left it as the 'choose category method' then don't set it
            if (!StringUtils.equals(selectedCategory, Utilities.rb.getString("select_category"))) {
                this.signupMeeting.setCategory(selectedCategory);
            }
        }

        //set instructor
        this.signupMeeting.setCreatorUserId(creatorUserId);

        Date eventEndTime = signupMeeting.getEndTime();
        Date eventStartTime = signupMeeting.getStartTime();
        /*user defined own TS case*/
        if (isUserDefinedTS()) {
            eventEndTime = getUserDefineTimeslotBean().getEventEndTime();
            eventStartTime = getUserDefineTimeslotBean().getEventStartTime();
            /*pass the value since they are null*/
            this.signupMeeting.setStartTime(eventStartTime);
            this.signupMeeting.setEndTime(eventEndTime);

            if (getUserDefineTimeslotBean().getDestTSwrpList() == null
                    || getUserDefineTimeslotBean().getDestTSwrpList().isEmpty()) {
                validationError = true;
                Utilities.addErrorMessage(Utilities.rb.getString("event.create_custom_defined_TS_blocks"));
                return;
            }

        }

        if (eventEndTime.before(eventStartTime) || eventStartTime.equals(eventEndTime)) {
            validationError = true;
            Utilities.addErrorMessage(Utilities.rb.getString("event.endTime_should_after_startTime"));
            // signupMeeting.setMeetingType(null);
            return;
        }

        setRecurrence(false);
        if (!(getRepeatType().equals(ONCE_ONLY))) {
            int repeatNum = getOccurrences();
            if ("1".equals(getRecurLengthChoice())) {
                repeatNum = CreateMeetings.getNumOfRecurrence(getRepeatType(), eventStartTime,
                        getRepeatUntil());
            }

            if ((DAILY.equals(getRepeatType()) || WEEKDAYS.equals(getRepeatType()))
                    && isMeetingOverRepeatPeriod(eventStartTime, eventEndTime, 1)) {
                validationError = true;
                Utilities.addErrorMessage(Utilities.rb.getString("crossDay.event.repeat.daily.problem"));
                return;
            }

            if (WEEKLY.equals(getRepeatType()) && isMeetingOverRepeatPeriod(eventStartTime, eventEndTime, 7)) {
                validationError = true;
                Utilities.addErrorMessage(Utilities.rb.getString("crossDay.event.repeat.weekly.problem"));
                return;
            }

            if (BIWEEKLY.equals(getRepeatType())
                    && isMeetingOverRepeatPeriod(eventStartTime, eventEndTime, 14)) {
                validationError = true;
                Utilities.addErrorMessage(Utilities.rb.getString("crossDay.event.repeat.biweekly.problem"));
                return;
            }
            // TODO need to check for weekly too?

            if (repeatNum < 1) {
                validationError = true;
                if ("1".equals(getRecurLengthChoice()))
                    Utilities.addErrorMessage(Utilities.rb.getString("event.repeatbeforestart"));
                else
                    Utilities.addErrorMessage(Utilities.rb.getString("event.repeatNnum.bigger.than.one"));

                return;
            }
            setRecurrence(true);
        }

        warnMeetingAccrossTwoDates(eventEndTime, eventStartTime);

        if (!CreateSitesGroups.isAtleastASiteOrGroupSelected(this.getCurrentSite(), this.getOtherSites())) {
            validationError = true;
            Utilities.addErrorMessage(Utilities.rb.getString("select.atleast.oneGroup"));

        }

        if (signupMeeting.getMeetingType() == null) {
            validationError = true;
            Utilities.addErrorMessage(Utilities.rb.getString("signup.validator.selectMeetingType"));
            // signupMeeting.setMeetingType(null);

        }

        /*give warning to user in the next page if the event ending time get auto adjusted due to not even-division
         * and it's not the case for custom defined time slot*/
        setEndTimeAutoAdjusted(false);
        if (!isUserDefinedTS()) {
            if (isIndividualType() && getNumberOfSlots() != 0) {
                double duration = (double) (getSignupMeeting().getEndTime().getTime()
                        - getSignupMeeting().getStartTime().getTime())
                        / (double) (MINUTE_IN_MILLISEC * getNumberOfSlots());
                if (duration != Math.floor(duration)) {
                    setEndTimeAutoAdjusted(true);
                    Utilities.addErrorMessage(Utilities.rb.getString("event_endtime_auto_adjusted_warning"));
                }
            }
        }

        /*for custom time slot case*/
        if (!validationError && isUserDefinedTS()) {
            this.signupMeeting.setStartTime(eventStartTime);
            this.signupMeeting.setEndTime(eventEndTime);
            this.signupMeeting.setMeetingType(CUSTOM_TIMESLOTS);
        }
        /*reset meetingType for step1 */
        if (!isUserDefinedTS() && CUSTOM_TIMESLOTS.equals(this.signupMeeting.getMeetingType())) {
            this.signupMeeting.setMeetingType(INDIVIDUAL);
        }

        /*pre-load all possible coordinators for step2*/
        signupMeeting
                .setSignupSites(CreateSitesGroups.getSelectedSignupSites(getCurrentSite(), getOtherSites()));
        this.allPossibleCoordinators = this.sakaiFacade
                .getAllPossbileCoordinatorsOnFastTrack(this.signupMeeting);

        // tick the creator by default (SIGNUP-216)
        for (SignupUser u : this.allPossibleCoordinators) {
            if (StringUtils.equals(u.getInternalUserId(), this.creatorUserId)) {
                u.setChecked(true);
            }
        }

    }
}

From source file:org.motechproject.server.svc.impl.RegistrarBeanImpl.java

private void sendDeliveryNotification(Patient patient) {
    // Send message to phone number of facility serving patient's community

    Facility facility = getFacilityByPatient(patient);
    if (isNotNull(facility)) {
        String phoneNumber = facility.getPhoneNumber();
        if (phoneNumber != null) {
            String messageId = null;
            NameValuePair[] nameValues = new NameValuePair[0];
            MediaType mediaType = MediaType.TEXT;
            String languageCode = "en";

            // Send immediately if not during blackout,
            // otherwise adjust time to after the blackout period
            Date currentDate = new Date();
            Date messageStartDate = adjustDateForBlackout(currentDate);
            if (currentDate.equals(messageStartDate)) {
                messageStartDate = null;
            }//from ww  w .  j  ava 2s.  c  o  m

            WebServicePatientModelConverterImpl wsModelConverter = new WebServicePatientModelConverterImpl();
            wsModelConverter.setRegistrarBean(this);
            org.motechproject.ws.Patient wsPatient = wsModelConverter.patientToWebService(patient, true);
            org.motechproject.ws.Patient[] wsPatients = new org.motechproject.ws.Patient[] { wsPatient };

            MessageDefinition messageDef = wsPatient.getCommunity() == null
                    ? getMessageDefinition("pregnancy.notification.for.patient.with.no.community")
                    : getMessageDefinition("pregnancy.notification");
            if (messageDef == null) {
                log.error("Pregnancy delivery notification message " + "does not exist");
                return;
            }

            sendStaffMessage(messageId, nameValues, phoneNumber, languageCode, mediaType,
                    messageDef.getPublicId(), messageStartDate, null, wsPatients);
        }
    }
}

From source file:org.egov.ptis.domain.service.property.PropertyExternalService.java

private Boolean between(final Date date, final Date fromDate, final Date toDate) {
    return (date.after(fromDate) || date.equals(fromDate)) && date.before(toDate) || date.equals(toDate);
}

From source file:org.apache.lens.cube.metadata.CubeMetastoreClient.java

private LatestInfo getNextLatestOfDimtable(Table hiveTable, String timeCol, final int timeColIndex,
        UpdatePeriod updatePeriod, Map<String, String> nonTimePartSpec) throws HiveException {
    // getClient().getPartitionsByNames(tbl, partNames)
    List<Partition> partitions;
    try {//from  w  ww  .j av a  2 s  .  c o m
        partitions = getClient().getPartitionsByFilter(hiveTable,
                StorageConstants.getPartFilter(nonTimePartSpec));
        filterPartitionsByUpdatePeriod(partitions, updatePeriod);
        filterPartitionsByNonTimeParts(partitions, nonTimePartSpec, timeCol);
    } catch (TException e) {
        throw new HiveException(e);
    }

    // tree set contains partitions with timestamp as value for timeCol, in
    // descending order
    TreeSet<Partition> allPartTimeVals = new TreeSet<>(new Comparator<Partition>() {
        @Override
        public int compare(Partition o1, Partition o2) {
            Date partDate1 = getPartDate(o1, timeColIndex);
            Date partDate2 = getPartDate(o2, timeColIndex);
            if (partDate1 != null && partDate2 == null) {
                return -1;
            } else if (partDate1 == null && partDate2 != null) {
                return 1;
            } else if (partDate1 == null) {
                return o2.getTPartition().compareTo(o1.getTPartition());
            } else if (!partDate2.equals(partDate1)) {
                return partDate2.compareTo(partDate1);
            } else {
                return o2.getTPartition().compareTo(o1.getTPartition());
            }
        }
    });
    for (Partition part : partitions) {
        if (!isLatestPartOfDimtable(part)) {
            Date partDate = getPartDate(part, timeColIndex);
            if (partDate != null) {
                allPartTimeVals.add(part);
            }
        }
    }
    Iterator<Partition> it = allPartTimeVals.iterator();
    it.next(); // Skip itself. We have to find next latest.
    LatestInfo latest = null;
    if (it.hasNext()) {
        Partition nextLatest = it.next();
        latest = new LatestInfo();
        latest.setPart(nextLatest);
        Map<String, String> latestParams = LensUtil.getHashMap(getLatestPartTimestampKey(timeCol),
                nextLatest.getValues().get(timeColIndex));
        latest.addLatestPartInfo(timeCol, new LatestPartColumnInfo(latestParams));
    }
    return latest;
}

From source file:org.apache.lens.cube.metadata.CubeMetastoreClient.java

/**
 * Add a partition specified by the storage partition desc on the storage passed.
 *
 * @param cubeTableName   cube fact/dimension table name
 * @param storageName     storage name//from  w ww .  j  a  va 2  s  .c  o m
 * @param timePartSpec    time partitions
 * @param nonTimePartSpec non time partitions
 * @param updatePeriod    update period of the partition
 * @throws HiveException
 */
public void dropPartition(String cubeTableName, String storageName, Map<String, Date> timePartSpec,
        Map<String, String> nonTimePartSpec, UpdatePeriod updatePeriod) throws HiveException, LensException {
    String storageTableName = getStorageTableName(cubeTableName.trim(), storageName, updatePeriod);
    Table hiveTable = getHiveTable(storageTableName);
    List<FieldSchema> partCols = hiveTable.getPartCols();
    List<String> partColNames = new ArrayList<>(partCols.size());
    List<String> partVals = new ArrayList<>(partCols.size());
    for (FieldSchema column : partCols) {
        partColNames.add(column.getName());
        if (timePartSpec.containsKey(column.getName())) {
            partVals.add(updatePeriod.format(timePartSpec.get(column.getName())));
        } else if (nonTimePartSpec.containsKey(column.getName())) {
            partVals.add(nonTimePartSpec.get(column.getName()));
        } else {
            throw new HiveException("Invalid partspec, missing value for" + column.getName());
        }
    }
    if (isDimensionTable(cubeTableName)) {
        String timePartColsStr = hiveTable.getTTable().getParameters()
                .get(MetastoreConstants.TIME_PART_COLUMNS);
        Map<String, LatestInfo> latest = new HashMap<>();
        boolean latestAvailable = false;
        if (timePartColsStr != null) {
            List<String> timePartCols = Arrays.asList(StringUtils.split(timePartColsStr, ','));
            for (String timeCol : timePartSpec.keySet()) {
                if (!timePartCols.contains(timeCol)) {
                    throw new HiveException("Not a time partition column:" + timeCol);
                }
                int timeColIndex = partColNames.indexOf(timeCol);
                Partition part = getLatestPart(storageTableName, timeCol, nonTimePartSpec);

                Date latestTimestamp = getLatestTimeStampFromPartition(part, timeCol);
                Date dropTimestamp;
                try {
                    dropTimestamp = updatePeriod.parse(updatePeriod.format(timePartSpec.get(timeCol)));
                } catch (ParseException e) {
                    throw new HiveException(e);
                }
                // check if partition being dropped is the latest partition
                boolean isLatest = latestTimestamp != null && dropTimestamp.equals(latestTimestamp);
                if (isLatest) {
                    for (int i = 0; i < partVals.size(); i++) {
                        if (i != timeColIndex) {
                            if (!part.getValues().get(i).equals(partVals.get(i))) {
                                isLatest = false;
                                break;
                            }
                        }
                    }
                }
                if (isLatest) {
                    LatestInfo latestInfo = getNextLatestOfDimtable(hiveTable, timeCol, timeColIndex,
                            updatePeriod, nonTimePartSpec);
                    latestAvailable = (latestInfo != null && latestInfo.part != null);
                    latest.put(timeCol, latestInfo);
                } else {
                    latestAvailable = true;
                }
            }
        } else {
            if (timePartSpec != null && !timePartSpec.isEmpty()) {
                throw new HiveException("Not time part columns" + timePartSpec.keySet());
            }
        }
        getStorage(storageName).dropPartition(getClient(), storageTableName, partVals, latest, nonTimePartSpec);
        if (!latestAvailable) {
            // dropping latest and could not find latest, removing the entry from latest lookup cache
            latestLookupCache.remove(storageTableName);
        }
    } else {
        // dropping fact partition
        getStorage(storageName).dropPartition(getClient(), storageTableName, partVals, null, null);
        if (partitionTimelineCache.updateForDeletion(cubeTableName, storageName, updatePeriod, timePartSpec)) {
            this.alterTablePartitionCache((Storage.getPrefix(storageName) + cubeTableName).toLowerCase(),
                    updatePeriod, storageTableName);
        }
    }
}