List of usage examples for java.util Date from
public static Date from(Instant instant)
From source file:org.noorganization.instalist.server.api.ProductResource.java
/** * Finds a single product./*w w w .java 2 s . c o m*/ * @param _groupId The id of the group containing the searched product. * @param _productUUID The uuid of the needed product. */ @GET @TokenSecured @Path("{productuuid}") @Produces({ "application/json" }) public Response getProduct(@PathParam("groupid") int _groupId, @PathParam("productuuid") String _productUUID) throws Exception { UUID toFind; try { toFind = UUID.fromString(_productUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); IProductController productController = ControllerFactory.getProductController(manager); Product foundProduct = productController.findByGroupAndUUID(group, toFind); if (foundProduct == null) { if (productController.findDeletedByGroupAndUUID(group, toFind) != null) { manager.close(); return ResponseFactory .generateGone(new Error().withMessage("The requested " + "product has been deleted.")); } manager.close(); return ResponseFactory .generateNotFound(new Error().withMessage("The requested " + "product was not found.")); } manager.close(); ProductInfo rtn = new ProductInfo().withDeleted(false); rtn.setUUID(toFind); rtn.setName(foundProduct.getName()); rtn.setDefaultAmount(foundProduct.getDefaultAmount()); rtn.setStepAmount(foundProduct.getStepAmount()); if (foundProduct.getUnit() != null) rtn.setUnitUUID(foundProduct.getUnit().getUUID()); rtn.setLastChanged(Date.from(foundProduct.getUpdated())); return ResponseFactory.generateOK(rtn); }
From source file:com.bdb.weather.display.stripchart.StripChart.java
/** * Add an item to a series./*from www . j a v a2s . co m*/ * * @param seriesName The name of the series to which the data is to be added * @param time The time of the data * @param value The value of the data */ public void addItem(String seriesName, LocalDateTime time, double value) { TimeSeries timeSeries = series.get(seriesName); Instant instant = Instant.from(time.atZone(ZoneId.systemDefault())); Date res = Date.from(instant); if (timeSeries != null) { timeSeries.removeAgedItems(false); timeSeries.addOrUpdate(new Second(res), value); Calendar c = Calendar.getInstance(); c.setTime(res); adjustDateAxis(c); } }
From source file:com.example.geomesa.lambda.LambdaQuickStart.java
@Override public void run() { try {//from w w w . j av a 2s . c om // create the schema final String sftName = "lambda-quick-start"; final String sftSchema = "name:String,age:Int,dtg:Date,*geom:Point:srid=4326"; SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema); if (ds.getSchema(sftName) != null) { out.println("'" + sftName + "' feature type already exists - quick start will not work correctly"); out.println("Please delete it and re-run"); return; } out.println("Creating feature type '" + sftName + "'"); ds.createSchema(sft); out.println("Feature type created - register the layer '" + sftName + "' in geoserver then hit <enter> to continue"); in.read(); SimpleFeatureWriter writer = ds.getFeatureWriterAppend(sftName, Transaction.AUTO_COMMIT); out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes"); // creates and adds SimpleFeatures to the producer every 1/5th of a second final int COUNT = 1000; final int MIN_X = -180; final int MAX_X = 180; final int MIN_Y = -90; final int MAX_Y = 90; final int DX = 2; final String[] PEOPLE_NAMES = { "James", "John", "Peter", "Hannah", "Claire", "Gabriel" }; final long SECONDS_PER_YEAR = 365L * 24L * 60L * 60L; ZonedDateTime MIN_DATE = ZonedDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final Random random = new Random(); int numUpdates = (MAX_X - MIN_X) / DX; for (int j = 0; j < numUpdates; j++) { for (int i = 0; i < COUNT; i++) { SimpleFeature feature = writer.next(); feature.setAttribute(0, PEOPLE_NAMES[i % PEOPLE_NAMES.length]); // name feature.setAttribute(1, (int) Math.round(random.nextDouble() * 110)); // age feature.setAttribute(2, Date.from(MIN_DATE .plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR)).toInstant())); // dtg feature.setAttribute(3, "POINT(" + (MIN_X + (DX * j)) + " " + (MIN_Y + ((MAX_Y - MIN_Y) / ((double) COUNT)) * i) + ")"); // geom feature.getUserData().put(Hints.PROVIDED_FID, String.format("%04d", i)); writer.write(); } Thread.sleep(200); } writer.close(); out.println("Waiting for expiry and persistence..."); long total = 0, persisted = 0; do { long newTotal = (long) ds.stats().getCount(sft, Filter.INCLUDE, true).get(); long newPersisted = (long) ((AccumuloDataStore) ds.persistence()).stats() .getCount(sft, Filter.INCLUDE, true).get(); if (newTotal != total || newPersisted != persisted) { total = newTotal; persisted = newPersisted; out.println("Total features: " + total + ", features persisted to Accumulo: " + persisted); } Thread.sleep(100); } while (persisted < COUNT || total > COUNT); } catch (Exception e) { throw new RuntimeException(e); } finally { ds.dispose(); } }
From source file:fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.java
public static Date localDateTimeToDate(LocalDateTime ldt) { return Date.from(ldt.atZone(TimeZone.getDefault().toZoneId()).toInstant()); }
From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java
@Override @Transactional(readOnly = false)//from w w w . j a va2s . c o m public void reserver(final LocalDate startDate, final Famille famille, final List<DayOfWeek> jours) throws TechnicalException { final Activite activite = getCantineActivite(); final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille); icts.forEach(ict -> { final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndDateDebut( activite, ict.getGroupe(), Date.from(Instant.from(startDate.atStartOfDay(ZoneId.systemDefault())))); ouvertures.forEach(o -> { final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate()); try { this.reserver(date, ict.getIndividu().getId(), famille, jours.contains(date.getDayOfWeek())); } catch (TechnicalException e) { LOGGER.error("Une erreur technique s'est produite : " + e.getMessage(), e); } catch (FunctionalException e) { LOGGER.warn("Une erreur fonctionnelle s'est produite : " + e.getMessage(), e); } }); }); }
From source file:org.noorganization.instalist.server.api.CategoriesResource.java
/** * Get a list of categories./*from w w w . ja v a2s.c o m*/ * * @param _groupId The id of the group. * @param _categoryUUID The uuid of the category to fetch. */ @GET @TokenSecured @Path("{categoryuuid}") @Produces({ "application/json" }) public Response getCategory(@PathParam("groupid") int _groupId, @PathParam("categoryuuid") String _categoryUUID) throws Exception { UUID categoryUUID; try { categoryUUID = UUID.fromString(_categoryUUID); } catch (IllegalArgumentException e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); TypedQuery<Category> categoriesQuery = manager.createQuery( "select c from Category c " + "where c.group = :groupid and c.UUID = :uuid", Category.class); categoriesQuery.setParameter("groupid", group); categoriesQuery.setParameter("uuid", categoryUUID); List<Category> categories = categoriesQuery.getResultList(); if (categories.size() != 1) { TypedQuery<DeletedObject> deletedCategoriesQuery = manager .createQuery("select do " + "from DeletedObject do where do.group = :groupid and " + "do.type = :type and do.UUID = :uuid", DeletedObject.class); deletedCategoriesQuery.setParameter("groupid", group); deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY); deletedCategoriesQuery.setParameter("uuid", categoryUUID); List<DeletedObject> deletedCategories = deletedCategoriesQuery.getResultList(); manager.close(); if (deletedCategories.size() == 1) { CategoryInfo catInfo = new CategoryInfo(); catInfo.setDeleted(true); catInfo.setLastChanged(Date.from(deletedCategories.get(0).getUpdated())); catInfo.setUUID(categoryUUID); return ResponseFactory.generateGone(catInfo); } else { return ResponseFactory.generateNotFound(new Error().withMessage("Category was not" + " found.")); } } manager.close(); CategoryInfo catInfo = new CategoryInfo(); catInfo.setDeleted(false); catInfo.setLastChanged(Date.from(categories.get(0).getUpdated())); catInfo.setName(categories.get(0).getName()); catInfo.setUUID(categoryUUID); return ResponseFactory.generateOK(catInfo); }
From source file:com.esri.geoportal.commons.gpt.client.Client.java
private Date readLastUpdated(QueryResponse.Source source) { if (source != null && source.src_lastupdate_dt != null) { try {/*w w w . j ava 2 s .c o m*/ return Date.from(ZonedDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(source.src_lastupdate_dt)) .toInstant()); } catch (Exception ex) { } } return null; }
From source file:org.sonar.server.computation.task.projectanalysis.step.PeriodResolver.java
private static String formatDate(long date) { return DateUtils.formatDate(Date.from(new Date(date).toInstant().truncatedTo(ChronoUnit.SECONDS))); }
From source file:com.streamsets.pipeline.stage.origin.tcp.TCPObjectToRecordHandler.java
private void evaluateElAndSendResponse(ELEval eval, ELVars vars, String expression, ChannelHandlerContext ctx, Charset charset, boolean recordLevel, String expressionDescription) { if (Strings.isNullOrEmpty(expression)) { return;//from ww w .j a v a 2s . co m } if (lastRecord != null) { RecordEL.setRecordInContext(vars, lastRecord); } final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(timeZoneId))); TimeEL.setCalendarInContext(vars, calendar); TimeNowEL.setTimeNowInContext(vars, Date.from(ZonedDateTime.now().toInstant())); final String elResult; try { elResult = eval.eval(vars, expression, String.class); ctx.writeAndFlush(Unpooled.copiedBuffer(elResult, charset)); } catch (ELEvalException exception) { if (LOG.isErrorEnabled()) { LOG.error(String.format("ELEvalException caught attempting to evaluate %s expression", expressionDescription), exception); } if (recordLevel) { switch (context.getOnErrorRecord()) { case DISCARD: // do nothing break; case STOP_PIPELINE: if (LOG.isErrorEnabled()) { LOG.error(String.format( "ELEvalException caught when evaluating %s expression to send client response; failing pipeline %s" + " as per stage configuration: %s", expressionDescription, context.getPipelineId(), exception.getMessage()), exception); } stopPipelineHandler.stopPipeline(context.getPipelineId(), exception); break; case TO_ERROR: Record errorRecord = lastRecord != null ? lastRecord : context.createRecord(generateRecordId()); batchContext.toError(errorRecord, exception); break; } } else { context.reportError(Errors.TCP_35, expressionDescription, exception.getMessage(), exception); } } }
From source file:org.dbflute.solr.cbean.SolrQueryBuilder.java
public static String queryBuilderForRangeSearch(String solrFieldName, LocalDate from, LocalDate to) { Date fromDate = from == null ? null : Date.from(ZonedDateTime.of(from, LocalTime.MIDNIGHT, ZoneId.systemDefault()).toInstant()); Date toDate = to == null ? null : Date.from(ZonedDateTime.of(to, LocalTime.MIDNIGHT, ZoneId.systemDefault()).toInstant()); return queryBuilderForRangeSearch(solrFieldName, fromDate, toDate); }