List of usage examples for org.joda.time DateTime toString
public String toString(String pattern)
From source file:eu.hydrologis.jgrass.geonotes.photo.PhotoImportWizard.java
License:Open Source License
public boolean performFinish() { final FieldbookView fieldBookView = GeonotesPlugin.getDefault().getFieldbookView(); final String path = mainPage.getPhotoFolder(); shift = mainPage.getTime();/*from w w w .j a v a 2 s .com*/ intervalMinutes = mainPage.getIntervalMinutes(); doNotImport = mainPage.getDoNotImport(); createFeatureLayer = mainPage.doCreateFeatureLayer(); Display.getDefault().asyncExec(new Runnable() { public void run() { try { IWorkbench wb = PlatformUI.getWorkbench(); IProgressService ps = wb.getProgressService(); ps.busyCursorWhile(new IRunnableWithProgress() { public void run(IProgressMonitor pm) { File f = new File(path); File[] listFiles = f.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jpg") || name.endsWith(".JPG"); } }); HashMap<DateTime, List<File>> imageFiles = new HashMap<DateTime, List<File>>(); HashMap<DateTime, Coordinate> timestamp2Coordinates = new HashMap<DateTime, Coordinate>(); List<String> nonTakenFilesList = new ArrayList<String>(); pm.beginTask("Browsing pictures...", listFiles.length); for (File file : listFiles) { try { HashMap<String, String> metaData = ExifHandler.readMetaData(file); DateTime creationDatetimeUtc = ExifHandler.getCreationDatetimeUtc(metaData); // correct with the given shift int secShift = (int) (shift / 1000f); creationDatetimeUtc = creationDatetimeUtc.plusSeconds(secShift); // search for gps points of that timestamp Coordinate coordinate = GeonotesHandler .getGpsCoordinateForTimeStamp(creationDatetimeUtc, intervalMinutes); if (coordinate == null) { // could not find date nonTakenFilesList.add(file.getAbsolutePath()); } else { List<File> fileList = imageFiles.get(creationDatetimeUtc); if (fileList == null) { fileList = new ArrayList<File>(); imageFiles.put(creationDatetimeUtc, fileList); } fileList.add(file); timestamp2Coordinates.put(creationDatetimeUtc, coordinate); } pm.worked(1); } catch (Exception e) { e.printStackTrace(); } } pm.done(); List<Object[]> featureObjectList = new ArrayList<Object[]>(); Set<Entry<DateTime, List<File>>> timeSet = imageFiles.entrySet(); if (!doNotImport) { pm.beginTask("Adding EXIF tags and importing matching photos...", timeSet.size()); } else { pm.beginTask("Adding EXIF tags to matching photos...", timeSet.size()); } for (Entry<DateTime, List<File>> entry : timeSet) { try { DateTime timestamp = entry.getKey(); List<File> fileList = entry.getValue(); Coordinate coordinate = timestamp2Coordinates.get(timestamp); // set gps exif tags StringBuilder sB = new StringBuilder(""); for (File file : fileList) { sB.append(file.getName()); sB.append(" "); ExifHandler.writeGPSTagsToImage(coordinate.y, coordinate.x, file); if (createFeatureLayer) { // handle feature obj Object[] featureObjects = new Object[3]; featureObjects[0] = gf.createPoint(coordinate); featureObjects[1] = file.getName(); featureObjects[2] = timestamp .toString(UtcTimeUtilities.utcDateFormatterYYYYMMDDHHMMSS); featureObjectList.add(featureObjects); } } if (!doNotImport) { String title = sB.toString(); String info = "Date:" + UtcTimeUtilities.toStringWithMinutes(timestamp) + "\nN:" + coordinate.y + "\nE:" + coordinate.x; GeonotesHandler geonotesHandler = new GeonotesHandler(coordinate.x, coordinate.y, title, info, PHOTO, timestamp, null, null, null, null); for (File mFile : fileList) { geonotesHandler.addMedia(mFile, mFile.getName()); } if (fieldBookView != null) { geonotesHandler.addObserver(fieldBookView); } geonotesHandler.notifyObservers(NOTIFICATION.NOTEADDED); } } catch (Exception e) { e.printStackTrace(); } pm.worked(1); } pm.done(); /* * dump feature layer */ if (createFeatureLayer) { SimpleFeatureCollection newCollection = FeatureCollections.newCollection(); SimpleFeatureTypeBuilder ftypeBuilder = new SimpleFeatureTypeBuilder(); ftypeBuilder.setName("pictureslayer"); ftypeBuilder.setCRS(DefaultGeographicCRS.WGS84); ftypeBuilder.add("the_geom", Point.class); ftypeBuilder.add("name", String.class); ftypeBuilder.add("date", String.class); SimpleFeatureType ftype = ftypeBuilder.buildFeatureType(); int id = 0; for (Object[] objects : featureObjectList) { SimpleFeatureBuilder builder = new SimpleFeatureBuilder(ftype); builder.addAll(objects); SimpleFeature feature = builder.buildFeature(ftype.getTypeName() + "." + id++); newCollection.add(feature); } try { FeatureUtilities.featureCollectionToTempLayer(newCollection); } catch (IOException e) { e.printStackTrace(); } } /* * handle not matched pics */ if (nonTakenFilesList.size() > 0) { final StringBuilder sB = new StringBuilder(); sB.append( "For the following images no gps point within the threshold could be found:\n"); for (String p : nonTakenFilesList) { sB.append(p).append("\n"); } Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell(); MessageDialog.openWarning(shell, "Warning", sB.toString()); } }); } else { Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell(); if (!doNotImport) { MessageDialog.openInformation(shell, "Info", "All photos were successfully tagged and imported."); } else { MessageDialog.openInformation(shell, "Info", "All photos were successfully tagged."); } } }); } } }); } catch (Exception e1) { e1.printStackTrace(); String message = "An error occurred while importing pictures"; ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, GeonotesPlugin.PLUGIN_ID, e1); } } }); return true; }
From source file:eu.hydrologis.jgrass.gpsnmea.imports.GpxImportWizard.java
License:Open Source License
public boolean performFinish() { final File gpxFile = mainPage.getGpxFile(); /*/*from w w w . j av a 2s . c om*/ * run with backgroundable progress monitoring */ IRunnableWithProgress operation = new IRunnableWithProgress() { @SuppressWarnings("unchecked") public void run(IProgressMonitor pm) throws InvocationTargetException, InterruptedException { try { JAXBContext jaxbContext = JAXBContext.newInstance("schema.gpx_1_1"); Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); JAXBElement<GpxType> jaxbElement = (JAXBElement<GpxType>) unMarshaller.unmarshal(gpxFile); GpxType gpxType = jaxbElement.getValue(); SimpleFeatureCollection linesCollection = FeatureCollections.newCollection(); GeometryFactory gf = new GeometryFactory(); SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setName("gpx_import_lines"); b.setCRS(DefaultGeographicCRS.WGS84); b.add("the_geom", LineString.class); b.add("starttime", String.class); b.add("endtime", String.class); b.add("startelev", Double.class); b.add("endelev", Double.class); SimpleFeatureType type = b.buildFeatureType(); // get tracks int fid = 0; List<TrkType> trkList = gpxType.getTrk(); for (TrkType trkType : trkList) { SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type); Object[] values = new Object[] { null, null, null, null, null }; List<LineString> lineStrings = new ArrayList<LineString>(); // get each track segment List<TrksegType> trksegList = trkType.getTrkseg(); for (TrksegType trksegType : trksegList) { List<Coordinate> coords = new ArrayList<Coordinate>(); String startDate = null; String endDate = null; Double startElev = null; Double endElev = null; // get the segment's trackpoint List<WptType> trkptList = trksegType.getTrkpt(); for (int i = 0; i < trkptList.size(); i++) { WptType wptType = trkptList.get(i); BigDecimal lat = wptType.getLat(); BigDecimal lon = wptType.getLon(); BigDecimal ele = wptType.getEle(); if (ele == null) { ele = new BigDecimal(-1.0); } XMLGregorianCalendar time = wptType.getTime(); String timeStr = ""; if (time != null) { DateTime dt = new DateTime(time.toGregorianCalendar().getTime()); timeStr = dt.toString(dateTimeFormatterYYYYMMDDHHMMSS); } if (i == 0) { startDate = timeStr; startElev = ele.doubleValue(); } if (i == trkptList.size() - 1) { endDate = timeStr; endElev = ele.doubleValue(); } coords.add(new Coordinate(lon.doubleValue(), lat.doubleValue())); } LineString lineString = gf.createLineString(coords.toArray(new Coordinate[0])); lineStrings.add(lineString); values[0] = lineString; values[1] = startDate; values[2] = endDate; values[3] = startElev; values[4] = endElev; builder.addAll(values); SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + fid); fid++; linesCollection.add(feature); } } if (linesCollection.size() > 0) { FeatureUtilities.featureCollectionToTempLayer(linesCollection); } fid = 0; SimpleFeatureCollection pointsCollection = FeatureCollections.newCollection(); b = new SimpleFeatureTypeBuilder(); b.setName("gpx_import_poits"); b.setCRS(DefaultGeographicCRS.WGS84); b.add("the_geom", Point.class); b.add("elev", Double.class); b.add("time", String.class); type = b.buildFeatureType(); // get waypoints List<WptType> wpt = gpxType.getWpt(); for (int i = 0; i < wpt.size(); i++) { WptType wptType = wpt.get(i); BigDecimal lat = wptType.getLat(); BigDecimal lon = wptType.getLon(); BigDecimal ele = wptType.getEle(); if (ele == null) { ele = new BigDecimal(-1.0); } XMLGregorianCalendar time = wptType.getTime(); String timeStr = ""; if (time != null) { DateTime dt = new DateTime(time.toGregorianCalendar().getTime()); timeStr = dt.toString(dateTimeFormatterYYYYMMDDHHMMSS); } Point point = gf.createPoint(new Coordinate(lon.doubleValue(), lat.doubleValue())); Object[] values = new Object[] { point, ele.doubleValue(), timeStr }; SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type); builder.addAll(values); SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + fid); fid++; pointsCollection.add(feature); } if (pointsCollection.size() > 0) { FeatureUtilities.featureCollectionToTempLayer(pointsCollection); } System.out.println(); } catch (Exception e) { e.printStackTrace(); String message = "An error occurred during the gpx file import."; ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, GpsActivator.PLUGIN_ID, e); } } }; PlatformGIS.runInProgressDialog("Importing GPX data", true, operation, true); return true; }
From source file:eu.itesla_project.mcla.forecast_errors.FEAHistoDBFacade.java
License:Mozilla Public License
protected String historicalDataQuery() { String query = "headers=true"; query += "&count=" + MAXRECORDSNUM; DateTimeFormatter dateFormatter = ISODateTimeFormat.date(); DateTime intervalStart = histoInterval.getStart(); DateTime intervalEnd = histoInterval.getEnd(); query += "&time=[" + intervalStart.toString(dateFormatter) + "," + intervalEnd.toString(dateFormatter) + "]"; switch (timeHorizon) { case DACF://from w w w . j a va 2s . c om query += "&horizon=" + timeHorizon.getName(); break; default: throw new AssertionError(); } if (timeHorizon.getForecastTime() >= 0) query += "&forecast=" + timeHorizon.getForecastTime(); query += "&cols=datetime,horizon,forecastTime"; for (String generatorId : generatorsIds) { query += "," + generatorId + "_P" + "," + generatorId + "_Q"; } for (String loadId : loadsIds) { query += "," + loadId + "_P" + "," + loadId + "_Q"; } return query; }
From source file:eu.trentorise.opendata.jackan.test.ckan.CkanTestReporter.java
License:Apache License
/** * Formats date time up to the day, in English format */// w w w . j a va 2 s. c o m private static String formatDateUpToDay(DateTime date) { return date.toString(DateTimeFormat.mediumDate().withLocale(Locale.ENGLISH)); }
From source file:eu.trentorise.opendata.jackan.test.ckan.CkanTestReporter.java
License:Apache License
/** * Formats date time up to the second, in English format *//*from www.j a v a 2 s . c o m*/ private static String formatDateUpToSecond(DateTime date) { return date.toString(DateTimeFormat.mediumDateTime().withLocale(Locale.ENGLISH)); }
From source file:femr.util.calculations.dateUtils.java
License:Open Source License
/** * Converts a DateTime object to a string * * @param dateTime the DateTime object to convert, not null * @return A string in the format "mm yyyy" or null if dateTime is null *//*from ww w. j a va2s. c o m*/ public static String getFriendlyDateMonthYear(DateTime dateTime) { if (dateTime == null) return null; DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/yyyy"); String dateString = dateTime.toString(formatter); return dateString; }
From source file:femr.util.calculations.dateUtils.java
License:Open Source License
public static String getFriendlyDate(DateTime dateTime) { if (dateTime == null) return null; DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM d, yyyy - HH:mm:ss"); String dtStr = dateTime.toString(fmt); return dtStr; }
From source file:forms.CreationCommandeForm.java
public Commande creerCommande(HttpServletRequest request) { Client client;//from w w w. j av a 2 s .c o m /* * Si l'utilisateur choisit un client dj existant, pas de validation * effectuer */ String choixNouveauClient = getValeurChamp(request, CHAMP_CHOIX_CLIENT); if (ANCIEN_CLIENT.equals(choixNouveauClient)) { /* Rcupration du nom du client choisi */ String nomAncienClient = getValeurChamp(request, CHAMP_LISTE_CLIENTS); /* Rcupration de l'objet client correspondant dans la session */ HttpSession session = request.getSession(); client = ((Map<String, Client>) session.getAttribute(SESSION_CLIENTS)).get(nomAncienClient); } else { /* * Sinon on garde l'ancien mode, pour la validation des champs. * * L'objet mtier pour valider la cration d'un client existe dj, * il est donc dconseill de dupliquer ici son contenu ! la * place, il suffit de passer la requte courante l'objet mtier * existant et de rcuprer l'objet Client cr. */ CreationClientForm clientForm = new CreationClientForm(); client = clientForm.creerClient(request); /* * Et trs important, il ne faut pas oublier de rcuprer le contenu * de la map d'erreur cre par l'objet mtier CreationClientForm * dans la map d'erreurs courante, actuellement vide. */ erreurs = clientForm.getErreurs(); } /* * Ensuite, il suffit de procder normalement avec le reste des champs * spcifiques une commande. */ /* * Rcupration et conversion de la date en String selon le format * choisi. */ DateTime dt = new DateTime(); DateTimeFormatter formatter = DateTimeFormat.forPattern(FORMAT_DATE); String date = dt.toString(formatter); String montant = getValeurChamp(request, CHAMP_MONTANT); String modePaiement = getValeurChamp(request, CHAMP_MODE_PAIEMENT); String statutPaiement = getValeurChamp(request, CHAMP_STATUT_PAIEMENT); String modeLivraison = getValeurChamp(request, CHAMP_MODE_LIVRAISON); String statutLivraison = getValeurChamp(request, CHAMP_STATUT_LIVRAISON); Commande commande = new Commande(); commande.setClient(client); double valeurMontant = -1; try { valeurMontant = validationMontant(montant); } catch (Exception e) { setErreur(CHAMP_MONTANT, e.getMessage()); } commande.setMontant(valeurMontant); commande.setDate(date); try { validationModePaiement(modePaiement); } catch (Exception e) { setErreur(CHAMP_MODE_PAIEMENT, e.getMessage()); } commande.setModePaiement(modePaiement); try { validationStatutPaiement(statutPaiement); } catch (Exception e) { setErreur(CHAMP_STATUT_PAIEMENT, e.getMessage()); } commande.setStatutPaiement(statutPaiement); try { validationModeLivraison(modeLivraison); } catch (Exception e) { setErreur(CHAMP_MODE_LIVRAISON, e.getMessage()); } commande.setModeLivraison(modeLivraison); try { validationStatutLivraison(statutLivraison); } catch (Exception e) { setErreur(CHAMP_STATUT_LIVRAISON, e.getMessage()); } commande.setStatutLivraison(statutLivraison); if (erreurs.isEmpty()) { resultat = "Succs de la cration de la commande."; } else { resultat = "chec de la cration de la commande."; } return commande; }
From source file:fr.amap.commons.animation.Timeline.java
public static void main(String[] args) { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); Timeline timeline = new Timeline(new DateTime(2016, 10, 30, 0, 0, zone), new DateTime(2016, 10, 30, 23, 59, zone), 0.01); timeline.addTimelineListener(new TimelineAdapter() { @Override// ww w. j av a 2s.co m public void onTimeChanged(DateTime time) { System.out.println(time.toString("HH:mm:ss")); } }); int nearestIndex = timeline.getNearestIndex(new DateTime(2016, 10, 30, 1, 2, zone)); timeline.start(); }
From source file:fr.ybonnel.model.ScoreWithHistory.java
License:Apache License
private void aggregateOneTypeOfScore(DateTime now, Iterator<Score> itScores) { Set<String> hoursKept = new HashSet<>(); while (itScores.hasNext()) { Score score = itScores.next();//from w w w .ja v a2 s.c o m DateTime dateTimeOfScore = new DateTime(score.getTimeOfScore()); String hourOfScore = dateTimeOfScore.toString("yyyyMMddHH"); String hoursForPast1Day = dateTimeOfScore.withHourOfDay((dateTimeOfScore.getHourOfDay() / 4) * 4) .toString("yyyyMMddHH"); if (dateTimeOfScore.compareTo(now.minusHours(2)) < 0 && hoursKept.contains(hourOfScore) || dateTimeOfScore.compareTo(now.minusDays(1)) < 0 && hoursKept.contains(hoursForPast1Day)) { itScores.remove(); } else { hoursKept.add(hourOfScore); hoursKept.add(hoursForPast1Day); } } }