Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

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

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:org.libreplan.web.planner.order.OrderPlanningModel.java

private void dateInFutureMessage(Datebox datebox) {
    Date value = datebox.getValue();
    Date today = LocalDate.fromDateFields(new Date()).toDateTimeAtStartOfDay().toDate();
    if (value != null && (value.compareTo(today) > 0)) {
        throw new WrongValueException(datebox, _("date in the future"));
    }//from www.j  a va  2 s. co m
}

From source file:com.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.c1_publish_order);
    mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    File file = new File(newFileName());
    if (file.exists()) {
        file.delete();//  www .java  2s  .  com
    }

    Intent intent = getIntent();
    mServiceType = (SERVICE_TYPE) intent.getSerializableExtra(O2OMobileAppConst.SERVICE_TYPE);
    mDefaultReceiverId = intent.getIntExtra(DEFAULT_RECEIVER_ID, 0);
    service_list = intent.getStringExtra("service_list");

    mBack = (ImageView) findViewById(R.id.top_view_back);
    mTitle = (TextView) findViewById(R.id.top_view_title);
    mBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    });
    mArrowImage = (ImageView) findViewById(R.id.top_view_arrow_image);
    mClose = (ImageView) findViewById(R.id.top_view_right_close);
    mTitleView = (LinearLayout) findViewById(R.id.top_view_title_view);
    mServiceTypeView = (FrameLayout) findViewById(R.id.c1_publish_order_service_type_view);
    mServiceTypeListview = (ListView) findViewById(R.id.c1_publish_order_service_type_list);
    mPrice = (EditText) findViewById(R.id.c1_publish_order_price);
    mTime = (TextView) findViewById(R.id.c1_publish_order_time);
    mLocation = (EditText) findViewById(R.id.c1_publish_order_location);
    mText = (EditText) findViewById(R.id.c1_publish_order_text);
    mVoice = (Button) findViewById(R.id.c1_publish_order_voice);
    mVoicePlay = (Button) findViewById(R.id.c1_publish_order_voicePlay);
    mVoiceReset = (ImageView) findViewById(R.id.c1_publish_order_voiceReset);
    mPublish = (Button) findViewById(R.id.c1_publish_order_publish);
    mVoiceView = (FrameLayout) findViewById(R.id.c1_publish_order_voice_view);
    mVoiceAnim = (ImageView) findViewById(R.id.c1_publish_order_voice_anim);
    mVoiceAnim.setImageResource(R.anim.voice_animation);
    mAnimationDrawable = (AnimationDrawable) mVoiceAnim.getDrawable();
    mAnimationDrawable.setOneShot(false);
    mTitleView.setEnabled(false);
    mServiceTypeView.setOnClickListener(null);
    mServiceTypeListview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (mDefaultReceiverId == 0) {
                mTitle.setText(mHomeModel.publicServiceTypeList.get(position).title);
                mServiceTypeId = mHomeModel.publicServiceTypeList.get(position).id;
                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this,
                        mHomeModel.publicServiceTypeList, position);
                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            } else {
                mTitle.setText(mServiceTypeList.get(position).title);
                mServiceTypeId = mServiceTypeList.get(position).id;
                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this,
                        mServiceTypeList, position);
                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            }

        }
    });

    mTitleView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (mServiceTypeView.getVisibility() == View.GONE) {
                mServiceTypeView.setVisibility(View.VISIBLE);
                mClose.setVisibility(View.VISIBLE);
                mArrowImage.setImageResource(R.drawable.b4_arrow_up);
                AnimationUtil.showAnimationFromTop(mServiceTypeListview);
                closeKeyBoard();
            } else {
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            }
        }
    });

    mClose.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mClose.setVisibility(View.GONE);
            mArrowImage.setImageResource(R.drawable.b3_arrow_down);
            AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
            Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    mServiceTypeView.setVisibility(View.GONE);
                }
            };
            mHandler.sendEmptyMessageDelayed(0, 200);
        }
    });

    mPrice.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            if (s.toString().length() > 0) {
                if (s.toString().substring(0, 1).equals(".")) {
                    s = s.toString().substring(1, s.length());
                    mPrice.setText(s);
                }
            }
            if (s.toString().length() > 1) {
                if (s.toString().substring(0, 1).equals("0")) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        s = s.toString().substring(1, s.length());
                        mPrice.setText(s);
                        CharSequence charSequencePirce = mPrice.getText();
                        if (charSequencePirce instanceof Spannable) {
                            Spannable spanText = (Spannable) charSequencePirce;
                            Selection.setSelection(spanText, charSequencePirce.length());
                        }
                    }
                }
            }
            boolean flag = false;
            for (int i = 0; i < s.toString().length() - 1; i++) {
                String getstr = s.toString().substring(i, i + 1);
                if (getstr.equals(".")) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                int i = s.toString().indexOf(".");
                if (s.toString().length() - 3 > i) {
                    String getstr = s.toString().substring(0, i + 3);
                    mPrice.setText(getstr);
                    CharSequence charSequencePirce = mPrice.getText();
                    if (charSequencePirce instanceof Spannable) {
                        Spannable spanText = (Spannable) charSequencePirce;
                        Selection.setSelection(spanText, charSequencePirce.length());
                    }
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    initData();

    mHomeModel = new HomeModel(this);
    mHomeModel.addResponseListener(this);
    if (mDefaultReceiverId == 0) {
        mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
        mHomeData = mShared.getString("home_data", "");
        if ("".equals(mHomeData)) {
            mHomeModel.getServiceTypeList();
        } else {
            try {
                servicetypelistResponse response = new servicetypelistResponse();
                response.fromJson(new JSONObject(mHomeData));
                mHomeModel.publicServiceTypeList = response.services;
                setServiceTypeAdater();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (service_list != null && !"".equals(service_list)) {
            try {
                JSONObject userJson = new JSONObject(service_list);
                myservicelistResponse response = new myservicelistResponse();
                response.fromJson(userJson);
                for (int i = 0; i < response.services.size(); i++) {
                    SERVICE_TYPE service = new SERVICE_TYPE();
                    service = response.services.get(i).service_type;
                    mServiceTypeList.add(service);
                }
                if (mServiceTypeList.size() > 0) {
                    mTitleView.setEnabled(true);
                    mArrowImage.setVisibility(View.VISIBLE);
                    if (mServiceType != null) {
                        for (int i = 0; i < mServiceTypeList.size(); i++) {
                            if (mServiceType.id == mServiceTypeList.get(i).id) {
                                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList, i);
                                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                                mTitle.setText(mServiceTypeList.get(i).title);
                                mServiceTypeId = mServiceTypeList.get(i).id;
                                break;
                            }
                        }
                    } else {
                        mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList);
                        mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                        mTitle.setText(getString(R.string.select_service));
                    }

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
            mHomeData = mShared.getString("home_data", "");
            if ("".equals(mHomeData)) {
                mHomeModel.getServiceTypeList();
            } else {
                try {
                    servicetypelistResponse response = new servicetypelistResponse();
                    response.fromJson(new JSONObject(mHomeData));
                    mHomeModel.publicServiceTypeList = response.services;
                    setServiceTypeAdater();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    mLocationInfoModel = new LocationInfoModel(this);
    mLocationInfoModel.addResponseListener(this);
    mLocationInfoModel.get();

    mOrderPublishModel = new OrderPublishModel(this);
    mOrderPublishModel.addResponseListener(this);

    //??
    CharSequence charSequencePirce = mPrice.getText();
    if (charSequencePirce instanceof Spannable) {
        Spannable spanText = (Spannable) charSequencePirce;
        Selection.setSelection(spanText, charSequencePirce.length());
    }
    CharSequence charSequenceLocation = mLocation.getText();
    if (charSequenceLocation instanceof Spannable) {
        Spannable spanText = (Spannable) charSequenceLocation;
        Selection.setSelection(spanText, charSequenceLocation.length());
    }

    mVoice.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                closeKeyBoard();
                mVoice.setKeepScreenOn(true);
                mMaxTime = MAX_TIME;
                mVoiceView.setVisibility(View.VISIBLE);
                mAnimationDrawable.start();
                startRecording();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mVoice.setKeepScreenOn(false);
                mVoiceView.setVisibility(View.GONE);
                mAnimationDrawable.stop();
                if (mMaxTime > 28) {
                    mVoice.setEnabled(false);
                    Handler mHandler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            stopRecording();
                            mVoice.setEnabled(true);
                        }
                    };
                    mHandler.sendEmptyMessageDelayed(0, 500);
                } else {
                    stopRecording();
                }
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                mVoice.setKeepScreenOn(false);
                mVoiceView.setVisibility(View.GONE);
                mAnimationDrawable.stop();
                if (mMaxTime > 28) {
                    mVoice.setEnabled(false);
                    Handler mHandler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            stopRecording();
                            mVoice.setEnabled(true);
                        }
                    };
                    mHandler.sendEmptyMessageDelayed(0, 500);
                } else {
                    stopRecording();
                }
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                mVoice.getParent().requestDisallowInterceptTouchEvent(true);
            }
            return false;
        }
    });

    mVoicePlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mPlayer == null) {
                File file = new File(mFileName);
                if (file.exists()) {
                    mPlayer = new MediaPlayer();
                    mVoicePlay.setBackgroundResource(R.anim.record_animation);
                    mAnimationDrawable2 = (AnimationDrawable) mVoicePlay.getBackground();
                    mAnimationDrawable2.setOneShot(false);
                    mAnimationDrawable2.start();
                    try {
                        mPlayer.setDataSource(mFileName);
                        mPlayer.prepare();
                        mPlayer.start();
                        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                mp.reset();
                                mPlayer = null;
                                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                                mAnimationDrawable2.stop();
                            }
                        });
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(C1_PublishOrderActivity.this, getString(R.string.file_does_not_exist),
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                mPlayer.release();
                mPlayer = null;
                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                mAnimationDrawable2.stop();
            }
        }
    });

    mVoiceReset.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mPlayer != null) {
                mPlayer.release();
                mPlayer = null;
                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                mAnimationDrawable2.stop();
            }
            File file = new File(mFileName);
            if (file.exists()) {
                file.delete();
            }
            mVoice.setVisibility(View.VISIBLE);
            mVoicePlay.setVisibility(View.GONE);
            mVoiceReset.setVisibility(View.GONE);
        }
    });

    mPublish.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            File file = new File(newFileName());
            int duration = 0;
            if (file.exists()) {
                MediaPlayer mp = MediaPlayer.create(C1_PublishOrderActivity.this, Uri.parse(mFileName));
                if (null != mp) {
                    duration = mp.getDuration();//? ms
                    mp.release();
                }
                if (duration % 1000 > 500) {
                    duration = duration / 1000 + 1;
                } else {
                    duration = duration / 1000;
                }
            } else {
                file = null;
            }
            int num = 0;
            try { // ??
                Date date = new Date();
                Date date1 = mFormat.parse(mFormat.format(date));
                Date date2 = mFormat.parse(mTime.getText().toString());
                num = date2.compareTo(date1);

                if (num < 0) {
                    long diff = date1.getTime() - date2.getTime();
                    long mins = diff / (1000 * 60);
                    if (mins < 3) {
                        num = 1;
                    }
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (mServiceTypeId == 0) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.select_service));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mPrice.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.price_range));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mPrice.getText().toString().equals("0.")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.right_price));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mTime.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.appoint_time));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (num < 0) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.wrong_appoint_time_hint));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mLocation.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.appoint_location_hint));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else {
                mOrderPublishModel.publish(mPrice.getText().toString(), mTime.getText().toString(),
                        mLocation.getText().toString(), mText.getText().toString(), file, mServiceTypeId,
                        mDefaultReceiverId, duration);
            }
        }
    });
}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

protected void internalMpsLevelTransfer(int mpsSrcId, int mpsDstId) {
    generatedMPSLines = new ArrayList<MpsLine>();
    Mps mpsSrc = mpsService.load(mpsSrcId);
    Mps mpsDst = mpsService.load(mpsDstId);

    PlanningRange planningRange = calculateMPSPlanningRange(mpsDst);
    clearMPS(mpsDst);/*from ww  w  . ja  va  2  s  .c  om*/

    List<MpsLine> lines = ormTemplate
            .findByCriteria(OrmTemplate.createCriteria(MpsLine.class).add(Restrictions.eq("Mps", mpsSrc))
                    .add(Restrictions.or(Restrictions.gt("PlannedQty", BigDecimal.ZERO),
                            Restrictions.gt("AdjustmentQty", BigDecimal.ZERO)))
                    .addOrder(Order.asc("BucketOffset")));
    BucketRange bucketRange = null;
    int mpsDstSequence = 1;
    boolean firstLine = true;
    long numberOfDays = 1;
    int currentBucketOffset = 1;
    for (MpsLine mpsLine : lines) {
        //?  ?      ?  ? if-
        if (firstLine || currentBucketOffset != mpsLine.getBucketOffset()) {
            bucketRange = MfUtils.determineBucketRange(mpsSrc.getPlanningLevel().getId(),
                    mpsLine.getBucketOffset());
            //NumberOfDays = EndDay - StartDay + 1
            numberOfDays = DateTimeUtils.getDaysBetween(bucketRange.getBucketStart(),
                    bucketRange.getBucketEnd()) + 1;
            currentBucketOffset = mpsLine.getBucketOffset();
            firstLine = false;
        }

        BigDecimal remainingQty = mpsLine.getPlannedQty().add(mpsLine.getAdjustmentQty());
        // if PlanStartDay <= EndDay and PlanEndDay >= StartDay then
        // ,  ?   ? ?
        int c1 = planningRange.startPlanningDate.compareTo(bucketRange.getBucketEnd());
        int c2 = planningRange.endPlanningDate.compareTo(bucketRange.getBucketStart());
        if (c1 <= 0 && c2 >= 0) {
            long remainingNumberOfDays = numberOfDays;
            //PlanStartDay > StartDay
            if (planningRange.startPlanningDate.compareTo(bucketRange.getBucketStart()) > 0)
                remainingNumberOfDays = numberOfDays - DateTimeUtils
                        .getDaysBetween(planningRange.startPlanningDate, bucketRange.getBucketStart());

            BigDecimal srcQty = MathUtils.divide(remainingQty, new BigDecimal(remainingNumberOfDays),
                    Constants.QUANTITY_ROUND_CONTEXT);
            Date countDay = bucketRange.getBucketStart();
            //while CountDay <= EndDay
            while (MathUtils.compareToZero(remainingQty) > 0
                    && countDay.compareTo(bucketRange.getBucketEnd()) <= 0) {
                //if CountDay >= PlanStartDay and CountDay <= PlanEndDay then
                if (countDay.compareTo(planningRange.startPlanningDate) >= 0
                        && countDay.compareTo(planningRange.endPlanningDate) <= 0) {
                    RollUpMPSResult rollUpMPSResult = rollUpMPS(mpsDst, mpsLine, srcQty, countDay,
                            mpsDstSequence);
                    mpsDstSequence = rollUpMPSResult.mpsSequence; // ?
                    remainingNumberOfDays -= 1;
                    remainingQty = remainingQty.subtract(rollUpMPSResult.quan);
                    if (remainingNumberOfDays > 0)
                        srcQty = MathUtils.divide(remainingQty, new BigDecimal(remainingNumberOfDays),
                                Constants.QUANTITY_ROUND_CONTEXT);
                }
                countDay = DateTimeUtils.incDay(countDay, 1);
            }
        }
    }
    persistGeneratedMPSLines();
}

From source file:com.mediaworx.intellij.opencmsplugin.sync.SyncFileAnalyzer.java

private void handleExistingFile(OpenCmsModule ocmsModule, File file, CmisObject vfsObject, String vfsPath) {
    LOG.info("It's a file that exists on the VFS and the RFS");

    if (pullAllMetaInformation) {
        syncList.add(new SyncFile(ocmsModule, vfsPath, file, vfsObject, SyncAction.PULL, true));
    } else {//  www  .j  av a  2  s.  c o m
        Date localDate = new Date(file.lastModified());
        Date vfsDate = vfsObject.getLastModificationDate().getTime();

        if (ocmsModule.getSyncMode() == SyncMode.SYNC) {
            LOG.info("SyncMode is SYNC, so compare dates");
            if (localDate.after(vfsDate)) {
                LOG.info("RFS file is newer, PUSH");
                syncList.add(new SyncFile(ocmsModule, vfsPath, file, vfsObject, SyncAction.PUSH, true));
            } else if (vfsDate.after(localDate)) {
                LOG.info("VFS file is newer, PULL");
                syncList.add(new SyncFile(ocmsModule, vfsPath, file, vfsObject, SyncAction.PULL, true));
            } else {
                LOG.info("VFS file and RFS file have the same date, ignore");
            }
        }
        // if the dates are different, add the resource with PUSH or PULL action, depending on the module's syncMode
        else if (vfsDate.compareTo(localDate) != 0) {
            SyncAction syncAction = ocmsModule.getSyncMode() == SyncMode.PUSH ? SyncAction.PUSH
                    : SyncAction.PULL;
            LOG.info("SyncMode is " + ocmsModule.getSyncMode() + " and files are not equal, so force "
                    + syncAction);
            syncList.add(new SyncFile(ocmsModule, vfsPath, file, vfsObject, syncAction, true));
        }
    }
}

From source file:org.jasig.ssp.service.impl.EarlyAlertServiceImpl.java

@Override
public void sendAllEarlyAlertReminderNotifications() {
    Date lastResponseDate = getMinimumResponseComplianceDate();
    // if no responseDate is given no emails are sent
    if (lastResponseDate == null) {
        return;//from  w  ww . j av  a2 s  . c o  m
    }
    List<EarlyAlert> eaOutOfCompliance = dao.getResponseDueEarlyAlerts(lastResponseDate);
    LOGGER.debug("Early Alerts out of compliance: {}", eaOutOfCompliance.size());
    Map<UUID, List<EarlyAlertMessageTemplateTO>> easByCoach = new HashMap<UUID, List<EarlyAlertMessageTemplateTO>>();
    Map<UUID, Person> coaches = new HashMap<UUID, Person>();
    final boolean includeCoachAsRecipient = this.earReminderRecipientConfig.includeCoachAsRecipient();
    final boolean includeEarlyAlertCoordinatorAsRecipient = this.earReminderRecipientConfig
            .includeEarlyAlertCoordinatorAsRecipient();
    final boolean includeEarlyAlertCoordinatorAsRecipientOnlyIfStudentHasNoCoach = this.earReminderRecipientConfig
            .includeEarlyAlertCoordinatorAsRecipientOnlyIfStudentHasNoCoach();
    LOGGER.info("Config: includeCoachAsRecipient(): {}", includeCoachAsRecipient);
    LOGGER.info("Config: includeEarlyAlertCoordinatorAsRecipient(): {}",
            includeEarlyAlertCoordinatorAsRecipient);
    LOGGER.info("Config: includeEarlyAlertCoordinatorAsRecipientOnlyIfStudentHasNoCoach(): {}",
            includeEarlyAlertCoordinatorAsRecipientOnlyIfStudentHasNoCoach);
    for (EarlyAlert earlyAlert : eaOutOfCompliance) {
        final Set<Person> recipients = new HashSet<Person>();
        Person coach = earlyAlert.getPerson().getCoach();
        if (includeCoachAsRecipient) {
            if (coach == null) {
                LOGGER.warn(
                        "Early Alert with id: {} is associated with a person without a coach, so skipping email to coach.",
                        earlyAlert.getId());
            } else {
                recipients.add(coach);
            }
        }
        if (includeEarlyAlertCoordinatorAsRecipient
                || (coach == null && includeEarlyAlertCoordinatorAsRecipientOnlyIfStudentHasNoCoach)) {
            final Campus campus = earlyAlert.getCampus();
            if (campus == null) {
                LOGGER.error("Early Alert with id: {} does not have valid a campus, so skipping email to EAC.",
                        earlyAlert.getId());
            } else {
                final UUID earlyAlertCoordinatorId = campus.getEarlyAlertCoordinatorId();
                if (earlyAlertCoordinatorId == null) {
                    LOGGER.error(
                            "Early Alert with id: {} has campus with no early alert coordinator, so skipping email to EAC.",
                            earlyAlert.getId());
                } else {
                    try {
                        final Person earlyAlertCoordinator = personService.get(earlyAlertCoordinatorId);
                        if (earlyAlertCoordinator == null) { // guard against change in behavior where ObjectNotFoundException is not thrown (which we've seen)
                            LOGGER.error(
                                    "Early Alert with id: {} has campus with an early alert coordinator with a bad ID ({}), so skipping email to EAC.",
                                    earlyAlert.getId(), earlyAlertCoordinatorId);
                        } else {
                            recipients.add(earlyAlertCoordinator);
                        }
                    } catch (ObjectNotFoundException exp) {
                        LOGGER.error(
                                "Early Alert with id: {} has campus with an early alert coordinator with a bad ID ({}), so skipping email to coach because no coach can be resolved.",
                                new Object[] { earlyAlert.getId(), earlyAlertCoordinatorId, exp });
                    }
                }
            }
        }
        LOGGER.debug("Early Alert: {}; Recipients: {}", earlyAlert.getId(), recipients);
        if (recipients.isEmpty()) {
            continue;
        } else {
            for (Person person : recipients) {
                // We've definitely got a coach by this point
                if (easByCoach.containsKey(person.getId())) {
                    final List<EarlyAlertMessageTemplateTO> coachEarlyAlerts = easByCoach.get(person.getId());
                    coachEarlyAlerts.add(createEarlyAlertTemplateTO(earlyAlert));
                } else {
                    coaches.put(person.getId(), person);
                    final ArrayList<EarlyAlertMessageTemplateTO> eam = Lists.newArrayList();
                    eam.add(createEarlyAlertTemplateTO(earlyAlert)); // add separately from newArrayList() call else list will be sized to 1
                    easByCoach.put(person.getId(), eam);
                }
            }
        }
        List<WatchStudent> watchers = earlyAlert.getPerson().getWatchers();
        for (WatchStudent watcher : watchers) {
            if (easByCoach.containsKey(watcher.getPerson().getId())) {
                final List<EarlyAlertMessageTemplateTO> coachEarlyAlerts = easByCoach
                        .get(watcher.getPerson().getId());
                coachEarlyAlerts.add(createEarlyAlertTemplateTO(earlyAlert));
            } else {
                coaches.put(watcher.getPerson().getId(), watcher.getPerson());
                final ArrayList<EarlyAlertMessageTemplateTO> eam = Lists.newArrayList();
                eam.add(createEarlyAlertTemplateTO(earlyAlert)); // add separately from newArrayList() call else list will be sized to 1
                easByCoach.put(watcher.getPerson().getId(), eam);
            }
        }
    }
    for (UUID coachId : easByCoach.keySet()) {
        Map<String, Object> messageParams = new HashMap<String, Object>();

        Collections.sort(easByCoach.get(coachId), new Comparator<EarlyAlertTO>() {
            @Override
            public int compare(EarlyAlertTO p1, EarlyAlertTO p2) {
                Date p1Date = p1.getLastResponseDate();
                if (p1Date == null)
                    p1Date = p1.getCreatedDate();
                Date p2Date = p2.getLastResponseDate();
                if (p2Date == null)
                    p2Date = p2.getCreatedDate();
                return p1Date.compareTo(p2Date);
            }

        });

        Integer daysSince1900ResponseExpected = DateTimeUtils.daysSince1900(lastResponseDate);
        List<Pair<EarlyAlertMessageTemplateTO, Integer>> earlyAlertTOPairs = new ArrayList<Pair<EarlyAlertMessageTemplateTO, Integer>>();
        for (EarlyAlertMessageTemplateTO ea : easByCoach.get(coachId)) {
            Integer daysOutOfCompliance;
            if (ea.getLastResponseDate() != null) {
                daysOutOfCompliance = daysSince1900ResponseExpected
                        - DateTimeUtils.daysSince1900(ea.getLastResponseDate());
            } else {
                daysOutOfCompliance = daysSince1900ResponseExpected
                        - DateTimeUtils.daysSince1900(ea.getCreatedDate());
            }

            // Just in case attempt to only send emails for EA full day out of compliance
            if (daysOutOfCompliance >= 0)
                earlyAlertTOPairs.add(new Pair<EarlyAlertMessageTemplateTO, Integer>(ea, daysOutOfCompliance));
        }
        messageParams.put("earlyAlertTOPairs", earlyAlertTOPairs);
        messageParams.put("coach", coaches.get(coachId));
        messageParams.put("DateTimeUtils", DateTimeUtils.class);
        messageParams.put("termToRepresentEarlyAlert",
                configService.getByNameEmpty("term_to_represent_early_alert"));

        SubjectAndBody subjAndBody = messageTemplateService
                .createEarlyAlertResponseRequiredToCoachMessage(messageParams);
        try {
            messageService.createMessage(coaches.get(coachId), null, subjAndBody);
        } catch (Exception exp) {
            LOGGER.error(
                    "Unable to send reminder emails to coach: " + coaches.get(coachId).getFullName() + "\n",
                    exp);
        }
    }

}

From source file:org.sofun.core.kup.KupImpl.java

/**
 * Returns the Kup's last betable event start date.
 * //  ww  w.  j a  v a2s.  co  m
 * <p>
 * 
 * Returns the specified start date of the Kup if no events and / or start
 * date of events are unknown
 * 
 * @return a {@link Date} instance.
 */
private Date getLastEventStartDate() {
    Date d = null;
    for (TournamentSeason season : getBettableTournaments()) {
        Date startDate = season.getStartDate();
        if (startDate != null) {
            if (d == null) {
                d = startDate;
            } else {
                if (startDate.compareTo(d) > 0) {
                    d = startDate;
                }
            }
        }
    }
    for (TournamentStage stage : getBettableStages()) {
        Date startDate = stage.getStartDate();
        if (startDate != null) {
            if (d == null) {
                d = startDate;
            } else {
                if (startDate.compareTo(d) > 0) {
                    d = startDate;
                }
            }
        }
    }
    for (TournamentRound round : getBettableRounds()) {
        Date startDate = round.getStartDate();
        if (startDate != null) {
            if (d == null) {
                d = startDate;
            } else {
                if (startDate.compareTo(d) > 0) {
                    d = startDate;
                }
            }
        }
    }
    for (TournamentGame game : getBettableGames()) {
        Date startDate = game.getStartDate();
        if (startDate != null) {
            if (d == null) {
                d = startDate;
            } else {
                if (startDate.compareTo(d) > 0) {
                    d = startDate;
                }
            }
        }
    }
    return d;
}

From source file:com.rapidminer.tools.Tools.java

/**
 * Returns <code>true</code> if date d1 is equal to date d2. Returns <code>false</code> if
 * either d1 or d2 is <code>null</code> or dates are not equal.
 *//* ww w.  jav  a2  s  .  co m*/
public static boolean isEqual(Date d1, Date d2) {
    if (d1 == d2) {
        return true;
    }
    if (d1 == null || d2 == null) {
        return false;
    }
    return d1.compareTo(d2) == 0;
}

From source file:gov.utah.dts.det.ccl.service.impl.FacilityServiceImpl.java

@Override
public Facility deactivateFacility(Facility facility, PickListValue reason, Date effectiveDate)
        throws CclServiceException {
    if (facility != null && facility.getStatus() != FacilityStatus.INACTIVE) {
        if (facility.getStatus() != FacilityStatus.IN_PROCESS && reason == null) {
            throw new IllegalArgumentException("Reason must not be null");
        }//from   w w  w .ja  va  2s .c o  m

        if (facility.getStatus() == FacilityStatus.IN_PROCESS) {
            // delete all in process licenses
            for (Iterator<License> itr = facility.getLicenses().iterator(); itr.hasNext();) {
                License lic = itr.next();
                if (lic.getStatus() != null
                        && lic.getStatus().getValue().equalsIgnoreCase(LICENSE_STATUS_IN_PROCESS)) {
                    itr.remove();
                }
            }
            facility.setStatus(FacilityStatus.INACTIVE);
            facility = facilityDao.save(facility);
        } else {
            Date now = new Date();

            Date eDate = effectiveDate == null ? now : effectiveDate;

            // make sure the deactivation can't happen too far in the past
            if (eDate.compareTo(DateUtils.addDays(now, -60)) < 0) {
                throw new CclServiceException("Unable to deactivate facility",
                        "error.facility.deactivate.past-retroactive-deadline");
            }

            facility = performDeactivation(facility, reason, eDate);
        }
    }

    return facility;
}

From source file:de.hybris.platform.ytelcoacceleratorstorefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/subscriptionBillingActivity", method = RequestMethod.GET)
public String viewSubscriptionBillingActivity(
        @RequestParam(value = "subscriptionId", required = true) final String subscriptionId, final Model model)
        throws CMSItemNotFoundException {
    try {/*from   ww  w .j a  v a2  s .c om*/
        // retrieve subscription
        final SubscriptionData subscriptionData = subscriptionFacade.getSubscription(subscriptionId);
        model.addAttribute("subscriptionData", subscriptionData);

        // create breadcrumbs
        final List<Breadcrumb> breadcrumbs = accountBreadcrumbBuilder.getBreadcrumbs(null);
        breadcrumbs.add(new Breadcrumb("/my-account/subscriptions", getMessageSource()
                .getMessage("text.account.subscriptions", null, getI18nService().getCurrentLocale()), null));
        breadcrumbs.add(new Breadcrumb("/my-account/subscription/" + subscriptionData.getId(),
                getMessageSource().getMessage("text.account.subscription.subscriptionBreadcrumb",
                        new Object[] { subscriptionData.getId() }, "Subscription {0}",
                        getI18nService().getCurrentLocale()),
                null));
        model.addAttribute("breadcrumbs", breadcrumbs);

        // retrieve and sort billing activities
        final List<SubscriptionBillingData> billingActivities = subscriptionFacade
                .getBillingActivityList(subscriptionId, MapUtils.EMPTY_MAP);

        Collections.sort(billingActivities, new Comparator<SubscriptionBillingData>() {
            @Override
            public int compare(final SubscriptionBillingData billingData1,
                    final SubscriptionBillingData billingData2) {
                final DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
                try {
                    final Date date1 = dateFormat.parse(billingData1.getBillingDate());
                    final Date date2 = dateFormat.parse(billingData2.getBillingDate());
                    return -date1.compareTo(date2);
                } catch (final ParseException e) {
                    LOG.warn(
                            "Unable to parse billing date. Billing activities will probably not be sorted properly",
                            e);
                    return 1;
                }
            }
        });

        model.addAttribute("billingActivities", billingActivities);
    } catch (final SubscriptionFacadeException e) {
        LOG.warn("Viewing billing activities for subscriptions failed. Returning to subscription details page.",
                e);
        return REDIRECT_MY_ACCOUNT_SUBSCRIPTION + subscriptionId;
    }

    storeCmsPageInModel(model, getContentPageForLabelOrId(SUBSCRIPTION_BILLING_ACTIVITY_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(SUBSCRIPTION_BILLING_ACTIVITY_CMS_PAGE));
    model.addAttribute("metaRobots", "no-index,no-follow");
    return ControllerConstants.Views.Pages.Account.AccountSubscriptionBillingActivityPage;
}

From source file:org.egov.works.services.AbstractEstimateService.java

public boolean checkForBudgetaryAppropriationForDepositWorks(final FinancialDetail financialDetail,
        final String appropriationNumber) throws ValidationException {
    boolean flag = false;
    final Date appDate = new Date();
    double depApprAmnt = 0.0;
    final Accountdetailtype accountdetailtype = worksService.getAccountdetailtypeByName("DEPOSITCODE");

    // In case of deposit work whole amount will be appropriated at once.
    if (appDate.compareTo(financialDetail.getAbstractEstimate().getEstimateDate()) >= 0)
        depApprAmnt = financialDetail.getAbstractEstimate().getTotalAmount().getValue();

    final BigDecimal creditBalance = egovCommon.getDepositAmountForDepositCode(new Date(),
            financialDetail.getCoa().getGlcode(), financialDetail.getFund().getCode(),
            accountdetailtype.getId(),/*from  w w w  .jav a2 s  .co  m*/
            financialDetail.getAbstractEstimate().getDepositCode().getId().intValue());
    BigDecimal utilizedAmt = depositWorksUsageService.getTotalUtilizedAmountForDepositWorks(financialDetail,
            appDate);
    BigDecimal balance = BigDecimal.ZERO;
    if (utilizedAmt == null) {
        balance = creditBalance;
        utilizedAmt = BigDecimal.ZERO;
    } else
        balance = creditBalance.subtract(utilizedAmt);

    if (balance.doubleValue() >= depApprAmnt) {
        DepositWorksUsage depositWorksUsage = new DepositWorksUsage();
        final CFinancialYear budgetApprDate_finYear = financialYearHibernateDAO.getFinYearByDate(appDate);
        depositWorksUsage.setTotalDepositAmount(creditBalance);
        depositWorksUsage.setConsumedAmount(new BigDecimal(depApprAmnt));
        depositWorksUsage.setReleasedAmount(BigDecimal.ZERO);
        depositWorksUsage.setAppropriationNumber(appropriationNumber);
        depositWorksUsage.setAbstractEstimate(financialDetail.getAbstractEstimate());
        depositWorksUsage.setAppropriationDate(appDate);
        depositWorksUsage.setFinancialYear(budgetApprDate_finYear);
        depositWorksUsage.setDepositCode(financialDetail.getAbstractEstimate().getDepositCode());
        depositWorksUsage.setCoa(financialDetail.getCoa());
        depositWorksUsage = depositWorksUsageService.persist(depositWorksUsage);
        persistDepositCodeAppDetails(depositWorksUsage);
        flag = true;
    }
    return flag;
}