Example usage for org.joda.time Interval Interval

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

Introduction

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

Prototype

public Interval(Object interval, Chronology chronology) 

Source Link

Document

Constructs a time interval by converting or copying from another object, overriding the chronology.

Usage

From source file:energy.usef.core.util.DateTimeUtil.java

License:Apache License

/**
 * Calculate the number of minutes of a specific date. Only the date part (year, month and day) is used to calculate the number
 * of minutes. The number of minutes is calculated from midnight to midnight the next day. For a default day this method return
 * 24 * 60 = 1440. If on this day a summer- or wintertime switch occurs, the number of minutes are different.
 *
 * @param date the date time which includes the timezone. When setting the DateTime with the default constructor, the
 * default timezone where the application runs, is used.
 * @return the number of minutes for the day (date part) of the dateTime parameter.
 *///from   w w  w . j  a  v  a2s .co  m
public static Integer getMinutesOfDay(LocalDate date) {
    Duration duration = new Interval(date.toDateMidnight(), date.plusDays(1).toDateMidnight()).toDuration();
    return (int) duration.getStandardSeconds() / SECONDS_PER_MINUTE;
}

From source file:es.usc.citius.servando.calendula.activities.ConfirmActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    processIntent();//from w  w  w . ja  va2  s .com
    setContentView(R.layout.activity_confirm);

    isToday = LocalDate.now().equals(date);
    isInWindow = AlarmScheduler.isWithinDefaultMargins(date.toDateTime(time), this);

    DateTime dt = date.toDateTime(time);
    DateTime now = DateTime.now();
    Pair<DateTime, DateTime> interval = getCheckMarginInterval(dt);
    isDistant = !new Interval(interval.first, interval.second).contains(now);

    color = AvatarMgr.colorsFor(getResources(), patient.avatar())[0];
    color = Color.parseColor("#263238");

    setupStatusBar(Color.TRANSPARENT);
    setupToolbar("", Color.TRANSPARENT, Color.WHITE);
    toolbar.setTitleTextColor(Color.WHITE);
    findViewById(R.id.imageView5).setBackgroundColor(patient.color());
    fab = (FloatingActionButton) findViewById(R.id.myFAB);
    listView = (RecyclerView) findViewById(R.id.listView);
    avatar = (ImageView) findViewById(R.id.patient_avatar);
    title = (TextView) findViewById(R.id.routine_name);
    takeMadsMessage = (TextView) findViewById(R.id.textView3);
    chekAllOverlay = findViewById(R.id.check_overlay);
    checkAllImage = (ImageView) findViewById(R.id.check_all_image);

    avatarTitle = (ImageView) findViewById(R.id.patient_avatar_title);
    titleTitle = (TextView) findViewById(R.id.routine_name_title);

    friendlyTime = (TextView) findViewById(R.id.user_friendly_time);
    hour = (TextView) findViewById(R.id.routines_list_item_hour);
    minute = (TextView) findViewById(R.id.routines_list_item_minute);
    toolbarTitle = findViewById(R.id.toolbar_title);
    avatar.setImageResource(AvatarMgr.res(patient.avatar()));
    avatarTitle.setImageResource(AvatarMgr.res(patient.avatar()));
    titleTitle.setText(patient.name());
    title.setText((isRoutine ? routine.name() : schedule.toReadableString(this)));
    takeMadsMessage.setText(isInWindow ? getString(R.string.agenda_zoom_meds_time)
            : getString(R.string.meds_from) + " " + date.toString("EEEE dd"));

    relativeTime = DateUtils.getRelativeTimeSpanString(dt.getMillis(), now.getMillis(),
            5 * DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString();

    hour.setText(time.toString("kk:"));
    minute.setText(time.toString("mm"));
    friendlyTime.setText(relativeTime.substring(0, 1).toUpperCase() + relativeTime.substring(1));

    if (isDistant) {
        fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.android_orange_dark)));
    }

    fab.setImageDrawable(new IconicsDrawable(this).icon(CommunityMaterial.Icon.cmd_check_all).color(Color.WHITE)
            .sizeDp(24).paddingDp(0));

    checkAllImage.setImageDrawable(new IconicsDrawable(this).icon(CommunityMaterial.Icon.cmd_check_all)
            .color(Color.WHITE).sizeDp(100).paddingDp(0));

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            boolean somethingToCheck = false;
            for (DailyScheduleItem item : items) {
                if (!item.takenToday()) {
                    somethingToCheck = true;
                    break;
                }
            }
            if (somethingToCheck) {
                if (isDistant) {
                    showEnsureConfirmDialog(new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            onClickFab();
                        }
                    }, false);
                } else {
                    onClickFab();
                }
            } else {
                Snack.show(getResources().getString(R.string.all_meds_taken), ConfirmActivity.this);
            }
        }
    });

    appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
    toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    toolbarLayout.setContentScrimColor(patient.color());
    setupListView();

    if ("delay".equals(action)) {
        if (isRoutine && routine != null) {
            ReminderNotification.cancel(this,
                    ReminderNotification.routineNotificationId(routine.getId().intValue()));
        } else if (schedule != null) {
            ReminderNotification.cancel(this,
                    ReminderNotification.scheduleNotificationId(schedule.getId().intValue()));
        }
        showDelayDialog();

    }
}

From source file:es.usc.citius.servando.calendula.fragments.DailyAgendaFragment.java

License:Open Source License

public void addEmptyHours(List<DailyAgendaItemStub> stubs, DateTime min, DateTime max) {

    min = min.withTimeAtStartOfDay();// w  w w .j  a  v  a 2s . c  o  m
    max = max.withTimeAtStartOfDay().plusDays(1); // end of the day

    // add empty hours if there is not an item with the same hour
    for (DateTime start = min; start.isBefore(max); start = start.plusHours(1)) {

        boolean exact = false;
        for (DailyAgendaItemStub item : items) {
            if (start.equals(item.dateTime())) {
                exact = true;
                break;
            }
        }

        Interval hour = new Interval(start, start.plusHours(1));
        if (!exact || hour.contains(DateTime.now())) {
            stubs.add(new DailyAgendaItemStub(start.toLocalDate(), start.toLocalTime()));
        }

        if (start.getHourOfDay() == 0) {
            DailyAgendaItemStub spacer = new DailyAgendaItemStub(start.toLocalDate(), start.toLocalTime());
            spacer.isSpacer = true;
            stubs.add(spacer);
        }
    }
}

From source file:es.usc.citius.servando.calendula.scheduling.DailyAgenda.java

License:Open Source License

public void setupForToday(Context ctx, final boolean force) {

    final SharedPreferences settings = ctx.getSharedPreferences(PREFERENCES_NAME, 0);
    final Long lastDate = settings.getLong(PREF_LAST_DATE, 0);
    final DateTime now = DateTime.now();

    Log.d(TAG, "Setup daily agenda. Last updated: " + new DateTime(lastDate).toString("dd/MM - kk:mm"));

    Interval today = new Interval(now.withTimeAtStartOfDay(), now.withTimeAtStartOfDay().plusDays(1));

    // we need to update daily agenda
    if (!today.contains(lastDate) || force) {
        // Start transaction
        try {/*w w  w. j  ava  2 s  .c  o m*/
            TransactionManager.callInTransaction(DB.helper().getConnectionSource(), new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    if (!force) {
                        LocalDate yesterday = now.minusDays(1).toLocalDate();
                        LocalDate tomorrow = now.plusDays(1).toLocalDate();

                        // delete items older than yesterday
                        DB.dailyScheduleItems().removeOlderThan(yesterday);
                        // delete items beyond tomorrow (only possible when changing date)
                        DB.dailyScheduleItems().removeBeyond(tomorrow);
                    } else {
                        DB.dailyScheduleItems().removeAll();
                    }
                    // and add new ones
                    createDailySchedule(now);
                    // Save last date to prefs
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putLong(PREF_LAST_DATE, now.getMillis());
                    editor.commit();
                    return null;
                }
            });
        } catch (SQLException e) {
            if (!force) {
                Log.e(TAG, "Error setting up daily agenda. Retrying with force = true", e);
                // setup with force, destroy current daily agenda but continues working
                setupForToday(ctx, true);
            } else {
                Log.e(TAG, "Error setting up daily agenda", e);
            }
        }
        // Update alarms
        AlarmScheduler.instance().updateAllAlarms(ctx);
        CalendulaApp.eventBus().post(new AgendaUpdatedEvent());
    } else {
        Log.d(TAG, "No need to update daily schedule (" + DailyScheduleItem.findAll().size()
                + " items found for today)");
    }
}

From source file:es.usc.citius.servando.calendula.util.PickupUtils.java

License:Open Source License

public Pair<LocalDate, List<PickupInfo>> getBestDay() {

    if (this.bestDay != null) {
        return this.bestDay;
    }/*from w  w  w.  j  a  va  2  s .c om*/

    HashMap<LocalDate, List<PickupInfo>> bestDays = new HashMap<>();
    if (pickups.size() > 0) {
        LocalDate today = LocalDate.now();
        LocalDate first = LocalDate.now();
        LocalDate now = LocalDate.now().minusDays(MAX_DAYS);

        if (now.getDayOfWeek() == DateTimeConstants.SUNDAY) {
            now = now.plusDays(1);
        }

        // get the date of the first med we can take from 10 days ago
        for (PickupInfo p : pickups) {
            if (p.from().isAfter(now) && !p.taken()) {
                first = p.from();
                break;
            }
        }

        for (int i = 0; i < 10; i++) {
            LocalDate d = first.plusDays(i);
            if (!d.isAfter(today) && d.getDayOfWeek() != DateTimeConstants.SUNDAY) {
                // only take care of days after today that are not sundays
                continue;
            }

            // compute the number of meds we cant take for each day
            for (PickupInfo p : pickups) {
                // get the pickup take secure interval
                DateTime iStart = p.from().toDateTimeAtStartOfDay();
                DateTime iEnd = p.from().plusDays(MAX_DAYS - 1).toDateTimeAtStartOfDay();
                Interval interval = new Interval(iStart, iEnd);
                // add the pickup to the daily list if we can take it
                if (!p.taken() && interval.contains(d.toDateTimeAtStartOfDay())) {
                    if (!bestDays.containsKey(d)) {
                        bestDays.put(d, new ArrayList<PickupInfo>());
                    }
                    bestDays.get(d).add(p);
                }
            }
        }

        // select the day with the highest number of meds
        int bestDayCount = 0;
        LocalDate bestOption = null;
        Set<LocalDate> localDates = bestDays.keySet();
        ArrayList<LocalDate> sorted = new ArrayList<>(localDates);
        Collections.sort(sorted);
        for (LocalDate day : sorted) {
            List<PickupInfo> pks = bestDays.get(day);
            Log.d("PickupUtils", day.toString("dd/MM/YYYY") + ": " + pks.size());
            if (pks.size() >= bestDayCount) {
                bestDayCount = pks.size();
                bestOption = day;
                if (bestOption.getDayOfWeek() == DateTimeConstants.SUNDAY) {
                    bestOption = bestOption.minusDays(1);
                }
            }
        }
        if (bestOption != null) {
            this.bestDay = new Pair<>(bestOption, bestDays.get(bestOption));
            return this.bestDay;
        }
    }

    return null;
}

From source file:es.usc.citius.servando.calendula.util.ScheduleHelper.java

License:Open Source License

public static boolean cycleEnabledForDate(LocalDate date, LocalDate s, int activeDays, int restDays) {
    DateTime start = s.toDateTimeAtStartOfDay();
    DateTime day = date.toDateTimeAtStartOfDay().plusDays(1);

    if (day.isBefore(start))
        return false;

    int activePeriod = activeDays;
    int restPeriod = restDays;
    int cycleLength = activePeriod + restPeriod;
    int days = (int) new Interval(start, day).toDuration().getStandardDays();
    int cyclesUntilNow = days / cycleLength;

    Log.d("ScheduleHelper", "start: " + start.toString("dd/MM/YYYY") + ", day: " + day.toString("dd/MM/YYYY"));
    Log.d("ScheduleHelper", "Active: " + activePeriod + ", rest: " + restPeriod + ", cycle: " + cycleLength
            + ", days: " + days + ", cyclesUntilNow: " + cyclesUntilNow);

    // get start of current cycle

    DateTime cycleStart = start.plusDays(cyclesUntilNow * cycleLength);

    return new Interval(cycleStart, cycleStart.plusDays(activePeriod)).contains(date.toDateTimeAtStartOfDay());

}

From source file:eu.cassandra.training.consumption.ConsumptionEvent.java

License:Apache License

/**
 * This function is used to calculate the variables that are not directly
 * given from the dataset as duration, weekday type and start/end minute of
 * the day./*from   w w  w . j  a va 2 s .  c o m*/
 */
public void calculateParameters() {
    duration = new Interval(startDateTime, endDateTime).toDuration();
    startMinuteOfDay = startDateTime.getMinuteOfDay();
    endMinuteOfDay = endDateTime.getMinuteOfDay();
    if (startDate.getDayOfWeek() > 6)
        weekday = false;
    else
        weekday = true;
}

From source file:eu.cassandra.training.consumption.ConsumptionEventRepo.java

License:Apache License

/**
 * Function for exporting the consumption event start and end times
 * to a file for the training procedure.
 * /*from w  w  w. ja  va  2 s .c  om*/
 * @param filename
 *          The name of the file that will be exported.
 */
public void eventsToFile(String filename) {
    try {

        DateTime startBase = events.get(0).getStartDate();
        DateTime endBase = events.get(events.size() - 1).getEndDate().plusDays(1);

        long endTick = new Interval(startBase, endBase).toDuration().getStandardMinutes();

        PrintStream realSystemOut = System.out;
        OutputStream output = new FileOutputStream(filename);
        PrintStream printOut = new PrintStream(output);
        System.setOut(printOut);

        System.out.println("End:" + endTick);

        for (int i = 0; i < events.size(); i++) {

            long startDistance = new Interval(startBase, events.get(i).getStartDateTime()).toDuration()
                    .getStandardMinutes();

            long endDistance = new Interval(startBase, events.get(i).getEndDateTime()).toDuration()
                    .getStandardMinutes();

            System.out.println(startDistance + "-" + endDistance);

        }

        System.setOut(realSystemOut);
        output.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eu.hydrologis.jgrass.geonotes.fieldbook.FieldbookView.java

License:Open Source License

public void createPartControl(Composite parent) {

    SashForm sashForm = new SashForm(parent, SWT.VERTICAL);

    // left panel for list and search
    Composite mainListComposite = new Composite(sashForm, SWT.NONE);
    GridData gD1 = new GridData(SWT.LEFT, SWT.FILL, false, true);
    mainListComposite.setLayoutData(gD1);
    mainListComposite.setLayout(new GridLayout(1, false));

    mainGeonotesComposite = new Composite(sashForm, SWT.NONE);
    GridData gD2 = new GridData(SWT.FILL, SWT.FILL, true, true);
    mainGeonotesComposite.setLayoutData(gD2);
    StackLayout geonotesStackLayout = new StackLayout();
    mainGeonotesComposite.setLayout(geonotesStackLayout);

    sashForm.setWeights(new int[] { 45, 55 });
    /*/*  w  w  w.  j a  va 2 s .c  o  m*/
     * left panel
     */
    // the search types combo that leads the search types composite
    final Combo searchTypesCombo = new Combo(mainListComposite, SWT.DROP_DOWN | SWT.READ_ONLY);
    searchTypesCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    searchTypesCombo.setItems(SEARCHTYPES);
    searchTypesCombo.select(0);

    // the search types composite, that will hold the different search mechanisms
    final Composite searchTypesComposite = new Composite(mainListComposite, SWT.NONE);
    GridData gD4 = new GridData(SWT.FILL, SWT.TOP, true, false);
    gD4.heightHint = 30;
    searchTypesComposite.setLayoutData(gD4);
    final StackLayout searchtypesStackLayout = new StackLayout();
    searchTypesComposite.setLayout(searchtypesStackLayout);

    searchTypesCombo.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            int index = searchTypesCombo.getSelectionIndex();
            Control control = searchTypesMap.get(SEARCHTYPES[index]);
            searchtypesStackLayout.topControl = control;
            searchTypesComposite.layout();

            // clean up the selection, view all
            if (geonotesList != null)
                geonotesViewer.setInput(geonotesList);
            searchTextWidget.setText("");
        }
    });

    searchTextWidget = new Text(searchTypesComposite, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
    searchTextWidget.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    searchTextWidget.setText("");
    searchtypesStackLayout.topControl = searchTextWidget;
    searchTextWidget.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            if (geonotesList != null) {
                List<GeonotesHandler> toAdd = new ArrayList<GeonotesHandler>();
                for (GeonotesHandler geonoteHandler : geonotesList) {
                    String noteTitle = geonoteHandler.getTitle();
                    String userText = searchTextWidget.getText();
                    if (noteTitle.matches(".*" + userText + ".*")) {
                        toAdd.add(geonoteHandler);
                    } else {
                        // check also in text
                        GeonotesTextareaTable geonotesTextareaTable = geonoteHandler.getGeonotesTextareaTable();
                        if (geonotesTextareaTable != null) {
                            String textAreaText = geonotesTextareaTable.getText();
                            if (textAreaText != null
                                    && textAreaText.toLowerCase().indexOf(userText.toLowerCase()) != -1) {
                                toAdd.add(geonoteHandler);
                            }
                        }
                    }
                }
                geonotesViewer.setInput(toAdd);
                geonotesViewer.setRelatedToNeutral();
            }
        }
    });

    // type 2: search by note color
    Composite searchColorWidget = new Composite(searchTypesComposite, SWT.BORDER);
    searchColorWidget.setLayout(new GridLayout(6, true));
    GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
    searchColorWidget.setLayoutData(gridData);
    int[][] colors = GeonoteConstants.DEFAULTBACKGROUNDCOLORS;
    int size = 20;
    for (int i = 0; i < colors.length; i++) {
        int[] clr = colors[i];
        final Label l = new Label(searchColorWidget, SWT.None);
        l.setSize(size, size);
        RGB rgb = new RGB(clr[0], clr[1], clr[2]);
        l.setBackground(new Color(searchColorWidget.getDisplay(), rgb));
        l.addMouseListener(new MouseAdapter() {
            public void mouseDown(MouseEvent e) {
                Color geonoteColor = l.getBackground();
                String selectedColor = geonoteColor.getRed() + ":" + geonoteColor.getGreen() + ":"
                        + geonoteColor.getBlue() + ":255";
                if (geonotesList != null) {
                    List<GeonotesHandler> toAdd = new ArrayList<GeonotesHandler>();
                    for (GeonotesHandler geonoteHandler : geonotesList) {
                        String geonoteColorRGB = geonoteHandler.getColorString();
                        if (geonoteColorRGB.equals(selectedColor)) {
                            toAdd.add(geonoteHandler);
                        }
                    }
                    geonotesViewer.setInput(toAdd);
                }
            }
        });
        GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false);
        l.setLayoutData(gd);
    }

    // type 3: search by date
    final Composite searchByDateWidget = new Composite(searchTypesComposite, SWT.BORDER);
    searchByDateWidget.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    searchByDateWidget.setLayout(new FillLayout());

    final Button fromDateButton = new Button(searchByDateWidget, SWT.PUSH);
    fromDateButton.setText("from");
    final Button toDateButton = new Button(searchByDateWidget, SWT.PUSH);
    toDateButton.setText("to");
    final Button searchDateButton = new Button(searchByDateWidget, SWT.PUSH);
    searchDateButton.setText("search");
    searchDateButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            String fromDateString = fromDateButton.getToolTipText();
            String toDateString = toDateButton.getToolTipText();
            DateTime fromDate = BeegisUtilsPlugin.dateTimeFormatterYYYYMMDDHHMM.parseDateTime(fromDateString);
            DateTime toDate = BeegisUtilsPlugin.dateTimeFormatterYYYYMMDDHHMM.parseDateTime(toDateString);
            Interval interval = new Interval(fromDate, toDate);
            if (geonotesList != null) {
                List<GeonotesHandler> toAdd = new ArrayList<GeonotesHandler>();
                for (GeonotesHandler geonoteHandler : geonotesList) {
                    DateTime dateTime = geonoteHandler.getCreationDate();
                    if (interval.contains(dateTime)) {
                        toAdd.add(geonoteHandler);
                    }
                }
                geonotesViewer.setInput(toAdd);
            }
        }
    });

    Listener dateListener = new Listener() {
        public void handleEvent(Event e) {
            if (e.widget instanceof Button) {
                final Button dateButton = (Button) e.widget;
                final Shell dialog = new Shell(Display.getDefault(), SWT.DIALOG_TRIM);
                dialog.setLayout(new GridLayout(3, false));

                final org.eclipse.swt.widgets.DateTime date = new org.eclipse.swt.widgets.DateTime(dialog,
                        SWT.DATE);
                final org.eclipse.swt.widgets.DateTime time = new org.eclipse.swt.widgets.DateTime(dialog,
                        SWT.TIME | SWT.SHORT);

                new Label(dialog, SWT.NONE);
                new Label(dialog, SWT.NONE);
                Button ok = new Button(dialog, SWT.PUSH);
                ok.setText("OK");
                ok.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
                ok.addSelectionListener(new SelectionAdapter() {
                    public void widgetSelected(SelectionEvent e) {
                        StringBuilder dateBuilder = new StringBuilder();
                        dateBuilder.append(date.getYear());
                        dateBuilder.append("-");
                        dateBuilder.append((date.getMonth() + 1));
                        dateBuilder.append("-");
                        dateBuilder.append(date.getDay());
                        dateBuilder.append(" ");
                        dateBuilder.append(time.getHours());
                        dateBuilder.append(":");
                        dateBuilder.append(time.getMinutes());
                        if (dateButton.equals(fromDateButton)) {
                            fromDateButton.setToolTipText(dateBuilder.toString());
                        } else {
                            toDateButton.setToolTipText(dateBuilder.toString());
                        }
                        dialog.close();
                    }
                });
                dialog.setDefaultButton(ok);
                Point mouse = dialog.getDisplay().getCursorLocation();
                dialog.setLocation(mouse.x, mouse.y);
                dialog.pack();
                dialog.open();
            }
        }
    };

    fromDateButton.addListener(SWT.Selection, dateListener);
    toDateButton.addListener(SWT.Selection, dateListener);

    // end of type 3

    // type 4: search by type
    final Composite isGpsWidget = new Composite(searchTypesComposite, SWT.BORDER);
    isGpsWidget.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    isGpsWidget.setLayout(new FillLayout());

    final Button allNotesButton = new Button(isGpsWidget, SWT.TOGGLE);
    allNotesButton.setText("all");
    allNotesButton.setSelection(true);

    final Button normalNotesButton = new Button(isGpsWidget, SWT.TOGGLE);
    normalNotesButton.setText("normal");

    final Button gpsNotesButton = new Button(isGpsWidget, SWT.TOGGLE);
    gpsNotesButton.setText("gps");

    final Button photoButton = new Button(isGpsWidget, SWT.TOGGLE);
    photoButton.setText("photo");

    Listener gpsListener = new Listener() {
        public void handleEvent(Event e) {
            Control[] children = isGpsWidget.getChildren();
            for (int i = 0; i < children.length; i++) {
                Control child = children[i];
                if (e.widget != child && child instanceof Button && (child.getStyle() & SWT.TOGGLE) != 0) {
                    ((Button) child).setSelection(false);
                }
            }
            Button selectedButton = (Button) e.widget;
            selectedButton.setSelection(true);

            if (selectedButton.equals(allNotesButton)) {
                if (geonotesList != null) {
                    List<GeonotesHandler> toAdd = new ArrayList<GeonotesHandler>();
                    toAdd.addAll(geonotesList);
                    geonotesViewer.setInput(toAdd);
                }
            } else if (selectedButton.equals(normalNotesButton)) {
                if (geonotesList != null) {
                    List<GeonotesHandler> toAdd = new ArrayList<GeonotesHandler>();
                    for (GeonotesHandler geoNote : geonotesList) {
                        if (geoNote.getType() == GeonoteConstants.NORMAL) {
                            toAdd.add(geoNote);
                        }
                    }
                    geonotesViewer.setInput(toAdd);
                }
            } else if (selectedButton.equals(photoButton)) {
                if (geonotesList != null) {
                    List<GeonotesHandler> toAdd = new ArrayList<GeonotesHandler>();
                    for (GeonotesHandler geoNote : geonotesList) {
                        if (geoNote.getType() == GeonoteConstants.PHOTO) {
                            toAdd.add(geoNote);
                        }
                    }
                    geonotesViewer.setInput(toAdd);
                }
            } else if (selectedButton.equals(gpsNotesButton)) {
                if (geonotesList != null) {
                    List<GeonotesHandler> toAdd = new ArrayList<GeonotesHandler>();
                    for (GeonotesHandler geoNote : geonotesList) {
                        if (geoNote.getType() == GeonoteConstants.GPS) {
                            toAdd.add(geoNote);
                        }
                    }
                    geonotesViewer.setInput(toAdd);
                }
            }

        }
    };
    allNotesButton.addListener(SWT.Selection, gpsListener);
    gpsNotesButton.addListener(SWT.Selection, gpsListener);
    photoButton.addListener(SWT.Selection, gpsListener);
    normalNotesButton.addListener(SWT.Selection, gpsListener);

    // end of type 4

    searchTypesMap.put(SEARCHTYPES[0], searchTextWidget);
    searchTypesMap.put(SEARCHTYPES[1], searchColorWidget);
    searchTypesMap.put(SEARCHTYPES[2], searchByDateWidget);
    searchTypesMap.put(SEARCHTYPES[3], isGpsWidget);

    geonotesViewer = new GeonotesListViewer(mainListComposite, mainGeonotesComposite, SWT.MULTI | SWT.BORDER);
    GridData gd3 = new GridData(SWT.FILL, SWT.FILL, true, true);
    geonotesViewer.getTable().setLayoutData(gd3);

    geonotesList = GeonotesHandler.getGeonotesHandlers();
    geonotesViewer.setInput(geonotesList);

    // add some actions
    Table table = geonotesViewer.getTable();
    MenuManager popManager = new MenuManager();

    IAction menuAction = new ZoomToNotesAction(geonotesViewer);
    popManager.add(menuAction);
    menuAction = new RemoveNotesAction(geonotesViewer);
    popManager.add(menuAction);
    popManager.add(new Separator());
    menuAction = new ExportToFeatureLayerAction(geonotesViewer);
    popManager.add(menuAction);
    menuAction = new DumpNotesAction(geonotesViewer);
    popManager.add(menuAction);
    menuAction = new DumpNotesBinaryAction(geonotesViewer);
    popManager.add(menuAction);
    importAction = new ImportNotesAction(geonotesViewer);
    popManager.add(importAction);
    popManager.add(new Separator());
    menuAction = new SendNotesAction(geonotesViewer);
    popManager.add(menuAction);
    popManager.add(new Separator());
    menuAction = new SortNotesTitleAction(geonotesViewer);
    popManager.add(menuAction);
    menuAction = new SortNotesTimeAction(geonotesViewer);
    popManager.add(menuAction);

    Menu menu = popManager.createContextMenu(table);
    table.setMenu(menu);

    // drop support
    Transfer[] transferTypes = new Transfer[] { TextTransfer.getInstance(), FileTransfer.getInstance() };
    int dndOperations = DND.DROP_MOVE | DND.DROP_LINK;
    geonotesViewer.addDropSupport(dndOperations, transferTypes, new FileDropListener());

    // open on double click
    geonotesViewer.addDoubleClickListener(new IDoubleClickListener() {
        public void doubleClick(DoubleClickEvent event) {
            IStructuredSelection sel = (IStructuredSelection) event.getSelection();
            GeonotesHandler geonotesHandler = (GeonotesHandler) sel.getFirstElement();
            GeonotesUI geonoteUI = new GeonotesUI(geonotesHandler);
            geonoteUI.openInShell(null);
            geonotesHandler.addObserver(FieldbookView.this);
        }
    });

    // add a close listener
    /*
     * the following is currently needed to solve the unable to load map error 
     * which is due to the fact that the reference envelope in the blackboard 
     * breaks the memento xml saving engine. So the reference envelopes
     * are currently removed every time the fieldbook is close, which in fact is 
     * even better, since it removes the pin selection.
     */
    this.getSite().getPage().addPartListener(new IPartListener2() {
        public void partClosed(IWorkbenchPartReference partRef) {
            Collection<? extends IMap> openMaps = ApplicationGIS.getOpenMaps();
            for (IMap map : openMaps) {
                IBlackboard blackboard = map.getBlackboard();
                blackboard.put(GeoNoteSelectionTool.SELECTIONID, new ReferencedEnvelope[0]);
            }
        }

        public void partActivated(IWorkbenchPartReference partRef) {
        }

        public void partBroughtToTop(IWorkbenchPartReference partRef) {
        }

        public void partDeactivated(IWorkbenchPartReference partRef) {
        }

        public void partHidden(IWorkbenchPartReference partRef) {
        }

        public void partInputChanged(IWorkbenchPartReference partRef) {
        }

        public void partOpened(IWorkbenchPartReference partRef) {
        }

        public void partVisible(IWorkbenchPartReference partRef) {
        }
    });

    DatabasePlugin.getDefault().addDatabaseEventListener(this);

}

From source file:eu.hydrologis.jgrass.geonotes.GeonotesHandler.java

License:Open Source License

/**
 * Fetches a gps coordinate from the database nearest to a supplied time and date.
 * //from   ww w  .  j  a va  2s. c om
 * @param dateTime the time to search for.
 * @return the coordinate of the nearest time.
 * @throws Exception
 */
public static Coordinate getGpsCoordinateForTimeStamp(DateTime dateTime, int minutesThreshold)
        throws Exception {
    DateTime from = dateTime.minusMinutes(minutesThreshold);
    DateTime to = dateTime.plusMinutes(minutesThreshold);

    Session session = null;
    try {
        session = DatabasePlugin.getDefault().getActiveDatabaseConnection().openSession();
        Criteria criteria = session.createCriteria(GpsLogTable.class);
        String utcTimeStr = "utcTime";
        criteria.add(between(utcTimeStr, from, to));
        criteria.addOrder(asc(utcTimeStr));

        List<GpsLogTable> resultsList = criteria.list();
        for (int i = 0; i < resultsList.size() - 1; i++) {

            GpsLogTable gpsLog1 = resultsList.get(i);
            GpsLogTable gpsLog2 = resultsList.get(i + 1);

            DateTime utcTimeBefore = gpsLog1.getUtcTime();
            DateTime utcTimeAfter = gpsLog2.getUtcTime();

            Interval interval = new Interval(utcTimeBefore, utcTimeAfter);
            if (interval.contains(dateTime)) {
                // take the nearest
                Interval intervalBefore = new Interval(utcTimeBefore, dateTime);
                Interval intervalAfter = new Interval(dateTime, utcTimeAfter);
                long beforeMillis = intervalBefore.toDurationMillis();
                long afterMillis = intervalAfter.toDurationMillis();
                if (beforeMillis < afterMillis) {
                    Coordinate coord = new Coordinate(gpsLog1.getEast(), gpsLog1.getNorth());
                    return coord;
                } else {
                    Coordinate coord = new Coordinate(gpsLog2.getEast(), gpsLog2.getNorth());
                    return coord;
                }
            }

        }
    } finally {
        session.close();
    }
    return null;
}