Example usage for org.joda.time DateTime getYear

List of usage examples for org.joda.time DateTime getYear

Introduction

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

Prototype

public int getYear() 

Source Link

Document

Get the year field value.

Usage

From source file:es.pode.adl.datamodels.datatypes.DateTimeValidator.java

License:Open Source License

/**
 * Compares two valid data model elements for equality.
 * /* w w w. j  a va 2 s. co  m*/
 * @param iFirst  The first value being compared.
 * 
 * @param iSecond The second value being compared.
 * 
 * @param iDelimiters The common set of delimiters associated with the
 * values being compared.
 * 
 * @return Returns <code>true</code> if the two values are equal, otherwise
 *         <code>false</code>.
 */
public boolean compare(String iFirst, String iSecond, Vector iDelimiters) {

    boolean equal = true;

    DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser();

    try {
        // Parse the first string and remove the sub-seconds
        DateTime dt1 = dtp.parseDateTime(iFirst);
        dt1 = new DateTime(dt1.getYear(), dt1.getMonthOfYear(), dt1.getDayOfMonth(), dt1.getHourOfDay(),
                dt1.getMinuteOfHour(), dt1.getSecondOfMinute(), 0);

        // Parse the second string and remove the sub-seconds
        DateTime dt2 = dtp.parseDateTime(iSecond);
        dt2 = new DateTime(dt2.getYear(), dt2.getMonthOfYear(), dt2.getDayOfMonth(), dt2.getHourOfDay(),
                dt2.getMinuteOfHour(), dt2.getSecondOfMinute(), 0);

        equal = dt1.equals(dt2);
    } catch (Exception e) {
        // String format error -- these cannot be equal
        equal = false;
    }

    return equal;
}

From source file:es.ucm.fdi.tutorias.business.boundary.Emails.java

License:Open Source License

private boolean crearArchivoCal(String nombreCalendario, Tutoria tutoria) {
    String hostEmail = username;//from w  w w . j  av  a  2  s.  co m

    //Initialize values
    String calFile = nombreCalendario;
    ;

    //start time
    DateTime comienzo = tutoria.getComienzoTutoria();
    java.util.Calendar startCal = java.util.Calendar.getInstance();
    startCal.set(comienzo.getYear(), comienzo.getMonthOfYear(), comienzo.getDayOfMonth(),
            comienzo.getHourOfDay(), comienzo.getMinuteOfHour());

    //end time
    java.util.Calendar endCal = java.util.Calendar.getInstance();
    DateTime fin = tutoria.getFinTutoria();
    endCal.set(fin.getYear(), fin.getMonthOfYear(), fin.getDayOfMonth(), fin.getHourOfDay(),
            fin.getMinuteOfHour());

    String subject = "Tutora";
    String location = "Location - \"Facultad de Informtica-UCM\"";
    String description = tutoria.getResumenDudas();

    net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
    calendar.getProperties().add(new ProdId("-//ProyectoSI-FdiUcm//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);

    SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'");
    String strDate = sdFormat.format(startCal.getTime());

    net.fortuna.ical4j.model.Date startDt = null;
    try {
        startDt = new net.fortuna.ical4j.model.Date(strDate, "yyyyMMdd'T'hhmmss'Z'");
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }

    long diff = endCal.getTimeInMillis() - startCal.getTimeInMillis();
    int min = (int) (diff / (1000 * 60));

    Dur dur = new Dur(0, 0, min, 0);

    //Creating a meeting event
    VEvent meeting = new VEvent(startDt, dur, subject);

    meeting.getProperties().add(new Location(location));
    meeting.getProperties().add(new Description());

    try {
        meeting.getProperties().getProperty(Property.DESCRIPTION).setValue(description);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return false;
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }

    try {
        meeting.getProperties().add(new Organizer("MAILTO:" + hostEmail));
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return false;
    }

    calendar.getComponents().add(meeting);

    FileOutputStream fout = null;

    try {
        fout = new FileOutputStream(calFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }

    CalendarOutputter outputter = new CalendarOutputter();
    outputter.setValidating(false);

    try {
        outputter.output(calendar, fout);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (ValidationException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:es.ugr.decsai.jpons.uticalculator.Uti.java

License:Open Source License

protected double convertUnits(DateTime t) {
    double cents = t.getDayOfYear() * 100 / 365;
    return t.getYear() + 0.01 * cents;

}

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

License:Open Source License

void setupNewCalendar() {
    caldroidFragment = new CaldroidSampleCustomFragment();
    Bundle args = new Bundle();
    DateTime now = DateTime.now();
    args.putInt(CaldroidFragment.MONTH, now.getMonthOfYear());
    args.putInt(CaldroidFragment.YEAR, now.getYear());
    args.putBoolean(CaldroidFragment.SHOW_NAVIGATION_ARROWS, false);
    args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, false);
    args.putInt(CaldroidFragment.START_DAY_OF_WEEK, CaldroidFragment.MONDAY);
    args.putInt(CaldroidFragment.THEME_RESOURCE, R.style.CaldroidDefaultNoGrid);
    caldroidFragment.setArguments(args);
    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.calendar, caldroidFragment);
    t.commit();/*from  ww  w  .  j a v a 2s  .  c o m*/

    final CaldroidListener listener = new CaldroidListener() {

        @Override
        public void onSelectDate(Date date, View view) {
            LocalDate d = LocalDate.fromDateFields(date);
            onDaySelected(d);
            if (bestDay != null && bestDay.first != null && bestDay.first.equals(d)) {
                //Toast.makeText(CalendarActivity.this, "Best day!", Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(CalendarActivity.this);
                builder.setTitle(R.string.best_date_recommendation_title).setPositiveButton(
                        getString(R.string.driving_warning_gotit), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                AlertDialog alertDialog = builder.create();
                alertDialog.setMessage(bestDayText);
                alertDialog.show();
            }
        }

        @Override
        public void onChangeMonth(int month, int year) {
            DateTime date = DateTime.now().withYear(year).withMonthOfYear(month);
            subtitle.setText(date.toString("MMMM YYYY").toUpperCase());
        }

        @Override
        public void onLongClickDate(Date date, View view) {

        }

        @Override
        public void onCaldroidViewCreated() {
            caldroidFragment.getView().findViewById(R.id.calendar_title_view).setVisibility(View.GONE);
            caldroidFragment.getMonthTitleTextView().setVisibility(View.GONE);
        }

    };

    caldroidFragment.setCaldroidListener(listener);
    this.bestDay = pickupUtils.getBestDay();
    this.bestDayText = getBestDayText();

    if (this.bestDay != null && this.bestDay.first != null) {
        //Toast.makeText(CalendarActivity.this, "Best day: " + bestDay.first.toString("dd/MM/YY"), Toast.LENGTH_SHORT).show();
        caldroidFragment.setBackgroundDrawableForDate(
                new ColorDrawable(getResources().getColor(R.color.android_green_light)),
                this.bestDay.first.toDate());
    }

    caldroidFragment.refreshView();
}

From source file:etc.HelperUtils.java

License:Apache License

/**
 * Takes the Timestamp in milis and parses it to the form "yyyy-MM-dd HH:mm" or to "unlimited", if zero
 * // w ww  .ja  va 2 s . c o  m
 * @param ts_Active
 *            the timestamp
 * @return the parsed timestamp
 */
public static String parseStringTs(long ts_Active) {
    if (ts_Active == 0)
        return "unlimited";

    DateTime dt = new DateTime(ts_Active);
    StringBuilder timeString = new StringBuilder();
    // add a leading "0" if the value is under ten
    timeString.append(dt.getYear()).append("-");
    timeString.append(addZero(dt.getMonthOfYear()));
    timeString.append("-");
    timeString.append(addZero(dt.getDayOfMonth()));
    timeString.append(" ");
    timeString.append(addZero(dt.getHourOfDay()));
    timeString.append(":");
    timeString.append(addZero(dt.getMinuteOfHour()));
    return timeString.toString();

}

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

License:Apache License

/**
 * //  w ww.ja va 2s . co m
 * Function for importing consumption events from an file.
 * 
 * @param filename
 *          The name of the file that will be exported.
 * @throws FileNotFoundException
 */
public void readEventsFile(String filename, Installation installation) throws FileNotFoundException {

    int startMinute = 0;
    int endMinute = 0;
    int counter = 0;
    DateTime startDateTime = new DateTime();
    DateTime endDateTime = new DateTime();
    DateTime startDate = new DateTime();
    DateTime endDate = new DateTime();
    DateTime date = installation.getStartDate();

    System.out.println(filename);

    File file = new File(filename);

    Scanner scanner = new Scanner(file);

    String line = scanner.nextLine();
    String[] temp = new String[2];

    while (scanner.hasNext()) {

        line = scanner.nextLine();
        temp = line.split("-");

        startMinute = Integer.parseInt(temp[0]);
        endMinute = Integer.parseInt(temp[1]);

        startDateTime = date.plusMinutes(startMinute);
        endDateTime = date.plusMinutes(endMinute);

        startDate = new DateTime(startDateTime.getYear(), startDateTime.getMonthOfYear(),
                startDateTime.getDayOfMonth(), 0, 0);
        endDate = new DateTime(endDateTime.getYear(), endDateTime.getMonthOfYear(), endDateTime.getDayOfMonth(),
                0, 0);

        if (startDateTime.isAfter(endDateTime) == false)
            events.add(new ConsumptionEvent(counter++, startDateTime, startDate, endDateTime, endDate));
        else
            System.out.println("Start: " + startDateTime + " End: " + endDateTime);

    }

    scanner.close();

    analyze(installation.getStartDate(), installation.getEndDate());

}

From source file:eu.europa.ec.fisheries.uvms.plugins.inmarsat.InmBody.java

License:Open Source License

DateTime getPositionDate(DateTime now) {
    int year = now.getYear();
    int month = now.getMonthOfYear();
    int d = getDayOfMonth();
    int h = getHour();
    int m = getMinutes();

    DateTime dateTime;/*w ww .j av  a2  s  . c o m*/
    try {
        // Date is in current month
        dateTime = new DateTime(year, month, d, h, m, DateTimeZone.UTC);
        // Date is in previous month
        if (dateTime.isAfter(now)) {
            dateTime = dateTime.minusMonths(1);
        }
    } catch (IllegalFieldValueException e) {
        // Date is in previous month, and day of month is > days of current month
        if (month != 1) {
            dateTime = new DateTime(year, month - 1, d, h, m, DateTimeZone.UTC);
        }
        // Date is in previous month and previous year (current month is january)
        else {
            dateTime = new DateTime(year - 1, 12, d, h, m, DateTimeZone.UTC);
        }
    }

    return dateTime;

}

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 });
    /*/*from w  ww.j a v  a 2s  .c om*/
     * 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.itesla_project.cases.EntsoeCaseRepository.java

License:Mozilla Public License

private <R> R scanRepository(DateTime date, CaseType type, Country country,
        Function<List<ImportContext>, R> handler) {
    Collection<UcteGeographicalCode> geographicalCodes = country != null ? forCountryHacked(country)
            : Collections.singleton(UcteGeographicalCode.UX);
    for (EntsoeFormat format : formats) {
        Path formatDir = config.getRootDir().resolve(format.getDirName());
        if (Files.exists(formatDir)) {
            Path typeDir = formatDir.resolve(type.name());
            if (Files.exists(typeDir)) {
                Path dayDir = typeDir.resolve(String.format("%04d", date.getYear()))
                        .resolve(String.format("%02d", date.getMonthOfYear()))
                        .resolve(String.format("%02d", date.getDayOfMonth()));
                if (Files.exists(dayDir)) {
                    List<ImportContext> importContexts = null;
                    for (UcteGeographicalCode geographicalCode : geographicalCodes) {
                        Collection<String> forbiddenFormats = config.getForbiddenFormatsByGeographicalCode()
                                .get(geographicalCode);
                        if (!forbiddenFormats.contains(format.getImporter().getFormat())) {
                            for (int i = 9; i >= 0; i--) {
                                String baseName = String.format(
                                        "%04d%02d%02d_%02d%02d_" + type + "%01d_" + geographicalCode.name()
                                                + "%01d",
                                        date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                                        date.getHourOfDay(), date.getMinuteOfHour(), date.getDayOfWeek(), i);
                                ReadOnlyDataSource ds = dataSourceFactory.create(dayDir, baseName);
                                if (importContexts == null) {
                                    importContexts = new ArrayList<>();
                                }//  ww w  . j  a va2  s . c o  m
                                if (format.getImporter().exists(ds)) {
                                    importContexts.add(new ImportContext(format.getImporter(), ds));
                                }
                            }
                        }
                    }
                    if (importContexts != null) {
                        R result = handler.apply(importContexts);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }
    }
    return null;
}

From source file:eu.itesla_project.entsoe.cases.EntsoeCaseRepository.java

License:Mozilla Public License

private <R> R scanRepository(DateTime date, CaseType type, Country country,
        Function<List<ImportContext>, R> handler) {
    Collection<EntsoeGeographicalCode> geographicalCodes = country != null ? forCountryHacked(country)
            : Collections.singleton(EntsoeGeographicalCode.UX);
    for (EntsoeFormat format : formats) {
        Path formatDir = config.getRootDir().resolve(format.getDirName());
        if (Files.exists(formatDir)) {
            Path typeDir = formatDir.resolve(type.name());
            if (Files.exists(typeDir)) {
                Path dayDir = typeDir.resolve(String.format("%04d", date.getYear()))
                        .resolve(String.format("%02d", date.getMonthOfYear()))
                        .resolve(String.format("%02d", date.getDayOfMonth()));
                if (Files.exists(dayDir)) {
                    List<ImportContext> importContexts = null;
                    for (EntsoeGeographicalCode geographicalCode : geographicalCodes) {
                        Collection<String> forbiddenFormats = config.getForbiddenFormatsByGeographicalCode()
                                .get(geographicalCode);
                        if (!forbiddenFormats.contains(format.getImporter().getFormat())) {
                            for (int i = 9; i >= 0; i--) {
                                String baseName = String.format(
                                        "%04d%02d%02d_%02d%02d_" + type + "%01d_" + geographicalCode.name()
                                                + "%01d",
                                        date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                                        date.getHourOfDay(), date.getMinuteOfHour(), date.getDayOfWeek(), i);
                                ReadOnlyDataSource ds = dataSourceFactory.create(dayDir, baseName);
                                if (importContexts == null) {
                                    importContexts = new ArrayList<>();
                                }/*from   w  ww  . j  av  a 2 s.com*/
                                if (format.getImporter().exists(ds)) {
                                    importContexts.add(new ImportContext(format.getImporter(), ds));
                                }
                            }
                        }
                    }
                    if (importContexts != null) {
                        R result = handler.apply(importContexts);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }
    }
    return null;
}