Example usage for org.joda.time Duration Duration

List of usage examples for org.joda.time Duration Duration

Introduction

In this page you can find the example usage for org.joda.time Duration Duration.

Prototype

public Duration(ReadableInstant start, ReadableInstant end) 

Source Link

Document

Creates a duration from the given interval endpoints.

Usage

From source file:com.almende.pi5.common.PowerTimeLine.java

License:Apache License

/**
 * Clear to zero starting at start (inclusive).
 *
 * @param start/*from   ww  w.  jav a  2 s .c  om*/
 *            the start
 * @return this for chaining
 */
public PowerTimeLine zeroFrom(final DateTime start) {
    if (this.series.size() == 0) {
        return this;
    }
    final long startOffset = new Duration(this.timestamp, start).getMillis();
    // remove all values with index after start incl
    final Iterator<PowerTime> iter = this.series.iterator();
    int index = 0;
    while (iter.hasNext()) {
        final PowerTime item = iter.next();
        final long offset = item.getOffset();
        if (offset < startOffset) {
            index++;
        } else if (offset >= startOffset) {
            iter.remove();
        }
    }
    // Add zero at start
    this.series.add(index, new PowerTime(startOffset, 0));
    return this;
}

From source file:com.almende.pi5.common.PowerTimeLine.java

License:Apache License

/**
 * Clear to zero before start (exclusive).
 *
 * @param start// w w w.j  a  v  a 2 s  .  co  m
 *            the start
 * @return this for chaining
 */
public PowerTimeLine zeroBefore(final DateTime start) {
    if (this.series.size() == 0) {
        return this;
    }
    final long startOffset = new Duration(this.timestamp, start).getMillis();
    final double startVal = getValueAt(start);
    // remove all values with index before start incl
    final Iterator<PowerTime> iter = this.series.iterator();
    while (iter.hasNext()) {
        final PowerTime item = iter.next();
        final long offset = item.getOffset();
        if (offset <= startOffset) {
            iter.remove();
        } else {
            break;
        }
    }
    // Add value at start
    this.series.add(0, new PowerTime(startOffset, startVal));
    return this;
}

From source file:com.almende.pi5.common.PowerTimeLine.java

License:Apache License

/**
 * With timestamp./* w  w w  . j  ava  2  s .  c  om*/
 *
 * @param timestamp
 *            the timestamp
 * @return the power time line
 */
public PowerTimeLine withTimestamp(DateTime timestamp) {
    final DateTime oldTimestamp = this.timestamp;
    this.timestamp = timestamp;
    if (oldTimestamp != null && !oldTimestamp.equals(timestamp) && series.size() > 0) {
        long diff = new Duration(timestamp, oldTimestamp).getMillis();
        for (PowerTime pt : series) {
            pt.setOffset(pt.getOffset() + diff);
        }
    }
    return this;
}

From source file:com.almende.pi5.lch.DERSimAgent.java

License:Apache License

/**
 * Gets the current consumption.//w w  w  .  jav  a2s  .  c om
 *
 * @return the current consumption
 */
private Double getConsumption(final DateTime time) {
    final long distance = Math.abs(new Duration(currentTimeslot, time).getMillis());

    double offsetFactor = 1.0;
    if (distance > TIMESLOTLENGTH) {
        offsetFactor = TIMESLOTLENGTH / distance;
    }

    return Math.max(0, Math.min(maxConsumption,
            getGoalConsumption(time) + (trickOffset + currentRandomOffset) * offsetFactor));
}

From source file:com.almende.pi5.lch.DERSimAgent.java

License:Apache License

@Override
public PowerProfile generateReport() {
    final PowerProfile profile = new PowerProfile(currentTimeslot);
    final PowerTimeLine demand = new PowerTimeLine(currentTimeslot);
    final PowerTimeLine max = new PowerTimeLine(currentTimeslot);
    final PowerTimeLine min = new PowerTimeLine(currentTimeslot);
    final String cat = getCategory().name();
    final DateTime now = DateTime.now();

    // Get current report and add the new info/ remove past
    int offset = -TIMESLOTLENGTH;
    long endOffset = new Duration(currentTimeslot, currentTimeslot.plus(forecastHorizon)).getMillis();
    while (offset < endOffset) {
        final Double consumption = getConsumption(currentTimeslot.plus(offset));
        demand.getSeries().add(new PowerTime(offset, consumption));
        max.getSeries().add(new PowerTime(offset,
                getMaxFlexibility(consumption, getBaseConsumption(currentTimeslot.plus(offset)))));
        min.getSeries().add(new PowerTime(offset,
                getMinFlexibility(consumption, getBaseConsumption(currentTimeslot.plus(offset)))));
        offset += TIMESLOTLENGTH;//from   w  w  w.  j  a  v  a2  s.  c o  m
    }
    if (currentReport != null) {
        demand.merge(currentReport.getCategoryProfile(cat).getDemand(), currentTimeslot.minus(TIMESLOTLENGTH),
                now);
        max.merge(currentReport.getCategoryProfile(cat).getExpectedFlexibilityMaxInWatts(),
                currentTimeslot.minus(TIMESLOTLENGTH), now);
        min.merge(currentReport.getCategoryProfile(cat).getExpectedFlexibilityMinInWatts(),
                currentTimeslot.minus(TIMESLOTLENGTH), now);
        LOG.fine("Adding historical data:" + currentTimeslot.minus(TIMESLOTLENGTH) + " -> " + now);
    }

    profile.getCategoryProfile(cat).setDemand(demand.compact());
    if (this.modus.equals(ControlMode.ABSTAIN)) {
        // No flexibility available if not participating.
        profile.getCategoryProfile(cat).setExpectedFlexibilityMaxInWatts(demand.compact());
        profile.getCategoryProfile(cat).setExpectedFlexibilityMinInWatts(demand.compact());
    } else {
        profile.getCategoryProfile(cat).setExpectedFlexibilityMaxInWatts(max.compact());
        profile.getCategoryProfile(cat).setExpectedFlexibilityMinInWatts(min.compact());
    }
    return profile;
}

From source file:com.anrisoftware.registration.data.RegisterKey.java

License:Open Source License

/**
 * Returns the days until the demo expire.
 *
 * @param date/*from  w w  w  . ja v  a2s  .  c  o m*/
 *            the current {@link DateTime} date.
 *
 * @return the {@link Long} days left.
 */
public long getDaysLeftDemo(DateTime date) {
    DateTime installDate = registration.getInstallDate();
    long days = new Duration(installDate, date).getStandardDays();
    return getDaysDemo() - days;
}

From source file:com.application.actify.lifecycle.ActivityFragment.java

License:Apache License

private void inflateTimerRow(final ActivityInstance ai, final ActivityPause ap) {
    scroller.setBackgroundResource(android.R.color.transparent);
    int activityid = ai.getactivityid();
    ActivitySetting as = Actify.findActivitySettingById(activityid);
    final String strActivity = as.getActivity();
    final String strLocation = as.getLocation();
    final int mode = ai.getMode();
    final long oriStart = ai.getStart().getTimeInMillis();

    LayoutInflater inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.activity_row, null);

    final Chronometer mChronometer = (Chronometer) rowView.findViewById(R.id.chronometer);

    long base;/*ww  w.j  a v  a 2 s  . com*/
    if (mode == Actify.MODE_RUNNING) {
        base = SystemClock.elapsedRealtime()
                - (Calendar.getInstance().getTimeInMillis() - ai.getStart().getTimeInMillis());
        mChronometer.setBase(base);
        mChronometer.start();

    } else if (mode == Actify.MODE_PAUSED) {
        base = SystemClock.elapsedRealtime() - ai.getEnd().getTimeInMillis();
        mChronometer.setBase(base);
    }

    final View idColor = (View) rowView.findViewById(R.id.idColor);
    idColor.setBackgroundColor(Color.parseColor(Actify.colorAdapter.getItem(ai.getactivityid()).toString()));

    final TextView txtActivity = (TextView) rowView.findViewById(R.id.txtActivity);

    final TextView txtStart = (TextView) rowView.findViewById(R.id.txtStart);
    txtStart.setText(Actify.datetimeFormat.format(ai.getStart().getTime()));

    if (mode == Actify.MODE_PAUSED) {
        txtActivity.setText(strActivity + getResources().getString(R.string.paused));
    } else {
        txtActivity.setText(strActivity);
    }

    final Button btnStop = (Button) rowView.findViewById(R.id.btnStop);
    btnStop.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            /*alarmManager.cancel(Actify.pendingIntents.get(ai.getId()));
            Actify.pendingIntents.remove(ai.getId());
            Actify.pendingIntentTimes.remove(ai.getId());
            Actify.printIntents();
            */
            ReminderUtil.cancelAlarm(getActivity(), ai.getId());

            mChronometer.stop();
            timer_container.removeView(rowView);

            Calendar calEnd = Calendar.getInstance();
            if (ai.getMode() == Actify.MODE_PAUSED) {
                ap.setEnd(calEnd);
                db.updateActivityPause(ap);
            }

            ai.setEnd(calEnd);
            ai.setMode(Actify.MODE_INSERT);
            db.updateActivity(ai);
            db.deleteLatestActivityLog();
            db.updateActivityPause(ai.getId(), ai.getSync(), ai.getMode());

            String query = db.activityGuestQueryBuilder(Actify.VIEW_TIMER, Actify.MODE_RUNNING, ai.getId());
            List<ActivityGuest> insertList = db.getActivityGuestList(query);
            for (ActivityGuest ag : insertList) {
                ag.setMode(Actify.MODE_INSERT);
                db.updateActivityGuest(ag);
            }
            query = db.activityGuestQueryBuilder(Actify.VIEW_TIMER, Actify.MODE_DELETE, ai.getId());
            List<ActivityGuest> deleteList = db.getActivityGuestList(query);
            for (ActivityGuest ag : deleteList) {
                db.deleteActivityGuest(ag);
            }

            Toast.makeText(act, strActivity + res.getString(R.string.toastActivitySaved), Toast.LENGTH_SHORT)
                    .show();

            if (timer_container.getChildCount() == 0) {
                //setIdleReminder();
                ReminderUtil.setIdleReminder(getActivity());
            }

        }
    });

    final Button btnPause = (Button) rowView.findViewById(R.id.btnPause);
    btnPause.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            switch (ai.getMode()) {
            case Actify.MODE_RUNNING: {
                // pausing

                Calendar calStart = Calendar.getInstance();
                ap.setStart(calStart);
                ActivityPause newap = db.addActivityPause(ap);
                ap.setId(newap.getId());

                Calendar calPaused = Calendar.getInstance();
                calPaused.setTimeInMillis(SystemClock.elapsedRealtime() - mChronometer.getBase());
                mChronometer.stop();
                ai.setMode(Actify.MODE_PAUSED);
                ai.setEnd(calPaused);
                db.updateActivity(ai);

                btnPause.setBackgroundResource(R.drawable.button_selector_resume);
                btnPause.setText(R.string.btnResume);
                txtActivity.setText(strActivity + getResources().getString(R.string.paused));
                break;
            }

            case Actify.MODE_PAUSED: {
                // resuming
                ai.setMode(Actify.MODE_RUNNING);
                db.updateActivity(ai);

                Calendar calResumed = Calendar.getInstance();
                ap.setEnd(calResumed);

                db.updateActivityPause(ap);
                db.deleteLatestActivityPauseLog();

                mChronometer.start();
                btnPause.setBackgroundResource(R.drawable.button_selector_pause);
                btnPause.setText(R.string.btnPause);
                txtActivity.setText(strActivity);

                break;
            }
            }
        }
    });
    if (mode == Actify.MODE_PAUSED) {
        btnPause.setBackgroundResource(R.drawable.button_selector_resume);
        btnPause.setText(R.string.btnResume);
    }

    final TextView txtLocation = (TextView) rowView.findViewById(R.id.txtLocation);
    txtLocation.setText(getResources().getString(R.string.txtLocation) + strLocation);

    final TextView txtGuest = (TextView) rowView.findViewById(R.id.txtGuest);
    List<String> guestList = db.getActivityGuestStringList(ai.getId());

    if (guestList.isEmpty())
        txtGuest.setText("");
    else {
        String guestNames = "";
        for (String s : guestList) {
            guestNames += s + " ";
        }
        txtGuest.setText(getResources().getString(R.string.txtGuests) + guestNames);
    }

    final LinearLayout ll = (LinearLayout) rowView.findViewById(R.id.ll);
    ll.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            /********************************* Activity Edit *************************************/

            final AlertDialog activityEditDialog = new AlertDialog.Builder(act).create();
            LayoutInflater inflater = act.getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.activity_edit, null);

            final Spinner spinnerActivity = (Spinner) dialogView.findViewById(R.id.spinnerActivity);
            spinnerActivity.setAdapter(Actify.activityAdapter);
            spinnerActivity.setSelection(Actify.findActivitySettingById(ai.getactivityid()).getOrder());
            spinnerActivity.setPadding(2, 2, 2, 2);

            final Spinner spinnerLocation = (Spinner) dialogView.findViewById(R.id.spinnerLocation);
            spinnerLocation.setAdapter(Actify.locationAdapter);
            spinnerLocation.setSelection(ai.getlocationid());
            spinnerLocation.setPadding(2, 2, 2, 2);

            final Button btnStart = (Button) dialogView.findViewById(R.id.btnStart);
            btnStart.setText(Actify.datetimeFormat.format(ai.getStart().getTime()));
            btnStart.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    dateTimePicker = new DateTimePicker(act, ai.getStart(),
                            new DateTimePickerListener(btnStart, ai),
                            res.getString(R.string.editActivityHeaderStartTime));
                    dateTimePicker.set24HourFormat(true);
                    dateTimePicker.showDialog();
                }

            });

            String dtReminderString = settings.getString("reminder_" + ai.getId(), "");
            DateTime dtReminder = DateTime.parse(dtReminderString, Actify.datetimeFormatJoda);
            DateTime dtNow = new DateTime();
            Duration duration = new Duration(dtNow, dtReminder);
            int hours = (int) duration.getStandardHours();
            int minutes = (int) duration.getStandardMinutes();
            int seconds = (int) duration.getStandardSeconds();
            String durationStr;

            if (seconds > 30) {
                minutes = minutes + 1;
                if (minutes % 60 == 0) {
                    hours = minutes / 60;
                }
            }

            if (hours > 0) {
                minutes = minutes - (hours * 60);
                durationStr = hours + "h " + minutes + "m from now";
            } else {
                durationStr = minutes + "m from now";
            }
            final int oldMinutes = minutes;
            final int oldHours = hours;
            changeReminder = false;

            final Button btnReminder = (Button) dialogView.findViewById(R.id.btnReminder);
            btnReminder.setText(durationStr);
            btnReminder.setOnClickListener(new OnClickListener() {
                TimePickerDialog.OnTimeSetListener nextAlarmSettingListener = new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hour, int minute) {
                        newHour = hour;
                        newMinute = minute;
                        String durationStr;
                        if (newHour > 0)
                            durationStr = newHour + " hours " + newMinute + " mins";
                        else
                            durationStr = newMinute + " mins";
                        btnReminder.setText(durationStr);
                        changeReminder = true;
                    }
                };

                @Override
                public void onClick(View v) {
                    TimePickerDialog tpDialog = new TimePickerDialog(ActivityFragment.this.getActivity(),
                            nextAlarmSettingListener, oldHours, oldMinutes, true);
                    tpDialog.setTitle("Reminder");
                    tpDialog.setMessage("Remind me after (HH:MM)");
                    tpDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            dialog.dismiss();
                        }
                    });
                    tpDialog.show();
                }
            });

            final Button btnPauses = (Button) dialogView.findViewById(R.id.btnPauses);
            btnPauses.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    /********************************* Pauses Edit *************************************/
                    String query = db.activityPauseQueryBuilder(Actify.VIEW_TIMER, ai.getId());
                    List<ActivityPause> activityPauses = db.getActivityPauseList(query);

                    if (activityPauses.isEmpty()) {
                        Toast.makeText(act, res.getString(R.string.toastActivityNoPauses), Toast.LENGTH_SHORT)
                                .show();
                    } else {

                        final AlertDialog dialogPause = new AlertDialog.Builder(act).create();

                        ScrollView sv = new ScrollView(act);

                        final LinearLayout ll = new LinearLayout(act);
                        ll.setOrientation(LinearLayout.VERTICAL);
                        for (int i = 0; i < activityPauses.size(); i++) {
                            final ActivityPause ap = activityPauses.get(i);
                            LayoutInflater inflater = (LayoutInflater) act
                                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                            final View pauseRowView = inflater.inflate(R.layout.activity_pause_row, null);

                            final Button btnStart = (Button) pauseRowView.findViewById(R.id.btnStart);
                            final String start = Actify.dateFormat.format(ap.getStart().getTime()) + "\n"
                                    + Actify.timeFormat.format(ap.getStart().getTime());
                            btnStart.setText(start);
                            btnStart.setId(START);
                            btnStart.setOnClickListener(new OnClickListener() {

                                public void onClick(View v) {
                                    dateTimePicker = new DateTimePicker(act, ap.getStart(),
                                            new DateTimePickerListener(btnStart, ap),
                                            res.getString(R.string.datetimePickerHeader));
                                    dateTimePicker.set24HourFormat(true);
                                    dateTimePicker.showDialog();
                                }
                            });

                            final Button btnEnd = (Button) pauseRowView.findViewById(R.id.btnEnd);
                            final String end = Actify.dateFormat.format(ap.getEnd().getTime()) + "\n"
                                    + Actify.timeFormat.format(ap.getEnd().getTime());
                            btnEnd.setText(end);
                            btnEnd.setId(END);
                            btnEnd.setOnClickListener(new OnClickListener() {

                                public void onClick(View v) {
                                    dateTimePicker = new DateTimePicker(act, ap.getEnd(),
                                            new DateTimePickerListener(btnEnd, ap),
                                            res.getString(R.string.datetimePickerHeader));
                                    dateTimePicker.set24HourFormat(true);
                                    dateTimePicker.showDialog();
                                }
                            });

                            final ImageButton btnDelete = (ImageButton) pauseRowView
                                    .findViewById(R.id.btnDelete);
                            btnDelete.setOnClickListener(new OnClickListener() {
                                public void onClick(View v) {
                                    AlertDialog alertDialog = new AlertDialog.Builder(act).create();
                                    alertDialog.setMessage(res.getString(R.string.editPauseDeleteMsg));
                                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,
                                            res.getString(R.string.btnYes),
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    db.deleteActivityPause(ap);
                                                    ll.removeView(pauseRowView);
                                                    activityEditDialog.dismiss();
                                                    dialog.dismiss();
                                                }
                                            });
                                    alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,
                                            res.getString(R.string.btnNo),
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            });
                                    alertDialog.show();
                                }
                            });

                            ll.addView(pauseRowView);
                        }
                        sv.addView(ll);

                        dialogPause.setView(sv);
                        dialogPause.setTitle(res.getString(R.string.editActivityTitlePauses));

                        dialogPause.setButton(AlertDialog.BUTTON_POSITIVE, res.getString(R.string.btnOk),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        dialogPause.setButton(AlertDialog.BUTTON_NEGATIVE, res.getString(R.string.btnCancel),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        dialogPause.show();
                    }
                }

            });

            final ArrayList<Guest> addGuests = new ArrayList<Guest>();
            final ArrayList<Guest> delGuests = new ArrayList<Guest>();
            final Button btnGuests = (Button) dialogView.findViewById(R.id.btnGuests);
            btnGuests.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    /********************************* Activity Guests Edit *************************************/
                    String query = db.guestQueryBuilder(ai, householdid);
                    final List<Guest> guests = db.getGuestList(query);
                    if (guests.isEmpty()) {
                        Toast.makeText(act, res.getString(R.string.editActivityToastNoGuest),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        final AlertDialog dialogGuest = new AlertDialog.Builder(act).create();

                        ScrollView sv = new ScrollView(act);

                        final LinearLayout ll = new LinearLayout(act);
                        ll.setOrientation(LinearLayout.VERTICAL);

                        for (int i = 0; i < guests.size(); i++) {
                            Guest g = guests.get(i);
                            CheckBox ch = new CheckBox(act);
                            if (db.isActivityGuest(ai.getId(), g.getId())) {
                                ch.setChecked(true);
                            } else
                                ch.setChecked(false);
                            String start = Actify.datetimeFormat.format(g.getStart().getTime());
                            String end = "...";
                            if (g.getMode() != Actify.MODE_RUNNING)
                                end = Actify.datetimeFormat.format(g.getEnd().getTime());
                            String text = g.getName() + " (" + start + " - " + end + ")";
                            ch.setText(text);
                            ch.setTextSize(14);
                            ll.addView(ch);
                        }

                        sv.addView(ll);

                        dialogGuest.setView(sv);
                        dialogGuest.setTitle(res.getString(R.string.editActivityTitleGuest));
                        dialogGuest.setMessage(res.getString(R.string.editActivityMsgGuest));

                        dialogGuest.setButton(AlertDialog.BUTTON_POSITIVE, res.getString(R.string.btnOk),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        for (int i = 0; i < guests.size(); i++) {
                                            CheckBox ch = (CheckBox) ll.getChildAt(i);
                                            if (ch.isChecked()) {
                                                addGuests.add(guests.get(i));
                                            } else
                                                delGuests.add(guests.get(i));
                                        }

                                        dialog.dismiss();
                                    }
                                });

                        dialogGuest.setButton(AlertDialog.BUTTON_NEGATIVE, res.getString(R.string.btnCancel),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        dialogGuest.show();
                    }
                }
            });

            activityEditDialog.setView(dialogView);
            activityEditDialog.setTitle(res.getString(R.string.editActivityTitleDialog));
            activityEditDialog.setButton(AlertDialog.BUTTON_POSITIVE, res.getString(R.string.btnOk),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            int activityid = Actify
                                    .findActivitySettingByOrder(spinnerActivity.getSelectedItemPosition())
                                    .getId();
                            int locationid = spinnerLocation.getSelectedItemPosition();
                            ai.setactivityid(activityid);
                            ai.setlocationid(locationid);
                            db.updateActivity(ai);

                            for (Guest g : addGuests) {
                                ActivityGuest ag = new ActivityGuest(ai.getId(), g.getId());
                                ag.setMode(Actify.MODE_RUNNING);
                                db.addActivityGuest(ag);
                            }
                            for (Guest g : delGuests) {
                                ActivityGuest ag = new ActivityGuest(ai.getId(), g.getId());
                                ag.setMode(Actify.MODE_DELETE);
                                db.updateActivityGuest(ag);
                            }

                            List<String> guestList = db.getActivityGuestStringList(ai.getId());

                            if (guestList.isEmpty())
                                txtGuest.setText("");
                            else {
                                String guestNames = "";
                                for (String s : guestList) {
                                    guestNames += s + " ";
                                }
                                txtGuest.setText(getResources().getString(R.string.txtGuests) + guestNames);
                            }

                            idColor.setBackgroundColor(
                                    Color.parseColor(Actify.colorAdapter.getItem(activityid).toString()));

                            txtLocation.setText(getResources().getString(R.string.txtLocation)
                                    + Actify.locationAdapter.getItem(locationid).toString());
                            txtStart.setText(Actify.datetimeFormat.format(ai.getStart().getTime()));

                            long changeStart = ai.getStart().getTimeInMillis() - oriStart;
                            long base;
                            String activityStr = Actify.findActivitySettingById(ai.getactivityid())
                                    .getActivity();

                            if (ai.getMode() == Actify.MODE_RUNNING) {
                                txtActivity.setText(activityStr);
                                mChronometer.stop();
                                base = SystemClock.elapsedRealtime() - (Calendar.getInstance().getTimeInMillis()
                                        - ai.getStart().getTimeInMillis());
                                mChronometer.setBase(base);
                                mChronometer.start();

                            } else if (ai.getMode() == Actify.MODE_PAUSED) {
                                base = SystemClock.elapsedRealtime() - ai.getEnd().getTimeInMillis()
                                        + changeStart;
                                mChronometer.setBase(base);
                                mChronometer.stop();
                                txtActivity.setText(activityStr + res.getString(R.string.paused));
                            }

                            if (changeReminder) {
                                ReminderUtil.cancelAlarm(getActivity(), ai.getId());
                                ActivitySetting as = Actify.findActivitySettingById(activityid);
                                ReminderUtil.setActivityReminder(getActivity(), ai.getId(),
                                        newHour * 60 + newMinute, as.getActivity());

                            }

                            dialog.dismiss();
                        }
                    });

            activityEditDialog.setButton(AlertDialog.BUTTON_NEGATIVE, res.getString(R.string.btnCancel),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

            activityEditDialog.show();

        }
    });
    timer_container.addView(rowView, timer_container.getChildCount());
}

From source file:com.arpnetworking.metrics.mad.PeriodWorker.java

License:Apache License

/**
 * {@inheritDoc}/* w w  w  .j a  v a 2  s  . c o m*/
 */
@Override
public void run() {
    Thread.currentThread()
            .setUncaughtExceptionHandler((thread, throwable) -> LOGGER.error().setMessage("Unhandled exception")
                    .addData("periodWorker", PeriodWorker.this).setThrowable(throwable).log());

    while (_isRunning) {
        try {
            DateTime now = DateTime.now();
            final DateTime rotateAt = getRotateAt(now);
            Duration timeToRotate = new Duration(now, rotateAt);
            while (_isRunning && timeToRotate.isLongerThan(Duration.ZERO)) {
                // Process records or sleep
                Record recordToProcess = _recordQueue.poll();
                if (recordToProcess != null) {
                    while (recordToProcess != null) {
                        process(recordToProcess);
                        recordToProcess = _recordQueue.poll();
                    }
                } else {
                    Thread.sleep(Math.min(timeToRotate.getMillis(), 100));
                }
                // Recompute time to close
                now = DateTime.now();
                timeToRotate = new Duration(now, rotateAt);
            }
            // Drain the record queue before rotating
            final List<Record> recordsToProcess = Lists.newArrayList();
            _recordQueue.drainTo(recordsToProcess);
            for (final Record recordToProcess : recordsToProcess) {
                process(recordToProcess);
            }
            // Rotate
            rotate(now);
        } catch (final InterruptedException e) {
            Thread.interrupted();
            LOGGER.warn().setMessage("Interrupted waiting to close buckets").setThrowable(e).log();
            // CHECKSTYLE.OFF: IllegalCatch - Top level catch to prevent thread death
        } catch (final Exception e) {
            // CHECKSTYLE.ON: IllegalCatch
            LOGGER.error().setMessage("Aggregator failure").addData("periodWorker", this).setThrowable(e).log();
        }
    }
}

From source file:com.axelor.apps.crm.service.EventService.java

License:Open Source License

@Transactional
public void addRecurrentEventsByWeeks(Event event, int periodicity, int endType, int repetitionsNumber,
        LocalDate endDate, Map<Integer, Boolean> daysCheckedMap) {
    Event lastEvent = event;//from  w w  w. ja  v  a  2  s  .  c om
    List<Integer> list = new ArrayList<Integer>();
    for (int day : daysCheckedMap.keySet()) {
        list.add(day);
    }
    Collections.sort(list);
    if (endType == 1) {
        int repeated = 0;
        Event copy = eventRepo.copy(lastEvent, false);
        copy.setParentEvent(lastEvent);
        int dayOfWeek = copy.getStartDateTime().getDayOfWeek();
        LocalDateTime nextDateTime = new LocalDateTime();
        if (dayOfWeek < list.get(0)) {
            nextDateTime = new LocalDateTime(copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek));
        } else if (dayOfWeek > list.get(0)) {
            nextDateTime = new LocalDateTime(copy.getStartDateTime().plusDays((7 - dayOfWeek) + list.get(0)));
        }
        Duration dur = new Duration(copy.getStartDateTime().toDateTime(), copy.getEndDateTime().toDateTime());

        for (Integer integer : list) {
            nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek());
            copy.setStartDateTime(nextDateTime);
            copy.setEndDateTime(nextDateTime.plus(dur));
            eventRepo.save(copy);
            lastEvent = copy;
            repeated++;
        }

        while (repeated < repetitionsNumber) {
            copy = eventRepo.copy(lastEvent, false);
            copy.setParentEvent(lastEvent);
            copy.setStartDateTime(copy.getStartDateTime().plusWeeks(periodicity));
            copy.setEndDateTime(copy.getEndDateTime().plusWeeks(periodicity));

            dayOfWeek = copy.getStartDateTime().getDayOfWeek();
            nextDateTime = new LocalDateTime();
            if (dayOfWeek < list.get(0)) {
                nextDateTime = new LocalDateTime(copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek));
            } else if (dayOfWeek > list.get(0)) {
                nextDateTime = new LocalDateTime(
                        copy.getStartDateTime().plusDays((7 - dayOfWeek) + list.get(0)));
            }
            dur = new Duration(copy.getStartDateTime().toDateTime(), copy.getEndDateTime().toDateTime());

            for (Integer integer : list) {
                nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek());
                copy.setStartDateTime(nextDateTime);
                copy.setEndDateTime(nextDateTime.plus(dur));
                eventRepo.save(copy);
                lastEvent = copy;
                repeated++;
            }
        }
    } else {

        Event copy = eventRepo.copy(lastEvent, false);
        copy.setParentEvent(lastEvent);
        int dayOfWeek = copy.getStartDateTime().getDayOfWeek();
        LocalDateTime nextDateTime = new LocalDateTime();
        if (dayOfWeek < list.get(0)) {
            nextDateTime = new LocalDateTime(copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek));
        } else if (dayOfWeek > list.get(0)) {
            nextDateTime = new LocalDateTime(copy.getStartDateTime().plusDays((7 - dayOfWeek) + list.get(0)));
        }
        Duration dur = new Duration(copy.getStartDateTime().toDateTime(), copy.getEndDateTime().toDateTime());

        for (Integer integer : list) {
            nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek());
            copy.setStartDateTime(nextDateTime);
            copy.setEndDateTime(nextDateTime.plus(dur));
            eventRepo.save(copy);
            lastEvent = copy;
        }

        while (!copy.getStartDateTime().plusWeeks(periodicity).isAfter(endDate)) {
            copy = eventRepo.copy(lastEvent, false);
            copy.setParentEvent(lastEvent);
            copy.setStartDateTime(copy.getStartDateTime().plusWeeks(periodicity));
            copy.setEndDateTime(copy.getEndDateTime().plusWeeks(periodicity));

            dayOfWeek = copy.getStartDateTime().getDayOfWeek();
            nextDateTime = new LocalDateTime();
            if (dayOfWeek < list.get(0)) {
                nextDateTime = new LocalDateTime(copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek));
            } else if (dayOfWeek > list.get(0)) {
                nextDateTime = new LocalDateTime(
                        copy.getStartDateTime().plusDays((7 - dayOfWeek) + list.get(0)));
            }
            dur = new Duration(copy.getStartDateTime().toDateTime(), copy.getEndDateTime().toDateTime());

            for (Integer integer : list) {
                nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek());
                copy.setStartDateTime(nextDateTime);
                copy.setEndDateTime(nextDateTime.plus(dur));
                eventRepo.save(copy);
                lastEvent = copy;
            }
        }
    }
}

From source file:com.axelor.apps.crm.service.EventService.java

License:Open Source License

@Transactional
public void addRecurrentEventsByMonths(Event event, int periodicity, int endType, int repetitionsNumber,
        LocalDate endDate, int monthRepeatType) {
    Event lastEvent = event;/*from  ww  w . j  a  v a 2s .c  om*/
    if (monthRepeatType == 1) {
        int dayOfMonth = event.getStartDateTime().getDayOfMonth();
        if (endType == 1) {
            int repeated = 0;
            while (repeated != repetitionsNumber) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);
                if (copy.getStartDateTime().plusMonths(periodicity).dayOfMonth()
                        .getMaximumValue() >= dayOfMonth) {
                    copy.setStartDateTime(copy.getStartDateTime().plusMonths(periodicity));
                    copy.setEndDateTime(copy.getEndDateTime().plusMonths(periodicity));
                    eventRepo.save(copy);
                    repeated++;
                    lastEvent = copy;
                }
            }
        } else {
            while (!lastEvent.getStartDateTime().plusMonths(periodicity).isAfter(endDate)) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);
                if (copy.getStartDateTime().plusMonths(periodicity).dayOfMonth()
                        .getMaximumValue() >= dayOfMonth) {
                    copy.setStartDateTime(copy.getStartDateTime().plusMonths(periodicity));
                    copy.setEndDateTime(copy.getEndDateTime().plusMonths(periodicity));
                    eventRepo.save(copy);
                    lastEvent = copy;
                }
            }
        }
    }

    else {
        int dayOfWeek = event.getStartDateTime().getDayOfWeek();
        int positionInMonth = 0;
        if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
            positionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
        } else {
            positionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
        }

        if (endType == 1) {
            int repeated = 0;
            while (repeated != repetitionsNumber) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);
                LocalDateTime nextDateTime = new LocalDateTime(copy.getStartDateTime());
                nextDateTime.plusMonths(periodicity);
                int nextDayOfWeek = nextDateTime.getDayOfWeek();
                if (nextDayOfWeek > dayOfWeek) {
                    nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
                } else {
                    nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
                }
                int nextPositionInMonth = 0;
                if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
                    nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
                } else {
                    nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
                }
                if (nextPositionInMonth > positionInMonth) {
                    nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
                } else {
                    nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
                }
                Duration dur = new Duration(copy.getStartDateTime().toDateTime(),
                        copy.getEndDateTime().toDateTime());
                copy.setStartDateTime(nextDateTime);
                copy.setEndDateTime(nextDateTime.plus(dur));
                eventRepo.save(copy);
                repeated++;
                lastEvent = copy;
            }
        } else {
            LocalDateTime nextDateTime = new LocalDateTime(lastEvent.getStartDateTime());
            nextDateTime.plusMonths(periodicity);
            int nextDayOfWeek = nextDateTime.getDayOfWeek();
            if (nextDayOfWeek > dayOfWeek) {
                nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
            } else {
                nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
            }
            int nextPositionInMonth = 0;
            if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
                nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
            } else {
                nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
            }
            if (nextPositionInMonth > positionInMonth) {
                nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
            } else {
                nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
            }
            while (!nextDateTime.isAfter(endDate)) {
                Event copy = eventRepo.copy(lastEvent, false);
                copy.setParentEvent(lastEvent);

                Duration dur = new Duration(copy.getStartDateTime().toDateTime(),
                        copy.getEndDateTime().toDateTime());
                copy.setStartDateTime(nextDateTime);
                copy.setEndDateTime(nextDateTime.plus(dur));
                eventRepo.save(copy);
                lastEvent = copy;

                nextDateTime = new LocalDateTime(lastEvent.getStartDateTime());
                nextDateTime.plusMonths(periodicity);
                nextDayOfWeek = nextDateTime.getDayOfWeek();
                if (nextDayOfWeek > dayOfWeek) {
                    nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
                } else {
                    nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
                }
                nextPositionInMonth = 0;
                if (event.getStartDateTime().getDayOfMonth() % 7 == 0) {
                    nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
                } else {
                    nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
                }
                if (nextPositionInMonth > positionInMonth) {
                    nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
                } else {
                    nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
                }
            }
        }
    }
}