List of usage examples for java.time ZoneId systemDefault
public static ZoneId systemDefault()
From source file:com.bdb.weather.display.stripchart.StripChart.java
/** * Add an item to a series./*from ww w . jav a2s . c o 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:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java
@SuppressWarnings("unchecked") public static <T> Optional<T> tryCast(Object val, final Class<T> expected) { if (val == null) { return Optional.empty(); }/*from w w w . ja v a 2 s.c om*/ if (expected == null) { throw new IllegalArgumentException("Must provide an expected class!"); } if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) { return tryCast(((BaseValue<?>) val).get(), expected); } if (val instanceof Supplier) { Supplier<?> fun = (Supplier<?>) val; return tryCast(fun.get(), expected); } if (Text.class.isAssignableFrom(expected)) { if (val instanceof Text) { return TypeUtils.tryOptional(() -> expected.cast(val)); } else { if (val instanceof ItemStack) { return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val))); } if (val instanceof Instant) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(PlaceholderAPIPlugin.getInstance().formatter() .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault()))))); } if (val instanceof Duration) { String dur = formatDuration((Duration) val); return TypeUtils .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur))); } if (val instanceof LocalDateTime) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize( PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val)))); } if (val instanceof CommandSource) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(String.valueOf(((CommandSource) val).getName())))); } if (val.getClass().isArray()) { List<Text> l2 = unboxPrimitiveArray(val).stream() .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } if (val instanceof Iterable) { Iterable<?> l = (Iterable<?>) val; // should be safe cause we already checked assignability @SuppressWarnings("serial") final List<Text> l2 = new ArrayList<Object>() { { for (Object o : l) { add(o); } } }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } return TypeUtils.tryOptional( () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val)))); } } if (val instanceof String) { if (String.class.isAssignableFrom(expected)) { return tryOptional(() -> expected.cast(val)); } if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(new String[] { v })); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(x)); } if (List.class.isAssignableFrom(expected) && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(Collections.singletonList(v))); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(Arrays.asList(x))); } Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected)); if (opt.isPresent()) { return opt; } opt = deserializers.entrySet().stream() .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected)) .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val))) .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o))); if (opt.isPresent()) { return opt; } try { // should theoretically match any string -> object conversions, such as deser // for now im filtering against method names as well just to avoid issues where // expected result is not obtained due to weird methods, might change in future Method method = Arrays.stream(expected.getDeclaredMethods()) .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class))) .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class)) .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no Object valout = method.invoke(null, (String) val); if (valout == null) { return Optional.empty(); } if (expected.isInstance(valout)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { return expected.cast(mh.invokeExact((String) val)); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(valout)); } if (valout instanceof Optional) { Optional<?> valopt = (Optional<?>) valout; if (!valopt.isPresent()) { return Optional.empty(); } Object v = valopt.get(); if (expected.isInstance(v)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { Optional<?> optx = (Optional<?>) mh.invokeExact((String) val); return expected.cast(optx.get()); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(v)); } else { return Optional.empty(); } } return Optional.empty(); } catch (Exception e) { // fires if no method found, if invoke throws, if something else goes wrong return Optional.empty(); } } return TypeUtils.tryOptional(() -> expected.cast(val)); }
From source file:dk.dbc.rawrepo.oai.OAIIdentifierCollectionIT.java
private void loadRecordsFrom(String... jsons) throws SQLException, IOException { Connection connection = pg.getConnection(); connection.prepareStatement("SET TIMEZONE TO 'UTC'").execute(); try (PreparedStatement rec = connection .prepareStatement("INSERT INTO oairecords (pid, changed, deleted) VALUES(?, ?::timestamp, ?)"); PreparedStatement recSet = connection .prepareStatement("INSERT INTO oairecordsets (pid, setSpec) VALUES(?, ?)")) { for (String json : jsons) { InputStream is = getClass().getClassLoader().getResourceAsStream(json); if (is == null) { throw new RuntimeException("Cannot find: " + json); }/* www . j a v a 2 s . com*/ ObjectMapper objectMapper = new ObjectMapper(); List<ObjectNode> array = objectMapper.readValue(is, List.class); for (Object object : array) { Map<String, Object> obj = (Map<String, Object>) object; rec.setString(1, (String) obj.get("pid")); rec.setString(2, (String) obj.getOrDefault("changed", DateTimeFormatter.ISO_INSTANT.format(Instant.now().atZone(ZoneId.systemDefault())))); rec.setBoolean(3, (boolean) obj.getOrDefault("deleted", false)); rec.executeUpdate(); recSet.setString(1, (String) obj.get("pid")); List<Object> sets = (List<Object>) obj.get("sets"); for (Object set : sets) { recSet.setString(2, (String) set); recSet.executeUpdate(); } } } } catch (SQLException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java
@Override @Transactional(readOnly = false)//w ww. j a va 2s . co 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.briljantframework.data.resolver.Resolve.java
private static Resolver<LocalDate> initializeLocalDateResolver() { Resolver<LocalDate> resolver = new Resolver<>(LocalDate.class); Converter<Long, LocalDate> longToLocalDate = (l) -> Instant.ofEpochMilli(l).atZone(ZoneId.systemDefault()) .toLocalDate();/*from ww w.j a v a 2 s. c o m*/ resolver.put(String.class, StringToLocalDate.ISO_DATE); resolver.put(Long.class, longToLocalDate); resolver.put(Long.TYPE, longToLocalDate); return resolver; }
From source file:org.openlmis.fulfillment.web.ShipmentControllerIntegrationTest.java
@Test public void shouldCreateShipment() { Order shipmentOrder = shipment.getOrder(); shipmentOrder.setStatus(OrderStatus.ORDERED); when(orderRepository.findOne(shipment.getOrder().getId())).thenReturn(shipment.getOrder()); //necessary as SaveAnswer change shipment id value also in captor when(shipmentRepository.save(any(Shipment.class))).thenReturn(shipment); when(proofOfDeliveryRepository.save(any(ProofOfDelivery.class))).thenReturn(proofOfDelivery); ShipmentDto extracted = restAssured.given().header(HttpHeaders.AUTHORIZATION, getTokenHeader()) .contentType(APPLICATION_JSON_VALUE).body(shipmentDto).when().post(RESOURCE_URL).then() .statusCode(201).extract().as(ShipmentDto.class); shipmentOrder.setStatus(OrderStatus.SHIPPED); shipmentOrder.setUpdateDetails(new UpdateDetails(INITIAL_USER_ID, ZonedDateTime.of(2015, 5, 7, 10, 5, 20, 500, ZoneId.systemDefault()))); assertEquals(shipmentDtoExpected, extracted); verify(orderRepository).save(shipmentOrder); verify(shipmentRepository).save(captor.capture()); verify(stockEventBuilder).fromShipment(any(Shipment.class)); verify(stockEventService).submit(any(StockEventDto.class)); assertTrue(reflectionEquals(shipment, captor.getValue(), singletonList("id"))); assertNull(captor.getValue().getId()); assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.responseChecks()); }
From source file:am.ik.categolj3.api.git.GitStore.java
Author author(RevCommit commit) { String name = commit != null ? commit.getAuthorIdent().getName() : ""; Date date = commit != null ? commit.getAuthorIdent().getWhen() : new Date(); OffsetDateTime o = OffsetDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return new Author(name, o); }
From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactoryTest.java
@Test public void when_purge_errored_jobs_and_jobs_in_error_exist_it_should_delete_job_which_pass_expiration() { Job jobNotExpired = new Job(); jobNotExpired.setUpdatedAt(new Date()); Date date = new Date(); LocalDateTime localDateTime = LocalDateTime.from(date.toInstant().atZone(ZoneId.systemDefault())) .minusDays(jobErroredDeleteExpirationDays + 1); Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); Job jobExpired = new Job(); jobExpired.setUpdatedAt(Date.from(instant)); when(jobRepo.findByJobEventOrderByUpdatedAtDesc(anyObject())) .thenReturn(Arrays.asList(jobNotExpired, jobExpired)); jobFactory.purgeErroredJobs();//from w w w. ja va 2 s .c o m verify(jobRepo, times(1)).delete((Job) notNull()); }
From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java
/** * copy participant info//from w ww .j a va 2 s .c o m */ private ParticipantType copyParticipant(ObjectFactory factory, Participant part) { final ParticipantType retVal = factory.createParticipantType(); if (part.getId() != null) retVal.setId(part.getId()); retVal.setName(part.getName()); final LocalDate bday = part.getBirthDate(); if (bday != null) { try { final DatatypeFactory df = DatatypeFactory.newInstance(); final XMLGregorianCalendar cal = df .newXMLGregorianCalendar(GregorianCalendar.from(bday.atStartOfDay(ZoneId.systemDefault()))); cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED); retVal.setBirthday(cal); } catch (DatatypeConfigurationException e) { LOGGER.log(Level.WARNING, e.toString(), e); } } final Period age = part.getAge(null); if (age != null) { try { final DatatypeFactory df = DatatypeFactory.newInstance(); final Duration ageDuration = df.newDuration(true, age.getYears(), age.getMonths(), age.getDays(), 0, 0, 0); retVal.setAge(ageDuration); } catch (DatatypeConfigurationException e) { LOGGER.log(Level.WARNING, e.toString(), e); } } retVal.setEducation(part.getEducation()); retVal.setGroup(part.getGroup()); final String lang = part.getLanguage(); final String langs[] = (lang != null ? lang.split(",") : new String[0]); for (String l : langs) { retVal.getLanguage().add(StringUtils.strip(l)); } if (part.getSex() == Sex.MALE) retVal.setSex(SexType.MALE); else if (part.getSex() == Sex.FEMALE) retVal.setSex(SexType.FEMALE); ParticipantRole prole = part.getRole(); if (prole == null) prole = ParticipantRole.TARGET_CHILD; retVal.setRole(prole.toString()); // create ID based on role if possible if (retVal.getId() == null && prole != null) { if (prole == ParticipantRole.TARGET_CHILD) { retVal.setId("CHI"); } else if (prole == ParticipantRole.MOTHER) { retVal.setId("MOT"); } else if (prole == ParticipantRole.FATHER) { retVal.setId("FAT"); } else if (prole == ParticipantRole.INTERVIEWER) { retVal.setId("INT"); } else { retVal.setId("p" + (++pIdx)); } } retVal.setSES(part.getSES()); return retVal; }
From source file:io.stallion.settings.Settings.java
public void assignDefaults() { if (getLocalMode() == null) { if (empty(System.getenv().getOrDefault("STALLION_DEPLOY_TIME", ""))) { setLocalMode(true);//from w w w .ja v a 2 s .co m } else { setLocalMode(false); } } if (bundleDebug == null) { bundleDebug = getLocalMode(); } if (getDebug() == null) { if (getEnv().equals("prod") && !getLocalMode()) { setDebug(false); } else { setDebug(true); } } if (timeZone == null) { timeZone = ZoneId.systemDefault().toString(); } if (timeZoneId == null) { timeZoneId = ZoneId.of(timeZone); } if (logFile == null) { String nowString = DateUtils.formatNow("yyyy-MM-dd-HHmmss"); String base = ""; try { if (!empty(siteUrl)) { base = new URL(siteUrl.replace(":{port}", "")).getHost(); } } catch (IOException e) { Log.exception(e, "Error parsing siteUrl " + siteUrl); } logFile = "/tmp/log/stallion/" + base + "-" + nowString + "-" + StringUtils.strip(GeneralUtils.slugify(targetFolder), "-") + ".log"; } if (logToConsole == null) { logToConsole = getLocalMode(); } if (logToFile == null) { logToFile = !logToConsole; } if (getEmailErrors() == null) { if ((getEnv().equals("prod") || getEnv().equals("qa")) && !getLocalMode()) { setEmailErrors(true); } else { setEmailErrors(false); } } if (getStrictnessLevel() == null) { if (getEnv().equals("prod") && !getLocalMode()) { setStrictnessLevel(StrictnessLevel.LAX); } else { setStrictnessLevel(StrictnessLevel.STRICT); } } if (!empty(secondaryDomains)) { secondaryDomainByDomain = map(); for (SecondaryDomain d : secondaryDomains) { secondaryDomainByDomain.put(d.getDomain(), d); } } if (!StringUtils.isEmpty(getDataDirectory())) { if (!getDataDirectory().startsWith("/")) { setDataDirectory(targetFolder + "/" + getDataDirectory()); } } else { setDataDirectory(targetFolder + "/app-data"); } if (getDataDirectory().endsWith("/")) { setDataDirectory(getDataDirectory().substring(0, getDataDirectory().length() - 1)); } if (getRewrites() != null) { // THe Toml library has a bug whereby if a map key is quoted, it keeps the // quotes as part of the key, rather than using the String inside the quotes Set<String> keys = new HashSet<>(getRewrites().keySet()); for (String key : keys) { if (key.startsWith("\"") && key.endsWith("\"")) { getRewrites().put(key.substring(1, key.length() - 1), getRewrites().get(key)); } } } if (getRedirects() != null) { // THe Toml library has a bug whereby if a map key is quoted, it keeps the // quotes as part of the key, rather than using the String inside the quotes Set<String> keys = new HashSet<>(getRedirects().keySet()); for (String key : keys) { if (key.startsWith("\"") && key.endsWith("\"")) { getRedirects().put(key.substring(1, key.length() - 1), getRedirects().get(key)); } } } if (getRewritePatterns() != null && getRewritePatterns().size() > 0) { if (rewriteCompiledPatterns == null) { rewriteCompiledPatterns = new ArrayList(); } for (String[] entry : getRewritePatterns()) { if (entry.length != 2) { Log.warn("Invalid rewritePatterns entry, size should be 2 but is {0} {1}", entry.length, entry); } Pattern pattern = Pattern.compile(entry[0]); Map.Entry<Pattern, String> kv = new AbstractMap.SimpleEntry<Pattern, String>(pattern, entry[1]); getRewriteCompiledPatterns().add(kv); } } if (getEmail() != null) { // By default, in debug mode, we do not want to send real emails to people if (getEmail().getRestrictOutboundEmails() == null) { getEmail().setRestrictOutboundEmails(getDebug()); } if (getEmail().getOutboundEmailTestAddress() == null) { if (getEmail().getAdminEmails() != null && getEmail().getAdminEmails().size() > 0) { getEmail().setOutboundEmailTestAddress(getEmail().getAdminEmails().get(0)); } } if (!empty(getEmail().getAllowedTestingOutboundEmailPatterns())) { if (getEmail().getAllowedTestingOutboundEmailCompiledPatterns() == null) { getEmail().setAllowedTestingOutboundEmailCompiledPatterns(new ArrayList<>()); } for (String emailPattern : getEmail().getAllowedTestingOutboundEmailPatterns()) { getEmail().getAllowedTestingOutboundEmailCompiledPatterns().add(Pattern.compile(emailPattern)); } } } if (getSecrets() == null) { setSecrets(new SecretsSettings()); } if (new File(targetFolder + "/pages").isDirectory()) { if (folders == null) { folders = new ArrayList<>(); } folders.add(new ContentFolder().setPath(targetFolder + "/pages").setType("markdown") .setItemTemplate(getPageTemplate())); } if (userUploads != null && empty(userUploads.getUploadsDirectory())) { userUploads.setUploadsDirectory(getDataDirectory() + "/st-user-file-uploads"); } }