Example usage for org.joda.time Interval contains

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

Introduction

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

Prototype

public boolean contains(long millisInstant) 

Source Link

Document

Does this time interval contain the specified millisecond instant.

Usage

From source file:de.rwth.idsg.xsharing.router.utils.DateTimeUtils.java

License:Open Source License

public static boolean contains(List<Interval> intervals, DateTime query) {
    try {//from   w w  w. j  a  v a 2s  .  c  o m
        for (Interval in : intervals) {
            if (in.contains(query)) {
                return true;
            }
        }
        return false;
    } catch (Exception e) {
        log.warn("Failed to check whether {} is contained within {}", query, intervals);
        return false;
    }
}

From source file:dk.teachus.backend.domain.impl.PeriodImpl.java

License:Apache License

public boolean conflicts(DateTime bookedTime, DateTime time) {
    boolean conflicts = false;

    // On the same date
    if (bookedTime.toDateMidnight().equals(time.toDateMidnight())) {
        bookedTime = DateUtils.resetDateTime(bookedTime, time);
        time = DateUtils.resetDateTime(time, time);

        DateTime st = bookedTime.minusMinutes(lessonDuration);
        DateTime et = bookedTime.plusMinutes(lessonDuration);

        Interval bookedInterval = new Interval(st, et);

        if (bookedInterval.contains(time) && st.equals(time) == false) {
            conflicts = true;/*w w w. java 2s . c  om*/
        }
    }

    return conflicts;
}

From source file:dk.teachus.backend.domain.impl.PeriodImpl.java

License:Apache License

public boolean dateIntervalContains(DateMidnight date) {
    DateMidnight start = beginDate;/*from w  w  w  . ja v a 2 s. c o  m*/
    DateMidnight end = endDate;
    boolean contains = false;

    if (start != null && end != null) {
        Interval interval = new Interval(start, end);
        contains = interval.contains(date) || date.equals(end);
    } else if (start != null) {
        contains = date.isAfter(start) || date.equals(start);
    } else if (end != null) {
        contains = date.isBefore(end) || date.equals(end);
    } else {
        contains = true;
    }

    return contains;
}

From source file:dk.teachus.backend.domain.impl.PeriodImpl.java

License:Apache License

public boolean inLesson(DateTime bookedTime, DateTime time) {
    boolean inLesson = false;

    // On the same date
    if (bookedTime.toDateMidnight().equals(time.toDateMidnight())) {
        bookedTime = DateUtils.resetDateTime(bookedTime, time);
        time = DateUtils.resetDateTime(time, time);

        DateTime et = bookedTime.plusMinutes(lessonDuration);

        Interval bookedInterval = new Interval(bookedTime, et);

        if (bookedInterval.contains(time) && bookedTime.equals(time) == false) {
            inLesson = true;//from w ww.  j a v a  2s.c  o  m
        }
    }

    return inLesson;
}

From source file:dk.teachus.backend.domain.impl.PeriodImpl.java

License:Apache License

public boolean isTimeValid(LocalTime time) {
    boolean timeValid = false;

    Interval periodTimeInterval = new Interval(startTime.toDateTimeToday(), endTime.toDateTimeToday());

    if (periodTimeInterval.contains(time.toDateTimeToday())) {
        int timeMinutes = new Duration(startTime.toDateTimeToday(), time.toDateTimeToday())
                .toPeriod(PeriodType.minutes()).getMinutes();

        if (timeMinutes % intervalBetweenLessonStart == 0) {
            timeValid = true;/*from  w  ww. j a v  a2  s .c  o  m*/
        }
    }

    return timeValid;
}

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();//from   w w w . j  ava2 s  .  com
    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 {//from  w  w w . ja v  a2s  . co  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;
    }//w  w  w  .  ja va2  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: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  .  jav  a  2  s .  co  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.  ja va 2 s. c o m
 * @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;
}