Java Examples for java.time.format.DateTimeFormatter
The following java examples will help you to understand the usage of java.time.format.DateTimeFormatter. These source code samples are taken from different open source projects.
Example 1
| Project: spring-framework-master File: DateTimeFormatterFactory.java View source code |
/**
* Create a new {@code DateTimeFormatter} using this factory.
* <p>If no specific pattern or style has been defined,
* the supplied {@code fallbackFormatter} will be used.
* @param fallbackFormatter the fall-back formatter to use when no specific
* factory properties have been set (can be {@code null}).
* @return a new date time formatter
*/
public DateTimeFormatter createDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
DateTimeFormatter dateTimeFormatter = null;
if (StringUtils.hasLength(this.pattern)) {
// Using strict parsing to align with Joda-Time and standard DateFormat behavior:
// otherwise, an overflow like e.g. Feb 29 for a non-leap-year wouldn't get rejected.
// However, with strict parsing, a year digit needs to be specified as 'u'...
String patternToUse = this.pattern.replace("yy", "uu");
dateTimeFormatter = DateTimeFormatter.ofPattern(patternToUse).withResolverStyle(ResolverStyle.STRICT);
} else if (this.iso != null && this.iso != ISO.NONE) {
switch(this.iso) {
case DATE:
dateTimeFormatter = DateTimeFormatter.ISO_DATE;
break;
case TIME:
dateTimeFormatter = DateTimeFormatter.ISO_TIME;
break;
case DATE_TIME:
dateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME;
break;
case NONE:
/* no-op */
break;
default:
throw new IllegalStateException("Unsupported ISO format: " + this.iso);
}
} else if (this.dateStyle != null && this.timeStyle != null) {
dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(this.dateStyle, this.timeStyle);
} else if (this.dateStyle != null) {
dateTimeFormatter = DateTimeFormatter.ofLocalizedDate(this.dateStyle);
} else if (this.timeStyle != null) {
dateTimeFormatter = DateTimeFormatter.ofLocalizedTime(this.timeStyle);
}
if (dateTimeFormatter != null && this.timeZone != null) {
dateTimeFormatter = dateTimeFormatter.withZone(this.timeZone.toZoneId());
}
return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
}Example 2
| Project: asta4d-master File: String2Java8Instant.java View source code |
@Override
protected Instant convert2Target(DateTimeFormatter formatter, String obj) {
TemporalAccessor temporal = formatter.parse(obj);
if (temporal instanceof Instant) {
return (Instant) temporal;
}
Objects.requireNonNull(temporal, "temporal");
try {
long instantSecs = temporal.getLong(INSTANT_SECONDS);
int nanoOfSecond = temporal.get(NANO_OF_SECOND);
return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
} catch (DateTimeException e) {
ZonedDateTime zdt;
try {
LocalDateTime ldt = LocalDateTime.from(temporal);
zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
} catch (DateTimeException ex) {
zdt = ZonedDateTime.of(LocalDate.from(temporal).atStartOfDay(), ZoneId.systemDefault());
}
return zdt.toInstant();
}
}Example 3
| Project: fastjson-master File: Issue952.java View source code |
public void test_for_issue() throws Exception {
final String pattern = "yyyy-MM-dd'T'HH:mm:ss";
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
String text = JSON.toJSONString(dateTime, SerializerFeature.UseISO8601DateFormat);
assertEquals(JSON.toJSONString(formatter.format(dateTime)), text);
}Example 4
| Project: hazelcast-examples-master File: HazelcastReplicatedMapExample.java View source code |
public static void main(String[] args) {
String mapName;
int entrySize;
if (args.length > 1) {
mapName = args[0];
entrySize = Integer.decode(args[1]);
} else {
mapName = "default";
entrySize = 20;
}
Instant start = Instant.now();
HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(new ClasspathXmlConfig("hazelcast.xml"));
Map<String, String> map = hazelcast.getReplicatedMap(mapName);
if (map instanceof ReplicatedMap) {
ReplicatedMap<String, String> rmap = (ReplicatedMap<String, String>) map;
rmap.addEntryListener(new MyEntryListener());
} else if (map instanceof IMap) {
IMap<String, String> rmap = (IMap<String, String>) map;
rmap.addEntryListener(new MyEntryListener(), true);
}
String lastKey = "key" + entrySize;
System.out.printf("last-key = [%s], value = [%s], exists = [%b]%n", lastKey, map.get("key" + entrySize), map.containsKey("key" + entrySize));
Instant createdTime = Instant.now();
Duration timeElapsed = Duration.between(start, createdTime);
System.out.printf("Cluster Joined Time = [%d] millis%n", timeElapsed.toMillis());
IntStream.rangeClosed(1, entrySize).forEach( i -> map.put("key" + i, "value" + i));
System.out.printf("[%s] Hazelcast Node, startup, putted [%d]entries.%n", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), entrySize);
System.console().readLine("Enter, shutdown...");
IntStream.rangeClosed(1, entrySize).forEach( i -> {
String key = "key" + i;
String value = map.get(key);
System.out.printf("Key = [%s], Value = [%s]%n", key, value);
});
hazelcast.getLifecycleService();
Hazelcast.shutdownAll();
}Example 5
| Project: btpka3.github.com-master File: DurationTest.java View source code |
public static void main(String[] args) throws InterruptedException {
// æ ¼å¼?化时间
LocalDateTime date = LocalDateTime.now();
String text = date.format(DateTimeFormatter.ISO_DATE_TIME);
LocalDateTime parsedDate = LocalDateTime.parse(text, DateTimeFormatter.ISO_DATE_TIME);
System.out.println("1.1 - " + date);
System.out.println("1.2 - " + text);
System.out.println("1.3 - " + parsedDate);
// 打�时间段
long start = System.currentTimeMillis();
Duration duration = Duration.ZERO.plusMillis(start);
System.out.println("2.1 - " + duration);
}Example 6
| Project: framework-master File: ComponentElementGetValueTest.java View source code |
@Test
public void checkDateField() {
DateFieldElement df = $(DateFieldElement.class).get(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String expected = formatter.format(ComponentElementGetValue.TEST_DATE_VALUE);
String actual = df.getValue();
Assert.assertEquals(expected, actual);
}Example 7
| Project: guide-master File: LocalTime1.java View source code |
public static void main(String[] args) {
// get the current time
Clock clock = Clock.systemDefaultZone();
long t0 = clock.millis();
System.out.println(t0);
Instant instant = clock.instant();
Date legacyDate = Date.from(instant);
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
// time
LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now1);
System.out.println(now2);
// false
System.out.println(now1.isBefore(now2));
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
System.out.println(hoursBetween);
System.out.println(minutesBetween);
// create time
LocalTime now = LocalTime.now();
System.out.println(now);
LocalTime late = LocalTime.of(23, 59, 59);
System.out.println(late);
DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.GERMAN);
LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
System.out.println(leetTime);
// to legacy date
}Example 8
| Project: jackson-datatype-jsr310-master File: DurationSerializer.java View source code |
@Override
public void serialize(Duration duration, JsonGenerator generator, SerializerProvider provider) throws IOException {
if (useTimestamp(provider)) {
if (provider.isEnabled(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)) {
generator.writeNumber(DecimalUtils.toBigDecimal(duration.getSeconds(), duration.getNano()));
} else {
generator.writeNumber(duration.toMillis());
}
} else {
// Does not look like we can make any use of DateTimeFormatter here?
generator.writeString(duration.toString());
}
}Example 9
| Project: java8-tutorial-master File: LocalTime1.java View source code |
public static void main(String[] args) {
// get the current time
Clock clock = Clock.systemDefaultZone();
long t0 = clock.millis();
System.out.println(t0);
Instant instant = clock.instant();
Date legacyDate = Date.from(instant);
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
// time
LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now1);
System.out.println(now2);
// false
System.out.println(now1.isBefore(now2));
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
System.out.println(hoursBetween);
System.out.println(minutesBetween);
// create time
LocalTime now = LocalTime.now();
System.out.println(now);
LocalTime late = LocalTime.of(23, 59, 59);
System.out.println(late);
DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.GERMAN);
LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
System.out.println(leetTime);
// to legacy date
}Example 10
| Project: vaadin-master File: ComponentElementGetValueTest.java View source code |
@Test
public void checkDateField() {
DateFieldElement df = $(DateFieldElement.class).get(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String expected = formatter.format(ComponentElementGetValue.TEST_DATE_VALUE);
String actual = df.getValue();
Assert.assertEquals(expected, actual);
}Example 11
| Project: levelup-java-examples-master File: GenerateRandomDate.java View source code |
@Test
public void generate_random_date_java8() {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
for (int x = 0; x < 7; x++) {
Instant instant = Instant.ofEpochSecond(getRandomTimeBetweenTwoDates());
LocalDateTime randomDate = LocalDateTime.ofInstant(instant, ZoneId.of("UTC-06:00"));
logger.info(randomDate.format(format));
assertThat(randomDate.atZone(ZoneId.of("UTC-06:00")).toEpochSecond(), allOf(lessThanOrEqualTo(endTime), greaterThanOrEqualTo(beginTime)));
}
}Example 12
| Project: brew-master File: ReportingRepository.java View source code |
public void createOrUpdate(Event event) {
BeerEvents beerEvents = eventsDatabase.getOrDefault(event.getProcessId(), new BeerEvents());
LocalDateTime time = event.getEventTime();
String convertedTime = DateTimeFormatter.ISO_DATE_TIME.format(time);
switch(event.getEventType()) {
case INGREDIENTS_ORDERED:
beerEvents.setIngredientsOrderedTime(convertedTime);
break;
case BREWING_STARTED:
beerEvents.setBrewingStartedTime(convertedTime);
break;
case BEER_MATURED:
beerEvents.setBeerMaturedTime(convertedTime);
break;
case BEER_BOTTLED:
beerEvents.setBeerBottledTime(convertedTime);
break;
}
eventsDatabase.put(event.getProcessId(), beerEvents);
}Example 13
| Project: com.packtpub.e4-master File: ShowTheTime.java View source code |
@Execute
public void execute(ESelectionService selectionService) {
Object selection = selectionService.getSelection();
if (selection instanceof ZoneId) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
String theTime = ZonedDateTime.now((ZoneId) selection).format(formatter);
MessageDialog.openInformation(null, "The time is", theTime);
}
}Example 14
| Project: LambdaDojo-master File: S203LambdaInsteadOfAnonClass.java View source code |
@Override
public void run() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
for (; ; ) {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println(LocalTime.now().format(formatter));
} catch (InterruptedException ex) {
return;
}
}
}Example 15
| Project: magarena-master File: StartTimeCellRenderer.java View source code |
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int col) {
final LocalDateTime gameStart = getLocalTimeFromEpoch(Long.parseLong((String) value));
final JLabel lbl = new JLabel(gameStart.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
lbl.setOpaque(true);
if (isSelected) {
lbl.setForeground(table.getSelectionForeground());
lbl.setBackground(table.getSelectionBackground());
} else {
lbl.setForeground(table.getForeground());
lbl.setBackground(table.getBackground());
}
// lbl.setBorder(noFocusBorder);
return lbl;
}Example 16
| Project: OpenLegislation-master File: ActiveListDAOTest.java View source code |
@Test
public void test() throws Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse("2000-01-02 12:12:12", formatter);
//ActiveListSpotcheckReference a = activeReference.getCalendarReference(new CalendarActiveListId(5, 2000, 0), dateTime);
/*ActiveListSpotcheckReference a = activeReference.getMostRecentReference(new CalendarActiveListId(5, 2000, 0));
System.out.println("\n\nSequence no: " + a.getSequenceNo());
System.out.println("CalendarId YEAR: " + a.getCalendarId().getYear());
System.out.println("CaeldnarId CALNO: " + a.getCalendarId().getCalNo());
System.out.println("CalDate: " + a.getCalDate());
System.out.println("ReportDate: " + a.getReferenceDate());
System.out.println("ReleaseDateTime: " + a.getReleaseDateTime());
*/
//ArrayList<ActiveListSpotcheckReference> thing = new ArrayList<> (activeReference.getMostRecentEachYear(2000));
//GGGGGGGGGGGGGGGGGGGGGGGGGGET ALL ENTRIES IN AN ACTIVE LIST
/*ArrayList<ActiveListSpotcheckReference> thing = (ArrayList)activeReference.getMostRecentEachYear(2000);
for (ActiveListSpotcheckReference a : thing){
System.out.println("\nNew list ");
System.out.println("\nSequence no: " + a.getSequenceNo());
System.out.println("CalendarId YEAR: " + a.getCalendarId().getYear());
System.out.println("CaeldnarId CALNO: " + a.getCalendarId().getCalNo());
System.out.println("CalDate: " + a.getCalDate());
System.out.println("ReportDate: " + a.getReferenceDate());
System.out.println("ReleaseDateTime: " + a.getReleaseDateTime());
}*/
// public CalendarActiveListEntry(Integer calNo, BillId billId)
List<CalendarEntry> entries = new ArrayList<CalendarEntry>();
entries.add(new CalendarEntry(1, new BillId("bill1", 2010, "a")));
entries.add(new CalendarEntry(2, new BillId("bill2", 2010, "b")));
entries.add(new CalendarEntry(3, new BillId("bill3", 2010, "c")));
DateTimeFormatter formatterCalDate = DateTimeFormatter.ofPattern("MMMM-dd-yyyy");
//String text = ;
LocalDate calDate = LocalDate.parse("July-24-2010", formatterCalDate);
String releasedDT = "12/04/2010 10:50 AM";
//LocalDateTime releasedDateTime = LocalDateTime.parse(releasedDT, DateUtils.LRS_WEBSITE_DATETIME_FORMAT);
LocalDateTime reportDate = LocalDateTime.now();
//1000 milliseconds is one second.
Thread.sleep(1000);
LocalDateTime releaseTimeNow = LocalDateTime.now();
activeReference.addCalendarReference(new ActiveListSpotcheckReference(2, new CalendarId(2000, 2000), calDate, releaseTimeNow, reportDate, entries));
//logger.info(OutputUtils.toJson("<a>"));
}Example 17
| Project: semiot-platform-master File: ZoneDateTimeProvider.java View source code |
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
if (rawType.getName().equals(java.time.ZonedDateTime.class.getName())) {
return new ParamConverter<T>() {
@Override
public T fromString(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
java.time.ZonedDateTime dateTime = java.time.ZonedDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
return rawType.cast(dateTime);
}
}
@Override
public String toString(T value) {
if (value instanceof ZonedDateTime) {
return ((ZonedDateTime) value).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
return null;
}
};
}
return null;
}Example 18
| Project: SIA-master File: ServerRequestJSONTest.java View source code |
@Test
public void testTimeStamps() throws Exception {
ServerRequest serverRequest = customObjectMapper.readValue(Resources.getResource("samplepayloadGetannotations.json"), ServerRequest.class);
assertThat(serverRequest.getParameters().getExpired()).isNotNull().isEqualTo(Date.from(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse("2017-02-22T03:14:00+01:00", Instant::from)));
}Example 19
| Project: SimpleFlatMapper-master File: JavaTimeHelper.java View source code |
public static DateTimeFormatter getDateTimeFormatter(Object... properties) { ZoneId zoneId = getZoneId(properties); DefaultDateFormatSupplier defaultDateFormatSupplier = null; for (Object prop : properties) { DateTimeFormatter dateTimeFormatter = toDateTimeFormatter(prop, zoneId); if (dateTimeFormatter != null) { return dateTimeFormatter; } else if (prop instanceof DefaultDateFormatSupplier) { defaultDateFormatSupplier = (DefaultDateFormatSupplier) prop; } } if (defaultDateFormatSupplier != null) { return withZone(defaultDateFormatSupplier.get(), zoneId); } return null; }
Example 20
| Project: assertj-core-master File: ZonedDateTimeAssert_isAfter_Test.java View source code |
@Theory
public void test_isAfter_assertion(ZonedDateTime referenceDate, ZonedDateTime dateBefore, ZonedDateTime dateAfter) {
// GIVEN
testAssumptions(referenceDate, dateBefore, dateAfter);
// WHEN
assertThat(dateAfter).isAfter(referenceDate);
assertThat(dateAfter).isAfter(referenceDate.format(DateTimeFormatter.ISO_DATE_TIME));
// THEN
verify_that_isAfter_assertion_fails_and_throws_AssertionError(referenceDate, referenceDate);
verify_that_isAfter_assertion_fails_and_throws_AssertionError(dateBefore, referenceDate);
}Example 21
| Project: java-driver-master File: LocalDateCodec.java View source code |
@Override
public java.time.LocalDate parse(String value) {
if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
return null;
// strip enclosing single quotes, if any
if (isQuoted(value))
value = unquote(value);
if (isLongLiteral(value)) {
long raw;
try {
raw = parseLong(value);
} catch (NumberFormatException e) {
throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
}
int days;
try {
days = fromCqlDateToDaysSinceEpoch(raw);
} catch (IllegalArgumentException e) {
throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
}
return EPOCH.plusDays(days);
}
try {
return java.time.LocalDate.parse(value, java.time.format.DateTimeFormatter.ISO_LOCAL_DATE);
} catch (RuntimeException e) {
throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
}
}Example 22
| Project: mapstruct-master File: AbstractJavaTimeToStringConversion.java View source code |
private String parametersListForParsing(ConversionContext conversionContext) {
// See http://docs.oracle.com/javase/tutorial/datetime/iso/format.html for how to format Dates
StringBuilder parameterBuilder = new StringBuilder("<SOURCE>");
if (!Strings.isEmpty(conversionContext.getDateFormat())) {
parameterBuilder.append(", DateTimeFormatter.ofPattern( \"").append(conversionContext.getDateFormat()).append("\" )");
}
return parameterBuilder.toString();
}Example 23
| Project: asciiblog-master File: FormatDateTag.java View source code |
@Override
public void doTag() throws JspException, IOException {
final String format;
if (rfc1123)
format = DateTimeFormatter.RFC_1123_DATE_TIME.format(value.atStartOfDay(ZoneOffset.UTC));
else
format = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy", Locale.ENGLISH).format(value).toLowerCase();
JspWriter out = getJspContext().getOut();
out.print(format);
}Example 24
| Project: betsy-master File: EngineTableGenerator.java View source code |
private static void generateEnginesJson() {
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("engines.tex"), StandardOpenOption.CREATE)) {
writer.write("Language & Name & Version & License & Developed in & Released at & Configurations\\\\");
writer.newLine();
List<EngineExtended> engines = getEngines().stream().filter( e -> !(e instanceof VirtualEngineAPI)).map( e -> ((IsEngine) e).getEngineObject()).collect(Collectors.toList());
Collections.sort(engines, Comparator.comparing(EngineExtended::getLanguage).thenComparing(EngineExtended::getName).thenComparing(EngineExtended::getVersion));
for (EngineExtended engine : engines) {
String line = String.join(" & ", Arrays.asList(engine.getLanguage().getId(), engine.getName(), engine.getVersion(), engine.getLicense(), engine.getProgrammingLanguage(), DateTimeFormatter.ISO_LOCAL_DATE.format(engine.getReleaseDate()), String.join(", ", engine.getConfiguration()))) + "\\\\";
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}Example 25
| Project: core-ng-project-master File: ActionLogger.java View source code |
private String actionLogMessage(ActionLog log) {
StringBuilder builder = new StringBuilder(256);
builder.append(DateTimeFormatter.ISO_INSTANT.format(log.date)).append(LOG_SPLITTER).append(log.result()).append(LOG_SPLITTER).append("elapsed=").append(log.elapsed).append(LOG_SPLITTER).append("id=").append(log.id).append(LOG_SPLITTER).append("action=").append(log.action);
if (log.refId != null) {
builder.append(LOG_SPLITTER).append("refId=").append(log.refId);
}
String errorCode = log.errorCode();
if (errorCode != null) {
builder.append(LOG_SPLITTER).append("errorCode=").append(errorCode).append(LOG_SPLITTER).append("errorMessage=").append(filterLineSeparator(log.errorMessage));
}
builder.append(LOG_SPLITTER).append("cpuTime=").append(log.cpuTime);
for (Map.Entry<String, String> entry : log.context.entrySet()) {
builder.append(LOG_SPLITTER).append(entry.getKey()).append('=').append(filterLineSeparator(entry.getValue()));
}
for (Map.Entry<String, PerformanceStat> entry : log.performanceStats.entrySet()) {
String action = entry.getKey();
PerformanceStat tracking = entry.getValue();
builder.append(LOG_SPLITTER).append(action).append("Count=").append(tracking.count).append(LOG_SPLITTER).append(action).append("ElapsedTime=").append(tracking.totalElapsed);
}
builder.append(System.lineSeparator());
return builder.toString();
}Example 26
| Project: data-quality-master File: CustomDateTimePatternManager.java View source code |
private static DateTimeFormatter getDateTimeFormatterByPattern(String customPattern, Locale locale) { String localeStr = locale.toString(); DateTimeFormatter formatter = dateTimeFormatterCache.get(customPattern + localeStr); if (formatter == null) { try { formatter = DateTimeFormatter.ofPattern(customPattern, locale); } catch (IllegalArgumentException e) { return null; } dateTimeFormatterCache.put(customPattern + localeStr, formatter); } return formatter; }
Example 27
| Project: erlyberly-master File: CrashReportGraphic.java View source code |
private Label dateLabel(CrashReport report) {
String dateString = report.getDateTime().format(DateTimeFormatter.ISO_TIME);
Label label;
label = new Label(dateString);
// the date label is grey bold text that is slightly smaller than the main label
label.setStyle("-fx-font-size: 10; -fx-font-weight: bold; -fx-text-fill: #b2b2b2;");
return label;
}Example 28
| Project: fess-master File: UserInfo.java View source code |
@Override
protected void addFieldToSource(final Map<String, Object> sourceMap, final String field, final Object value) {
if (value instanceof LocalDateTime) {
final LocalDateTime ldt = (LocalDateTime) value;
final ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
super.addFieldToSource(sourceMap, field, DateTimeFormatter.ISO_INSTANT.format(zdt));
} else {
super.addFieldToSource(sourceMap, field, value);
}
}Example 29
| Project: find-master File: CurrentTimeWidgetITCase.java View source code |
@Test
public void testDayFormat() {
final WebElement webElement = page.getWidgets().get(0);
final String currentDay = webElement.findElement(By.cssSelector(".day")).getText();
final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("EEEE").toFormatter();
dateTimeFormatter.parse(currentDay);
}Example 30
| Project: forklift-master File: ReplayESWriter.java View source code |
@Override
protected void poll(ReplayESWriterMsg t) {
final String index = "forklift-replay-" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
// any previously created indexes.
try {
final SearchResponse resp = client.prepareSearch("forklift-replay*").setTypes("log").setQuery(QueryBuilders.termQuery("_id", t.getId())).setFrom(0).setSize(50).setExplain(false).execute().actionGet();
if (resp != null && resp.getHits() != null && resp.getHits().getHits() != null) {
for (SearchHit hit : resp.getHits().getHits()) {
if (!hit.getIndex().equals(index))
client.prepareDelete(hit.getIndex(), "log", t.getId()).execute().actionGet();
}
}
} catch (Exception e) {
log.error("", e);
log.error("Unable to search for old replay logs {}", t.getId());
}
// Index the new information.
client.prepareIndex(index, "log").setId(t.getId()).setSource(t.getFields()).execute().actionGet();
}Example 31
| Project: haikudepotserver-master File: AuthorizationRulesSpreadsheetJobRunner.java View source code |
@Override
public void run(JobService jobService, AuthorizationRulesSpreadsheetJobSpecification specification) throws IOException, JobRunnerException {
final ObjectContext context = serverRuntime.getContext();
DateTimeFormatter dateTimeFormatter = DateTimeHelper.createStandardDateTimeFormat();
// this will register the outbound data against the job.
JobDataWithByteSink jobDataWithByteSink = jobService.storeGeneratedData(specification.getGuid(), "download", MediaType.CSV_UTF_8.toString());
try (OutputStream outputStream = jobDataWithByteSink.getByteSink().openBufferedStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
CSVWriter writer = new CSVWriter(outputStreamWriter, ',')) {
writer.writeNext(new String[] { "create-timestamp", "user-nickname", "user-active", "permission-code", "permission-name", "pkg-name" });
SelectQuery query = new SelectQuery(PermissionUserPkg.class);
query.addOrdering(new Ordering(PermissionUserPkg.USER_PROPERTY + "." + User.NICKNAME_PROPERTY, SortOrder.ASCENDING));
query.addOrdering(new Ordering(PermissionUserPkg.PERMISSION_PROPERTY + "." + Permission.CODE_PROPERTY, SortOrder.ASCENDING));
query.setFetchLimit(LIMIT_GENERATECSV);
List<PermissionUserPkg> rules;
do {
rules = context.performQuery(query);
for (PermissionUserPkg rule : rules) {
writer.writeNext(new String[] { dateTimeFormatter.format(Instant.ofEpochMilli(rule.getCreateTimestamp().getTime())), rule.getUser().getNickname(), Boolean.toString(rule.getUser().getActive()), rule.getPermission().getCode(), rule.getPermission().getName(), null != rule.getPkg() ? rule.getPkg().getName() : "" });
}
query.setFetchOffset(query.getFetchOffset() + LIMIT_GENERATECSV);
} while (rules.size() >= LIMIT_GENERATECSV);
writer.flush();
outputStreamWriter.flush();
}
}Example 32
| Project: ipp-master File: ReaderOptions.java View source code |
public Optional<Path> getReplayFile() {
if (!actualReplayFile.isPresent()) {
synchronized (actualReplayFile) {
if (!actualReplayFile.isPresent()) {
if (!replayFile.equals("-")) {
actualReplayFile = Optional.of(Optional.of(Paths.get(replayFile)));
} else if (getReplayFileEnabled()) {
actualReplayFile = Optional.of(Optional.of(Paths.get(replayFilePrefix + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")) + ".json")));
} else {
actualReplayFile = Optional.of(Optional.empty());
}
}
}
}
return actualReplayFile.get();
}Example 33
| Project: javacuriosities-master File: Lesson09ParseAndFormat.java View source code |
public static void main(String[] args) {
String input = "20100102";
// Parseamos un String a un Fecha con el formato básico yyyyMMdd
LocalDate basicIsoDate = LocalDate.parse(input, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(basicIsoDate);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy");
input = "Jan 5 2014";
LocalDate date = LocalDate.parse(input, formatter);
System.out.println(date);
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departureFlight = ZonedDateTime.of(leaving, leavingZone);
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
String departureTime = departureFlight.format(format);
System.out.println("Leaving at: " + departureTime + " (" + leavingZone + ")");
}Example 34
| Project: Java_MVVM_with_Swing_and_RxJava_Examples-master File: Example_8_Model.java View source code |
public Observable<LogRow> getLogs() {
SerializedSubject<LogRow, LogRow> subject = new SerializedSubject<>(PublishSubject.create());
ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(Example_8_Model.class.getSimpleName() + "-thread-%d").build();
final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), threadFactory);
IntStream.range(1, Runtime.getRuntime().availableProcessors() + 1).forEach( value -> {
executorService.submit(() -> {
SysOutUtils.sysout(Thread.currentThread().getName() + " will briefly start creating lots of log rows...");
VariousUtils.sleep(1000);
long incrementingNumber = 1;
while (true) {
subject.onNext(new LogRow(DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()), "Status " + Integer.toString(ThreadLocalRandom.current().nextInt(1, 5)), "Action " + incrementingNumber + " from " + Thread.currentThread().getName()));
}
});
});
return subject;
}Example 35
| Project: jfxtras-master File: LocalTimeTextFieldBuilder.java View source code |
/**
* Implementation of Builder interface
*/
@Override
public LocalTimeTextField build() {
Locale lLocale = (iLocale == null ? Locale.getDefault() : iLocale);
LocalTimeTextField lLocalTimeTextField = new LocalTimeTextField();
if (iDateTimeFormatter != null)
lLocalTimeTextField.setDateTimeFormatter(DateTimeFormatter.ofPattern(iDateTimeFormatter).withLocale(lLocale));
//if (iLocale != null) lLocalTimeTextField.setLocale(iLocale);
if (iPromptText != null)
lLocalTimeTextField.setPromptText(iPromptText);
if (iDateTimeFormatters != null) {
ObservableList<DateTimeFormatter> lDateTimeFormatters = FXCollections.observableArrayList();
for (String lPart : iDateTimeFormatters) {
lDateTimeFormatters.add(DateTimeFormatter.ofPattern(lPart.trim()).withLocale(lLocale));
}
lLocalTimeTextField.setDateTimeFormatters(lDateTimeFormatters);
}
applyCommonProperties(lLocalTimeTextField);
return lLocalTimeTextField;
}Example 36
| Project: jooby-master File: LocalDateParser.java View source code |
private static LocalDate parse(final DateTimeFormatter formatter, final String value) {
try {
Instant epoch = Instant.ofEpochMilli(Long.parseLong(value));
ZonedDateTime zonedDate = epoch.atZone(Optional.ofNullable(formatter.getZone()).orElse(ZoneId.systemDefault()));
return zonedDate.toLocalDate();
} catch (NumberFormatException ex) {
return LocalDate.parse(value, formatter);
}
}Example 37
| Project: levelup-java-exercises-master File: MagicDates.java View source code |
public static void main(String[] args) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Ask user for input
System.out.print("Enter date in mm/dd/yyyy format:");
String dateAsString = keyboard.next();
// close stream
keyboard.close();
// Parse string to date
LocalDate date = LocalDate.parse(dateAsString, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
// check date and display output
if (magicDate(date)) {
System.out.println("That date is magic!");
} else {
System.out.println("Sorry, nothing magic about that date...");
}
}Example 38
| Project: molecule-master File: HttpDate.java View source code |
public static Instant parse(String httpDate) {
for (DateTimeFormatter format : POSSIBLE_FORMATS) {
try {
// Ignore timezone component as all HTTP dates should be represented in UTC
return LocalDateTime.parse(httpDate, format).atZone(GMT).toInstant();
} catch (DateTimeParseException skip) {
}
}
throw new IllegalArgumentException("Invalid date format: " + httpDate);
}Example 39
| Project: prime-mvc-master File: LocalDateConverter.java View source code |
protected String objectToString(Object value, Type convertFrom, Map<String, String> attributes, String expression) throws ConversionException, ConverterStateException {
String format = attributes.get("dateTimeFormat");
if (format == null) {
throw new ConverterStateException("You must provide the dateTimeFormat dynamic attribute for " + "the form fields [" + expression + "] that maps to LocalDate properties in the action. " + "If you are using a text field it will look like this: [@jc.text _dateTimeFormat=\"MM/dd/yyyy\"]");
}
return ((LocalDate) value).format(DateTimeFormatter.ofPattern(format));
}Example 40
| Project: Raildelays-master File: ExcelRowToWriteResourceLocator.java View source code |
/**
* {@inheritDoc}
* <p>
* We only modify the {@link ResourceContext} when the list of item is not empty and that the
* {@link ResourceContext} has not been initialized yet.
* </p>
*/
@Override
public void onWrite(ExcelRow item, ResourceContext context) throws Exception {
super.onWrite(item, context);
if (!context.containsResource() && isValid(item)) {
String suffix = item.getDate().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
File file = ExcelFileUtils.getFile(new File(directoryPath), fileName, suffix, fileExtension);
context.changeResource(new FileSystemResource(file));
}
}Example 41
| Project: Rob-Maven-and-Gradle-Plugins-master File: RobLogGithubManager.java View source code |
@Override
protected List<? extends Commit> fetchFromApi(int page) {
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Github.URL).build();
Github github = restAdapter.create(Github.class);
List<GithubCommit> commits;
String auth = "";
if (token != null && !token.isEmpty()) {
auth = "Bearer " + token;
}
if (page == 0) {
commits = github.listCommits(owner, repository, this.startDate.format(DateTimeFormatter.ISO_LOCAL_DATE), this.endDate.format(DateTimeFormatter.ISO_LOCAL_DATE), auth);
} else {
commits = github.listCommits(owner, repository, page, this.startDate.format(DateTimeFormatter.ISO_LOCAL_DATE), this.endDate.format(DateTimeFormatter.ISO_LOCAL_DATE), auth);
}
return commits;
}Example 42
| Project: sportstracker-master File: SpeedToStringConverter.java View source code |
@Override
public Number fromString(final String strValue) {
try {
final String strValueTrimmed = strValue.trim();
switch(formatUtils.getSpeedView()) {
case DistancePerHour:
return NumberFormat.getInstance().parse(strValueTrimmed).floatValue();
case MinutesPerDistance:
if (ZERO_SPEED_TIME.equals(strValueTrimmed)) {
return 0f;
}
final LocalTime time = LocalTime.parse("00:" + strValueTrimmed, DateTimeFormatter.ISO_LOCAL_TIME);
return 3600 / (float) (time.getMinute() * 60 + time.getSecond());
default:
throw new IllegalArgumentException("Invalid SpeedView " + formatUtils.getSpeedView() + "!");
}
} catch (Exception e) {
return -1;
}
}Example 43
| Project: stocks-master File: DateEditingSupport.java View source code |
@Override
public final void setValue(Object element, Object value) throws Exception {
Object subject = adapt(element);
LocalDate newValue = null;
for (DateTimeFormatter formatter : formatters) {
try {
newValue = LocalDate.parse(String.valueOf(value), formatter);
break;
} catch (DateTimeParseException ignore) {
}
}
if (newValue == null)
throw new IllegalArgumentException(MessageFormat.format(Messages.MsgErrorNotAValidDate, value));
LocalDate oldValue = (LocalDate) descriptor().getReadMethod().invoke(subject);
if (!newValue.equals(oldValue)) {
descriptor().getWriteMethod().invoke(subject, newValue);
notify(element, newValue, oldValue);
}
}Example 44
| Project: vert.x-master File: VertxLoggerFormatter.java View source code |
@Override
public String format(final LogRecord record) {
OffsetDateTime date = fromMillis(record.getMillis());
StringBuilder sb = new StringBuilder();
// Minimize memory allocations here.
sb.append("[").append(Thread.currentThread().getName()).append("] ");
sb.append(date.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)).append(" ");
sb.append(record.getLevel()).append(" [");
sb.append(record.getLoggerName()).append("]").append(" ");
sb.append(record.getMessage());
sb.append(Utils.LINE_SEPARATOR);
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
return sb.toString();
}Example 45
| Project: Vortex-master File: UserinfoCmd.java View source code |
@Override
protected void execute(CommandEvent event) {
Member member;
if (event.getMessage().getMentionedUsers().isEmpty()) {
try {
member = event.getGuild().getMemberById(event.getArgs());
} catch (Exception e) {
member = null;
}
} else
member = event.getGuild().getMember(event.getMessage().getMentionedUsers().get(0));
if (member == null) {
event.reply(event.getClient().getError() + " Could not find user from `" + event.getArgs() + " `!");
return;
}
String title = (member.getUser().isBot() ? "" : "") + " Information about **" + member.getUser().getName() + "**#" + member.getUser().getDiscriminator();
EmbedBuilder builder = new EmbedBuilder();
builder.setColor(member.getColor());
String roles = "";
roles = member.getRoles().stream().map(( rol) -> rol.getName()).filter(( r) -> (!r.equalsIgnoreCase("@everyone"))).map(( r) -> "`, `" + r).reduce(roles, String::concat);
if (roles.isEmpty())
roles = "None";
else
roles = roles.substring(3) + "`";
builder.setDescription("Discord ID: **" + member.getUser().getId() + "**\n" + (member.getNickname() == null ? "" : "Nickname: **" + member.getNickname() + "**\n") + "Roles: " + roles + "\n" + "Status: **" + member.getOnlineStatus().name() + "**" + (member.getGame() == null ? "" : " (" + (member.getGame().getType() == Game.GameType.TWITCH ? "Streaming [*" + member.getGame().getName() + "*](" + member.getGame().getUrl() + ")" : "Playing *" + member.getGame().getName() + "*") + ")") + "\n" + "Account Creation: **" + member.getUser().getCreationTime().format(DateTimeFormatter.RFC_1123_DATE_TIME) + "**\n" + "Guild Join Date: **" + member.getJoinDate().format(DateTimeFormatter.RFC_1123_DATE_TIME) + "**\n");
builder.setThumbnail(member.getUser().getEffectiveAvatarUrl());
event.getChannel().sendMessage(new MessageBuilder().append(title).setEmbed(builder.build()).build()).queue();
}Example 46
| Project: esper-master File: TestDTInvalid.java View source code |
public void testInvalid() {
String epl;
// invalid incompatible params
epl = "select contained.set('hour', 1) from SupportBean_ST0_Container";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'contained.set(\"hour\",1)': Date-time enumeration method 'set' requires either a Calendar, Date, long, LocalDateTime or ZonedDateTime value as input or events of an event type that declares a timestamp property but received collection of events of type '" + SupportBean_ST0.class.getName() + "'");
// invalid incompatible params
epl = "select window(*).set('hour', 1) from SupportBean#keepall";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'window(*).set(\"hour\",1)': Date-time enumeration method 'set' requires either a Calendar, Date, long, LocalDateTime or ZonedDateTime value as input or events of an event type that declares a timestamp property but received collection of events of type 'SupportBean'");
// invalid incompatible params
epl = "select utildate.set('invalid') from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.set(\"invalid\")': Parameters mismatch for date-time method 'set', the method requires an expression providing a string-type calendar field name and an expression providing an integer-type value");
// invalid lambda parameter
epl = "select utildate.set(x => true) from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.set()': Parameters mismatch for date-time method 'set', the method requires an expression providing a string-type calendar field name and an expression providing an integer-type value");
// invalid no parameter
epl = "select utildate.set() from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.set()': Parameters mismatch for date-time method 'set', the method requires an expression providing a string-type calendar field name and an expression providing an integer-type value");
// invalid wrong parameter
epl = "select utildate.set(1) from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.set(1)': Parameters mismatch for date-time method 'set', the method requires an expression providing a string-type calendar field name and an expression providing an integer-type value");
// invalid wrong parameter
epl = "select utildate.between('a', 'b') from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.between(\"a\",\"b\")': Error validating date-time method 'between', expected a long-typed, Date-typed or Calendar-typed result for expression parameter 0 but received java.lang.String");
// invalid wrong parameter
epl = "select utildate.between(utildate, utildate, 1, true) from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.between(utildate,utildate,...(42 chars)': Error validating date-time method 'between', expected a boolean-type result for expression parameter 2 but received java.lang.Integer");
// mispatch parameter to input
epl = "select utildate.format(java.time.format.DateTimeFormatter.ISO_ORDINAL_DATE) from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.format(ParseCaseSensitive(...(114 chars)': Date-time enumeration method 'format' invalid format, expected string-format or DateFormat but received java.time.format.DateTimeFormatter");
epl = "select zoneddate.format(SimpleDateFormat.getInstance()) from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'zoneddate.format(SimpleDateFormat.g...(48 chars)': Date-time enumeration method 'format' invalid format, expected string-format or DateTimeFormatter but received java.text.SimpleDateFormat");
// invalid date format null
epl = "select utildate.format(null) from SupportDateTime";
tryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'utildate.format(null)': Error validating date-time method 'format', expected any of [String, DateFormat, DateTimeFormatter]-type result for expression parameter 0 but received null");
}Example 47
| Project: jidefx-oss-master File: LocalDateConverterTest.java View source code |
@Test
public void testToString() throws Exception {
Assert.assertEquals("Jan 1, 2000", _converter.toString(LocalDate.of(2000, 1, 1)));
_converter.setDefaultDateTimeFormatter(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL));
Assert.assertEquals("Saturday, January 1, 2000", _converter.toString(LocalDate.of(2000, 1, 1)));
_converter.setDefaultDateTimeFormatter(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT));
Assert.assertEquals("1/1/00", _converter.toString(LocalDate.of(2000, 1, 1)));
_converter.setDefaultDateTimeFormatter(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG));
Assert.assertEquals("January 1, 2000", _converter.toString(LocalDate.of(2000, 1, 1)));
_converter.setDefaultDateTimeFormatter(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));
Assert.assertEquals("Jan 1, 2000", _converter.toString(LocalDate.of(2000, 1, 1)));
}Example 48
| Project: ABMS-master File: ExcelUploader.java View source code |
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(req)) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Not a multipart request");
return;
}
// from Commons
ServletFileUpload upload = new ServletFileUpload();
YearMonth currentMonth = YearMonth.now();
YearMonth previousMonth = currentMonth.minusMonths(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM_yyyy");
String fileMonthAndYear = previousMonth.format(dtf);
try {
FileItemIterator iter = upload.getItemIterator(req);
PropertiesReader reader = new PropertiesReader();
if (iter.hasNext()) {
FileItemStream fileItem = iter.next();
InputStream in = fileItem.openStream();
// The destination of your uploaded files.
File targetFile = new File(UPLOAD_DIRECTORY + "/" + "Upkeep_" + fileMonthAndYear + ".xlsx");
FileUtils.copyInputStreamToFile(in, targetFile);
// Process file
ExcelToPersonalView.processFile(targetFile);
Cloudinary cloudinary = new Cloudinary(ObjectUtils.asMap("cloud_name", reader.readProperty("cloudinary.properties", "cloud_name"), "api_key", reader.readProperty("cloudinary.properties", "api_key"), "api_secret", reader.readProperty("cloudinary.properties", "api_secret")));
cloudinary.uploader().upload(targetFile, ObjectUtils.asMap("use_filename", true, "unique_filename", false, "resource_type", "auto"));
// sendMails();
}
} catch (Exception caught) {
throw new RuntimeException(caught);
}
}Example 49
| Project: apollo-master File: GlobalDefaultExceptionHandler.java View source code |
private ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request, HttpStatus status, Throwable ex) {
String message = ex.getMessage();
logger.error(message, ex);
Tracer.logError(ex);
Map<String, Object> errorAttributes = new HashMap<>();
boolean errorHandled = false;
if (ex instanceof HttpStatusCodeException) {
try {
//try to extract the original error info if it is thrown from apollo programs, e.g. admin service
errorAttributes = gson.fromJson(((HttpStatusCodeException) ex).getResponseBodyAsString(), mapType);
status = ((HttpStatusCodeException) ex).getStatusCode();
errorHandled = true;
} catch (Throwable th) {
}
}
if (!errorHandled) {
errorAttributes.put("status", status.value());
errorAttributes.put("message", message);
errorAttributes.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
errorAttributes.put("exception", ex.getClass().getName());
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(APPLICATION_JSON);
return new ResponseEntity<>(errorAttributes, headers, status);
}Example 50
| Project: Cachoeira-master File: TaskTableView.java View source code |
@Override
protected void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
this.setAlignment(Pos.CENTER);
if (empty) {
this.setText(null);
this.setGraphic(null);
} else {
String dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.getDefault()).format(date);
this.setText(dateFormatter);
}
}Example 51
| Project: camel-master File: LocalTimeFormatFactory.java View source code |
public LocalTime parse(String string) throws Exception {
LocalTime date;
DateTimeFormatter df = this.getDateFormat();
ObjectHelper.notNull(this.pattern, "pattern");
if (doesStringFitLengthOfPattern(string)) {
date = LocalTime.parse(string, df);
return date;
} else {
throw new FormatException("Date provided does not fit the pattern defined");
}
}Example 52
| Project: clc-java-sdk-master File: TimeToLiveTest.java View source code |
@Test
public void testConstructorStringPattern() {
String date = "2015/12/31T23:00+03:00";
String pattern = "yyyy/MM/dd'T'HH:mmXXX";
TimeToLive ttl = new TimeToLive(date, pattern);
Assert.assertEquals(ttl.format(), ZonedDateTime.parse(date, DateTimeFormatter.ofPattern(pattern)).format(DateTimeFormatter.ofPattern(TTL_PATTERN)));
}Example 53
| Project: common-resteasy-master File: Iso8601AndOthersLocalDateTimeFormat.java View source code |
/**
* Parse string to date.
*
* @param str string to parse
* @return date
*/
public LocalDateTime parse(String str) {
LocalDateTime date = null;
if (StringUtils.isNotBlank(str)) {
// try full ISO 8601 format first
try {
Date timestamp = ISO8601Utils.parse(str, new ParsePosition(0));
Instant instant = Instant.ofEpochMilli(timestamp.getTime());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
} catch (IllegalArgumentExceptionParseException | ex) {
date = null;
}
// then try ISO 8601 format without timezone
try {
return LocalDateTime.from(iso8601NozoneFormat.parse(str));
} catch (IllegalArgumentExceptionDateTimeParseException | ex) {
date = null;
}
// then try a list of formats
for (DateTimeFormatter formatter : FORMATS) {
try {
TemporalAccessor ta = formatter.parse(str);
try {
return LocalDateTime.from(ta);
} catch (DateTimeException dte) {
return LocalDate.from(ta).atStartOfDay();
}
} catch (IllegalArgumentExceptionDateTimeParseException | e) {
date = null;
}
}
throw new IllegalArgumentException("Could not parse date " + str + " using ISO 8601 or any of the formats " + Arrays.asList(FORMATS) + ".");
}
// empty string
return date;
}Example 54
| Project: elexis-3-base-master File: Medication.java View source code |
public static Medication fromPrescriptions(@NonNull Mandant author, @NonNull ch.elexis.data.Patient patient, @NonNull List<Prescription> prescriptions) {
Medication ret = new Medication();
ret.date = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm").format(LocalDateTime.now());
ret.patientInfo = ContactInfo.fromPatient(patient);
ret.mandantInfo = ContactInfo.fromKontakt(author);
for (Prescription prescription : prescriptions) {
EntryType type = prescription.getEntryType();
if (type == EntryType.FIXED_MEDICATION) {
if (ret.fixMedication == null) {
ret.fixMedication = new ArrayList<>();
}
ret.fixMedication.add(Medicament.fromPrescription(prescription));
} else if (type == EntryType.RESERVE_MEDICATION) {
if (ret.reserveMedication == null) {
ret.reserveMedication = new ArrayList<>();
}
ret.reserveMedication.add(Medicament.fromPrescription(prescription));
}
}
return ret;
}Example 55
| Project: hibernate-orm-master File: InstantLiteralTest.java View source code |
@Test
public void test() {
final DateEvent _dateEvent = doInJPA(this::entityManagerFactory, entityManager -> {
DateEvent dateEvent = new DateEvent();
dateEvent.setCreatedOn(Instant.from(DateTimeFormatter.ISO_INSTANT.parse("2016-10-13T06:40:18.745Z")));
entityManager.persist(dateEvent);
return dateEvent;
});
doInJPA(this::entityManagerFactory, entityManager -> {
DateEvent dateEvent = entityManager.unwrap(Session.class).createQuery("select de " + "from DateEvent de " + "where de.createdOn = '2016-10-13T06:40:18.745Z' ", DateEvent.class).getSingleResult();
assertNotNull(dateEvent);
assertEquals(_dateEvent.getId(), dateEvent.getId());
});
doInJPA(this::entityManagerFactory, entityManager -> {
DateEvent dateEvent = entityManager.unwrap(Session.class).createQuery("select de " + "from DateEvent de " + "where de.createdOn = :createdOn ", DateEvent.class).setParameter("createdOn", Instant.from(DateTimeFormatter.ISO_INSTANT.parse("2016-10-13T06:40:18.745Z"))).getSingleResult();
assertNotNull(dateEvent);
assertEquals(_dateEvent.getId(), dateEvent.getId());
});
}Example 56
| Project: hibernate-search-master File: TimeHelper.java View source code |
/**
* Workaround for https://bugs.openjdk.java.net/browse/JDK-8066982,
* which at the moment has only been solved for JDK9.
*
* <p>Tested against TCKDTFParsedInstant in
* http://hg.openjdk.java.net/jdk9/dev/jdk/rev/f371bdfb7875
* with both JDK8b101 and JDK9 (early access - build 137).
*
* @param value The value to be parsed
* @param formatter The formatter to use when parsing
* @return The parsed {@link ZonedDateTime}
*/
public static ZonedDateTime parseZoneDateTime(String value, DateTimeFormatter formatter) {
TemporalAccessor temporal = formatter.parse(value);
if (!temporal.isSupported(ChronoField.OFFSET_SECONDS)) {
// No need for a workaround
return ZonedDateTime.from(temporal);
}
/*
* Rationale
*
* The bug lies in the way epoch seconds are retrieved: the date is interpreted as being
* expressed in the default offset for the timezone, instead of using the given offset.
* ZonedDateTime.from uses these epoch seconds in priority when retrieving the local date/time,
* and falls back to using the epoch day and nano of day.
* We work around the bug by bypassing ZonedDateTime.from and not using the epoch seconds,
* but instead directly retrieving the LocalDateTime using LocalDateTime.from. This method
* relies on ChronoField.EPOCH_DAY and ChronoField.NANO_OF_DAY, which (strangely) seem
* unaffected by the bug.
*/
ZoneId zone = ZoneId.from(temporal);
ZoneOffset offset = ZoneOffset.from(temporal);
LocalDateTime ldt = LocalDateTime.from(temporal);
return ZonedDateTime.ofInstant(ldt, offset, zone);
}Example 57
| Project: idnadrev-master File: WeeklyDoneAppointmentView.java View source code |
private void applyContent(WeekViewAppointment<Task> appointment) {
name.setText(appointment.getTitle());
startTime.setText(appointment.getStart().format(DateTimeFormatter.ISO_LOCAL_TIME));
duration.setText(appointment.getDuration().toMinutes() + "min");
endTime.setText(appointment.getEnd().format(DateTimeFormatter.ISO_LOCAL_TIME));
viewer.show(new AsciiDocContent(appointment.getTitle(), appointment.getUserData().getDescription()));
Button btn = (Button) appointment.getControl();
Node graphic = btn.getGraphic();
if (graphic instanceof ImageView) {
Image image = ((ImageView) graphic).getImage();
doneView.setImage(image);
}
}Example 58
| Project: jabref-master File: Date.java View source code |
/**
* Try to parse the following formats
* - "M/y" (covers 9/15, 9/2015, and 09/2015)
* - "MMMM (dd), yyyy" (covers September 1, 2015 and September, 2015)
* - "yyyy-MM-dd" (covers 2009-1-15)
* - "dd-MM-yyyy" (covers 15-1-2009)
* - "d.M.uuuu" (covers 15.1.2015)
* - "uuuu.M.d" (covers 2015.1.15)
* The code is essentially taken from http://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat.
*/
public static Optional<Date> parse(String dateString) {
List<String> formatStrings = Arrays.asList("uuuu-M-d", "uuuu-M", "d-M-uuuu", "M/uu", "M/uuuu", "MMMM d, uuuu", "MMMM, uuuu", "d.M.uuuu", "uuuu.M.d", "uuuu");
for (String formatString : formatStrings) {
try {
TemporalAccessor parsedDate = DateTimeFormatter.ofPattern(formatString).parse(dateString);
return Optional.of(new Date(parsedDate));
} catch (DateTimeParseException ignored) {
}
}
return Optional.empty();
}Example 59
| Project: josm-master File: TimeValidator.java View source code |
/**
* Returns the standard tooltip text.
* @return the standard tooltip text
*/
public String getStandardTooltipText() {
final ZonedDateTime now = ZonedDateTime.now();
return tr("Please enter a valid time in the usual format for your locale.<br>" + "Example: {0}<br>" + "Example: {1}<br>" + "Example: {2}<br>" + "Example: {3}<br>", DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(now), DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).format(now), DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG).format(now), DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).format(now));
}Example 60
| Project: junit5-master File: JavaTimeArgumentConverter.java View source code |
@Override
public Object convert(Object input, Class<?> targetClass) throws ArgumentConversionException {
if (!TEMPORAL_QUERIES.containsKey(targetClass)) {
throw new ArgumentConversionException("Cannot convert to " + targetClass.getName() + ": " + input);
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
TemporalQuery<?> temporalQuery = TEMPORAL_QUERIES.get(targetClass);
return formatter.parse(input.toString(), temporalQuery);
}Example 61
| Project: Mujina-master File: AbstractIntegrationTest.java View source code |
private String getIdPSAMLResponse(String saml) throws IOException {
Matcher matcher = Pattern.compile("ID=\"(.*?)\"").matcher(saml);
assertTrue(matcher.find());
//We need the ID of the original request to mimic the real IdP authnResponse
String inResponseTo = matcher.group(1);
ZonedDateTime date = ZonedDateTime.now();
String now = date.format(DateTimeFormatter.ISO_INSTANT);
String samlResponse = IOUtils.toString(new ClassPathResource("saml_response.xml").getInputStream(), Charset.defaultCharset());
samlResponse = samlResponse.replaceAll("@@IssueInstant@@", now).replaceAll("@@InResponseTo@@", inResponseTo);
return samlResponse;
}Example 62
| Project: nifi-master File: TimezoneAdapter.java View source code |
@Override
public Date unmarshal(String date) throws Exception {
final LocalDateTime now = LocalDateTime.now();
final DateTimeFormatter parser = new DateTimeFormatterBuilder().appendPattern(DEFAULT_DATE_TIME_FORMAT).parseDefaulting(ChronoField.YEAR, now.getYear()).parseDefaulting(ChronoField.MONTH_OF_YEAR, now.getMonthValue()).parseDefaulting(ChronoField.DAY_OF_MONTH, now.getDayOfMonth()).parseDefaulting(ChronoField.HOUR_OF_DAY, now.getHour()).parseDefaulting(ChronoField.MINUTE_OF_HOUR, now.getMinute()).parseDefaulting(ChronoField.SECOND_OF_MINUTE, now.getSecond()).parseDefaulting(ChronoField.MILLI_OF_SECOND, 0).toFormatter(Locale.US);
final LocalDateTime parsedDateTime = LocalDateTime.parse(date, parser);
return Date.from(parsedDateTime.toInstant(ZONE_ID.getRules().getOffset(now)));
}Example 63
| Project: OpenConext-teams-master File: LdapUserDetailsManager.java View source code |
@Override
public Optional<teams.migration.Person> findPersonById(String urn) {
List<teams.migration.Person> persons = persons(urn, attributes -> {
String mail = this.safeGetAttribute(attributes, "mail");
String cn = this.safeGetAttribute(attributes, "cn");
String isGuest = this.safeGetAttribute(attributes, "collabpersonisguest");
String collabpersonregistered = this.safeGetAttribute(attributes, "collabpersonregistered");
Instant created = (collabpersonregistered != null ? Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rfc822ToRFC1123(collabpersonregistered))) : Instant.now());
return new teams.migration.Person(urn, cn, mail, "TRUE".equals(isGuest), created);
});
return persons.stream().findFirst();
}Example 64
| Project: optaplanner-master File: NurseRosteringExporter.java View source code |
@Override
public void writeSolution() throws IOException {
Element solutionElement = new Element("Solution");
document.setRootElement(solutionElement);
Element schedulingPeriodIDElement = new Element("SchedulingPeriodID");
schedulingPeriodIDElement.setText(nurseRoster.getCode());
solutionElement.addContent(schedulingPeriodIDElement);
Element competitorElement = new Element("Competitor");
competitorElement.setText("Geoffrey De Smet with OptaPlanner");
solutionElement.addContent(competitorElement);
Element softConstraintsPenaltyElement = new Element("SoftConstraintsPenalty");
softConstraintsPenaltyElement.setText(Integer.toString(nurseRoster.getScore().getSoftScore()));
solutionElement.addContent(softConstraintsPenaltyElement);
for (ShiftAssignment shiftAssignment : nurseRoster.getShiftAssignmentList()) {
Shift shift = shiftAssignment.getShift();
if (shift != null) {
Element assignmentElement = new Element("Assignment");
solutionElement.addContent(assignmentElement);
Element dateElement = new Element("Date");
dateElement.setText(shift.getShiftDate().getDate().format(DateTimeFormatter.ISO_DATE));
assignmentElement.addContent(dateElement);
Element employeeElement = new Element("Employee");
employeeElement.setText(shiftAssignment.getEmployee().getCode());
assignmentElement.addContent(employeeElement);
Element shiftTypeElement = new Element("ShiftType");
shiftTypeElement.setText(shift.getShiftType().getCode());
assignmentElement.addContent(shiftTypeElement);
}
}
}Example 65
| Project: PalletTown-master File: RandomDetails.java View source code |
static String randomBirthday() {
long minDay = LocalDate.of(1950, 1, 1).toEpochDay();
long maxDay = LocalDate.of(2002, 12, 31).toEpochDay();
long randomDay = ThreadLocalRandom.current().nextLong(minDay, maxDay);
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);
DateTimeFormatter yearlyFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return randomDate.format(yearlyFormat);
}Example 66
| Project: jmeter-master File: TimeShift.java View source code |
/** {@inheritDoc} */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
String dateString;
LocalDateTime localDateTimeToShift = LocalDateTime.now(systemDefaultZoneID);
DateTimeFormatter formatter = null;
if (!StringUtils.isEmpty(format)) {
try {
formatter = dateTimeFormatterCache.get(format, key -> createFormatter((String) key));
} catch (IllegalArgumentException ex) {
log.error("Format date pattern '{}' is invalid (see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)", format, ex);
return "";
}
}
if (!dateToShift.isEmpty()) {
try {
if (formatter != null) {
localDateTimeToShift = LocalDateTime.parse(dateToShift, formatter);
} else {
localDateTimeToShift = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateToShift)), ZoneId.systemDefault());
}
} catch (DateTimeParseExceptionNumberFormatException | ex) {
log.error("Failed to parse the date '{}' to shift", dateToShift, ex);
}
}
// Check amount value to shift
if (!StringUtils.isEmpty(amountToShift)) {
try {
Duration duration = Duration.parse(amountToShift);
localDateTimeToShift = localDateTimeToShift.plus(duration);
} catch (DateTimeParseException ex) {
log.error("Failed to parse the amount duration '{}' to shift (see https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-) ", amountToShift, ex);
}
}
if (formatter != null) {
dateString = localDateTimeToShift.format(formatter);
} else {
ZoneOffset offset = ZoneOffset.systemDefault().getRules().getOffset(localDateTimeToShift);
dateString = String.valueOf(localDateTimeToShift.toInstant(offset).toEpochMilli());
}
if (!StringUtils.isEmpty(variableName)) {
JMeterVariables vars = getVariables();
if (vars != null) {
// vars will be null on TestPlan
vars.put(variableName, dateString);
}
}
return dateString;
}Example 67
| Project: cas-master File: MockTicketGrantingTicketCreatedEventProducer.java View source code |
private static void createEvent(final int i, final CasEventRepository casEventRepository) {
final CasEvent dto = new CasEvent();
dto.setType(CasTicketGrantingTicketCreatedEvent.class.getName());
dto.putTimestamp(new Date().getTime());
final int days = ThreadLocalRandom.current().nextInt(0, 30);
dto.putCreationTime(ZonedDateTime.now().minusDays(days).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
dto.putId(TicketIdSanitizationUtils.sanitize("TGT-" + i + "-" + RandomStringUtils.randomAlphanumeric(16)));
dto.setPrincipalId("casuser");
dto.putClientIpAddress(getMockClientIpAddress());
dto.putServerIpAddress("127.0.0.1");
dto.putAgent(getMockUserAgent());
dto.putGeoLocation(getMockGeoLocation());
casEventRepository.save(dto);
}Example 68
| Project: Consent2Share-master File: ManagerReportController.java View source code |
/**
* Handle report request.
*
* @param format
* the format
* @return the model and view
*/
@RequestMapping(method = GET, value = ManagerReportConfig.REPORT_NAME)
public ModelAndView handleReportRequest(@RequestParam Optional<ReportFormat> format, @RequestParam @DateTimeFormat(pattern = "MM/dd/yyyy") LocalDate startDate, @RequestParam @DateTimeFormat(pattern = "MM/dd/yyyy") LocalDate endDate, @RequestParam Optional<Boolean> noAccountInformation, @RequestParam Optional<Boolean> noCatagoryDescription) {
final ReportFormat reportFormat = format.orElse(HTML);
Boolean noInformation = noAccountInformation.orElse(false);
Boolean noDescription = noCatagoryDescription.orElse(false);
RequestScopedParameters requestScopedParameters = requestScopedParametersProvider.getRequestScopedParameters();
LocalDateTime startDateTime = reportUtils.getStartDateTime(startDate);
LocalDateTime endDateTime = reportUtils.getEndDateTime(endDate);
long startSqlTimeStamp = reportUtils.convertLocalDateTimeToEpoch(startDateTime);
long endSqlTimeStamp = reportUtils.convertLocalDateTimeToEpoch(endDateTime);
requestScopedParameters.add("startDateTime", startDateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"))).add("endDateTime", endDateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"))).add("noInformation", noInformation).add("noDescription", noDescription);
Object[] args = new Object[] { startSqlTimeStamp, endSqlTimeStamp };
Collection<Object> reportData = this.reportDataProvider.getReportData(args);
if (reportData.size() == 0) {
return new ModelAndView("views/Administrator/noReportDataFound");
} else {
return reportModelAndView(reportFormat, () -> reportData);
}
}Example 69
| Project: controle-financeiro-master File: UserMessage.java View source code |
/**
* Calcula o tempo que se passou desde o envio da mensagem
*/
public void calculateElapsedTime() {
final LocalDateTime sentOn = LocalDateTime.ofInstant(this.message.getInclusion().toInstant(), ZoneId.systemDefault());
if (sentOn.toLocalDate().isBefore(LocalDate.now())) {
this.elapsedTime = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm").format(sentOn);
} else {
long difference = ChronoUnit.MINUTES.between(sentOn.toLocalTime(), LocalTime.now());
if (difference > 60) {
difference = ChronoUnit.HOURS.between(sentOn.toLocalTime(), LocalTime.now());
this.elapsedTime = String.valueOf(difference);
this.timeUnit = "message-box.hours";
} else {
this.elapsedTime = String.valueOf(difference);
this.timeUnit = "message-box.minutes";
}
}
}Example 70
| Project: datacollector-master File: TestSyslogDecoder.java View source code |
@Test
public void testRfc5424DateParsing() throws Exception {
final String[] examples = { "1985-04-12T23:20:50.52Z", "1985-04-12T19:20:50.52-04:00", "2003-10-11T22:14:15.003Z", "2003-08-24T05:14:15.000003-07:00", "2012-04-13T11:11:11-08:00", "2012-04-13T08:08:08.0001+00:00", "2012-04-13T08:08:08.251+00:00" };
SyslogDecoder decoder = new SyslogDecoder(StandardCharsets.UTF_8, getSystemClock());
DateTimeFormatter parser = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
for (String example : examples) {
assertEquals("Problem parsing date string: " + example, OffsetDateTime.parse(example, parser).toInstant().toEpochMilli(), decoder.parseRfc5424Date(example));
}
}Example 71
| Project: diirt-master File: TimeParser.java View source code |
/**
* A Helper function to help you convert various string represented time
* definition to an absolute Instant.
*
* @param time
* a string represent the time
* @return the parsed Instant or null
*/
public static Instant getInstant(String time) {
if (time.equalsIgnoreCase("now")) {
return Instant.now();
} else {
int quantity = 0;
String unit = "";
Pattern lastNUnitsPattern = Pattern.compile("last\\s*(\\d*)\\s*(min|mins|hour|hours|day|days|week|weeks).*", Pattern.CASE_INSENSITIVE);
Matcher lastNUnitsMatcher = lastNUnitsPattern.matcher(time);
while (lastNUnitsMatcher.find()) {
quantity = "".equals(lastNUnitsMatcher.group(1)) ? 1 : Integer.valueOf(lastNUnitsMatcher.group(1));
unit = lastNUnitsMatcher.group(2).toLowerCase();
switch(unit) {
case "min":
case "mins":
return Instant.now().minus(Duration.ofMinutes(quantity));
case "hour":
case "hours":
return Instant.now().minus(Duration.ofHours(quantity));
case "day":
case "days":
return Instant.now().minus(Duration.ofHours(quantity * 24));
case "week":
case "weeks":
return Instant.now().minus(Duration.ofHours(quantity * 24 * 7));
default:
break;
}
}
Pattern nUnitsAgoPattern = Pattern.compile("(\\d*)\\s*(min|mins|hour|hours|day|days|week|weeks)\\s*ago", Pattern.CASE_INSENSITIVE);
Matcher nUnitsAgoMatcher = nUnitsAgoPattern.matcher(time);
while (nUnitsAgoMatcher.find()) {
quantity = "".equals(nUnitsAgoMatcher.group(1)) ? 1 : Integer.valueOf(nUnitsAgoMatcher.group(1));
unit = nUnitsAgoMatcher.group(2).toLowerCase();
switch(unit) {
case "min":
case "mins":
return Instant.now().minus(Duration.ofMinutes(quantity));
case "hour":
case "hours":
return Instant.now().minus(Duration.ofHours(quantity));
case "day":
case "days":
return Instant.now().minus(Duration.ofHours(quantity * 24));
case "week":
case "weeks":
return Instant.now().minus(Duration.ofHours(quantity * 24 * 7));
default:
break;
}
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
return LocalDateTime.parse(time, formatter).atZone(TimeZone.getDefault().toZoneId()).toInstant();
}
}Example 72
| Project: drools-master File: FEELDateTimeDurationTest.java View source code |
@Parameterized.Parameters(name = "{index}: {0} ({1}) = {2}")
public static Collection<Object[]> data() {
final Object[][] cases = new Object[][] { // date/time/duration function invocations
{ "date(\"2016-07-29\")", DateTimeFormatter.ISO_DATE.parse("2016-07-29", LocalDate::from) }, // 105 BC
{ "date(\"-0105-07-29\")", DateTimeFormatter.ISO_DATE.parse("-0105-07-29", LocalDate::from) }, { "date(\"2016-15-29\")", null }, { "date(\"2016-12-48\")", null }, { "date( 10 )", null }, { "date( 2016, 8, 2 )", LocalDate.of(2016, 8, 2) }, { "date( -0105, 8, 2 )", LocalDate.of(-105, 8, 2) }, { "date( 2016, 15, 2 )", null }, { "date( 2016, 12, 48 )", null }, { "date( date and time(\"2016-07-29T05:48:23.765-05:00\") )", LocalDate.of(2016, 7, 29) }, { "date( date and time(\"2016-07-29T05:48:23Z\") )", LocalDate.of(2016, 7, 29) }, { "time(\"23:59:00\")", DateTimeFormatter.ISO_TIME.parse("23:59:00", LocalTime::from) }, { "time(\"05:48:23.765\")", DateTimeFormatter.ISO_TIME.parse("05:48:23.765", LocalTime::from) }, { "time(\"23:59:00z\")", DateTimeFormatter.ISO_TIME.parse("23:59:00z", OffsetTime::from) }, { "time(\"13:20:00-05:00\")", DateTimeFormatter.ISO_TIME.parse("13:20:00-05:00", OffsetTime::from) }, { "time( 14, 52, 25, null )", LocalTime.of(14, 52, 25) }, { "time( 14, 52, 25, duration(\"PT5H\"))", OffsetTime.of(14, 52, 25, 0, ZoneOffset.ofHours(5)) }, { "time( date and time(\"2016-07-29T05:48:23\") )", LocalTime.of(5, 48, 23, 0) }, { "time( date and time(\"2016-07-29T05:48:23Z\") )", OffsetTime.of(5, 48, 23, 0, ZoneOffset.UTC) }, { "time( date and time(\"2016-07-29T05:48:23.765-05:00\") )", OffsetTime.of(5, 48, 23, 765000000, ZoneOffset.ofHours(-5)) }, { "date and time(\"2016-07-29T05:48:23\")", LocalDateTime.of(2016, 7, 29, 5, 48, 23, 0) }, { "date and time(\"2016-07-29T05:48:23Z\")", ZonedDateTime.of(2016, 7, 29, 5, 48, 23, 0, ZoneId.of("Z").normalized()) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\")", DateTimeFormatter.ISO_DATE_TIME.parse("2016-07-29T05:48:23.765-05:00", ZonedDateTime::from) }, { "date and time(date(\"2016-07-29\"), time(\"05:48:23.765-05:00\") )", DateTimeFormatter.ISO_DATE_TIME.parse("2016-07-29T05:48:23.765-05:00", ZonedDateTime::from) }, { "duration( \"P2DT20H14M\" )", Duration.parse("P2DT20H14M") }, { "duration( \"P2Y2M\" )", Period.parse("P2Y2M") }, { "duration( \"P26M\" )", Period.parse("P26M") }, { "years and months duration( date(\"2011-12-22\"), date(\"2013-08-24\") )", Period.parse("P1Y8M") }, // comparison operators
{ "duration( \"P1Y6M\" ) = duration( \"P1Y6M\" )", Boolean.TRUE }, { "duration( \"P1Y6M\" ) = duration( \"P1Y8M\" )", Boolean.FALSE }, { "duration( \"P1Y\" ) = duration( \"P1Y\" )", Boolean.TRUE }, { "duration( \"P1Y\" ) = duration( \"P1M\" )", Boolean.FALSE }, { "duration( \"P1Y6M\" ) <= duration( \"P1Y8M\" )", Boolean.TRUE }, { "duration( \"P1Y6M\" ) < duration( \"P1Y8M\" )", Boolean.TRUE }, { "duration( \"P1Y6M\" ) > duration( \"P1Y8M\" )", Boolean.FALSE }, { "duration( \"P1Y6M\" ) >= duration( \"P1Y8M\" )", Boolean.FALSE }, { "duration( \"P1Y6M\" ) = null", Boolean.FALSE }, { "duration( \"P1Y6M\" ) != null", Boolean.TRUE }, { "duration( \"P1Y6M\" ) > null", null }, { "duration( \"P1Y6M\" ) < null", null }, { "date( 2016, 8, 2 ).year", BigDecimal.valueOf(2016) }, { "date( 2016, 8, 2 ).month", BigDecimal.valueOf(8) }, { "date( 2016, 8, 2 ).day", BigDecimal.valueOf(2) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\").year", BigDecimal.valueOf(2016) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\").month", BigDecimal.valueOf(7) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\").day", BigDecimal.valueOf(29) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\").hour", BigDecimal.valueOf(5) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\").minute", BigDecimal.valueOf(48) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\").second", BigDecimal.valueOf(23) }, { "date and time(\"2016-07-29T05:48:23.765-05:00\").time offset", Duration.parse("PT-5H") }, // { "date and time(\"2016-07-29T05:48:23.765@SomeTimeZoneFormat\").timezone", someTimezoneResult},
{ "time(\"13:20:00-05:00\").hour", BigDecimal.valueOf(13) }, { "time(\"13:20:00-05:00\").minute", BigDecimal.valueOf(20) }, { "time(\"13:20:00-05:00\").second", BigDecimal.valueOf(0) }, { "time(\"13:20:00-05:00\").time offset", Duration.parse("PT-5H") }, // { "time(\"13:20:00@SomeTimeZoneFormat\").timezone", someTimeZoneResult },
{ "duration( \"P2DT20H14M\" ).days", BigDecimal.valueOf(2) }, { "duration( \"P2DT20H14M\" ).hours", BigDecimal.valueOf(20) }, { "duration( \"P2DT20H14M\" ).minutes", BigDecimal.valueOf(14) }, { "duration( \"P2DT20H14M5S\" ).seconds", BigDecimal.valueOf(5) }, { "years and months duration( date(\"2011-12-22\"), date(\"2013-08-24\") ).years", BigDecimal.valueOf(1) }, { "years and months duration( date(\"2011-12-22\"), date(\"2013-08-24\") ).months", BigDecimal.valueOf(8) }, { "date and time(\"2017-05-14\")", LocalDateTime.of(2017, 5, 14, 0, 0, 0, 0) }, { "date(\"2017-05-12\")-date(\"2017-04-25\")", Duration.ofDays(17) } };
return Arrays.asList(cases);
}Example 73
| Project: elasticsearch-master File: DateFormatTests.java View source code |
public void testParseJoda() {
Function<String, DateTime> jodaFunction = DateFormat.Joda.getFunction("MMM dd HH:mm:ss Z", DateTimeZone.forOffsetHours(-8), Locale.ENGLISH);
assertThat(Instant.ofEpochMilli(jodaFunction.apply("Nov 24 01:29:01 -0800").getMillis()).atZone(ZoneId.of("GMT-8")).format(DateTimeFormatter.ofPattern("MM dd HH:mm:ss", Locale.ENGLISH)), equalTo("11 24 01:29:01"));
}Example 74
| Project: elasticsearch-readonlyrest-plugin-master File: ElasticsearchTweetsInitializer.java View source code |
private void createMessage(RestClient client, String endpoint, String id, String user, String message) {
try {
HttpPut httpPut = new HttpPut(client.from(endpoint + id));
httpPut.setEntity(new StringEntity("{\n" + "\"user\" : \"" + user + "\",\n" + "\"post_date\" : \"" + LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE) + "\",\n" + "\"message\" : \"" + message + "\"\n" + "}"));
consume(client.execute(httpPut).getEntity());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Creating message failed", e);
}
}Example 75
| Project: elexis-3-core-master File: ConditionTest.java View source code |
@Test
public void getProperties() {
IFindingsFactory factory = FindingsServiceComponent.getService().getFindingsFactory();
assertNotNull(factory);
ICondition condition = factory.createCondition();
assertNotNull(condition);
// set the properties
condition.setPatientId(AllTests.PATIENT_ID);
LocalDate dateRecorded = LocalDate.of(2016, Month.OCTOBER, 19);
condition.setDateRecorded(dateRecorded);
condition.setCategory(ConditionCategory.DIAGNOSIS);
condition.setStatus(ConditionStatus.ACTIVE);
condition.addNote("first note");
condition.addNote("second note\nthird note");
LocalDateTime startTime = LocalDateTime.of(2016, Month.OCTOBER, 1, 12, 0, 0);
condition.setStart(startTime.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));
ICoding code = new ICoding() {
@Override
public String getSystem() {
return "testSystem";
}
@Override
public String getDisplay() {
return "test display";
}
@Override
public String getCode() {
return "test";
}
};
condition.setCoding(Collections.singletonList(code));
condition.addStringExtension("test", "testValue");
FindingsServiceComponent.getService().saveFinding(condition);
List<IFinding> conditions = FindingsServiceComponent.getService().getPatientsFindings(AllTests.PATIENT_ID, ICondition.class);
assertNotNull(conditions);
assertFalse(conditions.isEmpty());
assertEquals(1, conditions.size());
// read condition and test the properties
ICondition readcondition = (ICondition) conditions.get(0);
assertEquals(AllTests.PATIENT_ID, readcondition.getPatientId());
assertTrue(readcondition.getDateRecorded().isPresent());
assertEquals(dateRecorded, readcondition.getDateRecorded().get());
List<String> notes = readcondition.getNotes();
assertNotNull(notes);
assertFalse(notes.isEmpty());
assertTrue(notes.get(0).equals("first note"));
assertTrue(notes.get(1).equals("second note\nthird note"));
assertTrue(readcondition.getStart().isPresent());
assertEquals(startTime.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), readcondition.getStart().get());
List<ICoding> coding = readcondition.getCoding();
assertNotNull(coding);
assertFalse(coding.isEmpty());
assertEquals(coding.get(0).getDisplay(), "test display");
Map<String, String> extensions = readcondition.getStringExtensions();
assertFalse(extensions.isEmpty());
assertTrue(extensions.containsKey("test"));
assertEquals("testValue", extensions.get("test"));
}Example 76
| Project: gshell-master File: HistoryAction.java View source code |
private void renderEntry(final IO io, final History.Entry entry) {
AttributedStringBuilder buff = new AttributedStringBuilder();
if (timestamps) {
LocalTime lt = LocalTime.from(entry.time().atZone(ZoneId.systemDefault())).truncatedTo(ChronoUnit.SECONDS);
DateTimeFormatter.ISO_LOCAL_TIME.formatTo(lt, buff);
buff.append(" ");
}
buff.style(buff.style().bold());
buff.append(String.format("%3d", entry.index() + 1));
buff.style(buff.style().boldOff());
buff.append(" ").append(entry.line());
io.println(buff.toAnsi(io.terminal));
}Example 77
| Project: hadatac-master File: FileFactory.java View source code |
public void openFile(String type, String mode) throws IOException {
if (type.equals("ccsv")) {
ccsvFileReader = new FileReader(ccsvFile);
ccsvBufferedReader = new BufferedReader(ccsvFileReader);
} else if (type.equals("csv")) {
csvFile = new File(arguments.getTempPath() + fileName + ".temp.csv");
if (mode.equals("w")) {
csvFileWriter = new FileWriter(csvFile);
csvBufferedWriter = new BufferedWriter(csvFileWriter);
} else if (mode.equals("r")) {
csvFileReader = new FileReader(csvFile);
csvBufferedReader = new BufferedReader(csvFileReader);
}
} else if (type.equals("xcsv")) {
xcsvFile = new File(arguments.getOutputPath() + fileName + ".xcsv");
xcsvFileWriter = new FileWriter(xcsvFile);
xcsvBufferedWriter = new BufferedWriter(xcsvFileWriter);
} else if (type.equals("ttl")) {
ttlFile = new File(arguments.getOutputPath() + fileName + ".ttl");
ttlFileWriter = new FileWriter(ttlFile);
ttlBufferedWriter = new BufferedWriter(ttlFileWriter);
} else if (type.equals("log")) {
logFile = new File(arguments.getLogPath() + "hadatac-loader-" + LocalDateTime.now().toLocalDate().format(DateTimeFormatter.ISO_DATE) + ".log");
logFileWriter = new FileWriter(logFile);
logBufferedWriter = new BufferedWriter(logFileWriter);
}
}Example 78
| Project: heroic-master File: DateTimeExpression.java View source code |
public static LocalDateTime parseLocalDateTime(final String input) {
final ImmutableList.Builder<Throwable> errors = ImmutableList.builder();
for (final DateTimeFormatter f : FORMATTERS) {
final TemporalAccessor accessor;
try {
accessor = f.parse(input);
} catch (final DateTimeException e) {
errors.add(e);
continue;
}
final int year = accessor.get(ChronoField.YEAR);
final int month = accessor.get(ChronoField.MONTH_OF_YEAR);
final int dayOfMonth = accessor.get(ChronoField.DAY_OF_MONTH);
final int hour = getOrDefault(accessor, ChronoField.HOUR_OF_DAY, 0);
final int minute = getOrDefault(accessor, ChronoField.MINUTE_OF_HOUR, 0);
final int second = getOrDefault(accessor, ChronoField.SECOND_OF_MINUTE, 0);
final int nanoOfSecond = getOrDefault(accessor, ChronoField.MILLI_OF_SECOND, 0) * 1000000;
return LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond);
}
final IllegalArgumentException e = new IllegalArgumentException("Invalid dateTime: " + input);
errors.build().forEach(e::addSuppressed);
throw e;
}Example 79
| Project: jsmart-web-master File: FormatTagHandler.java View source code |
String formatValue(final Object value) {
if (value != null) {
if (Type.NUMBER.equalsIgnoreCase(type)) {
return new DecimalFormat(regex).format(value);
} else if (Type.DATE.equalsIgnoreCase(type)) {
if (value instanceof Date) {
return new SimpleDateFormat(regex, getRequest().getLocale()).format(value);
} else if (value instanceof LocalDateTime) {
return ((LocalDateTime) value).format(DateTimeFormatter.ofPattern(regex).withLocale(getRequest().getLocale()));
} else if (value instanceof DateTime) {
return ((DateTime) value).toString(DateTimeFormat.forPattern(regex).withLocale(getRequest().getLocale()));
}
}
return value.toString();
}
return null;
}Example 80
| Project: junit-quickcheck-master File: YearMonthGenerator.java View source code |
/**
* <p>Tells this generator to produce values within a specified
* {@linkplain InRange#min() minimum} and/or {@linkplain InRange#max()
* maximum}, inclusive, with uniform distribution.</p>
*
* <p>If an endpoint of the range is not specified, the generator will use
* dates with values of either {@code YearMonth(Year#MIN_VALUE, 1)} or
* {@code YearMonth(Year#MAX_VALUE, 12)} as appropriate.</p>
*
* <p>{@link InRange#format()} describes
* {@linkplain DateTimeFormatter#ofPattern(String) how the generator is to
* interpret the range's endpoints}.</p>
*
* @param range annotation that gives the range's constraints
*/
public void configure(InRange range) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(range.format());
if (!defaultValueOf(InRange.class, "min").equals(range.min()))
min = YearMonth.parse(range.min(), formatter);
if (!defaultValueOf(InRange.class, "max").equals(range.max()))
max = YearMonth.parse(range.max(), formatter);
if (min.compareTo(max) > 0)
throw new IllegalArgumentException(String.format("bad range, %s > %s", range.min(), range.max()));
}Example 81
| Project: LiquidDonkey-master File: BackupFormatter.java View source code |
public static BackupFormatter create(String indent, DateTimeFormatter dateTimeFormatter) {
if (dateTimeFormatter.getLocale() == null) {
dateTimeFormatter = dateTimeFormatter.withLocale(Locale.getDefault());
}
if (dateTimeFormatter.getZone() == null) {
dateTimeFormatter = dateTimeFormatter.withZone(ZoneId.systemDefault());
}
return new BackupFormatter(indent, dateTimeFormatter);
}Example 82
| Project: minicubes-master File: CpuIdelController.java View source code |
@FXML
private void initialize() {
cpuIdelLineChart.getData().add(new Series<String, Integer>());
// Start to fetch data for line chart...
fetchCpuIdelData.scheduleAtFixedRate(new CpuIdelCollector(), 100, 500, TimeUnit.MILLISECONDS);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("mm:ss");
// Start to redraw line chart...
Runnable t = new Runnable() {
@Override
public void run() {
Integer cpuIdel = -1;
try {
cpuIdel = cpuIdelDataQueue.poll(500, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
if (cpuIdel >= 0) {
try {
ObservableList<XYChart.Data<String, Integer>> seriesData = cpuIdelLineChart.getData().get(0).getData();
seriesData.add(new XYChart.Data<String, Integer>(formatter.format(LocalDateTime.now()), cpuIdel));
cpuIdelLineChart.getData().get(0).setData(seriesData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
redrawCpuIdelChart.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
Platform.runLater(t);
}
}, 1, 1, TimeUnit.SECONDS);
System.out.println("Working...");
}Example 83
| Project: mssql-jdbc-master File: SQLServerBulkCopy42Helper.java View source code |
static Object getTemporalObjectFromCSVWithFormatter(String valueStrUntrimmed, int srcJdbcType, int srcColOrdinal, DateTimeFormatter dateTimeFormatter, SQLServerConnection connection, SQLServerBulkCopy sqlServerBC) throws SQLServerException {
DriverJDBCVersion.checkSupportsJDBC42();
try {
TemporalAccessor ta = dateTimeFormatter.parse(valueStrUntrimmed);
int taHour, taMin, taSec, taYear, taMonth, taDay, taNano, taOffsetSec;
taHour = taMin = taSec = taYear = taMonth = taDay = taNano = taOffsetSec = 0;
if (ta.isSupported(ChronoField.NANO_OF_SECOND))
taNano = ta.get(ChronoField.NANO_OF_SECOND);
if (ta.isSupported(ChronoField.OFFSET_SECONDS))
taOffsetSec = ta.get(ChronoField.OFFSET_SECONDS);
if (ta.isSupported(ChronoField.HOUR_OF_DAY))
taHour = ta.get(ChronoField.HOUR_OF_DAY);
if (ta.isSupported(ChronoField.MINUTE_OF_HOUR))
taMin = ta.get(ChronoField.MINUTE_OF_HOUR);
if (ta.isSupported(ChronoField.SECOND_OF_MINUTE))
taSec = ta.get(ChronoField.SECOND_OF_MINUTE);
if (ta.isSupported(ChronoField.DAY_OF_MONTH))
taDay = ta.get(ChronoField.DAY_OF_MONTH);
if (ta.isSupported(ChronoField.MONTH_OF_YEAR))
taMonth = ta.get(ChronoField.MONTH_OF_YEAR);
if (ta.isSupported(ChronoField.YEAR))
taYear = ta.get(ChronoField.YEAR);
Calendar cal = null;
cal = new GregorianCalendar(new SimpleTimeZone(taOffsetSec * 1000, ""));
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, taHour);
cal.set(Calendar.MINUTE, taMin);
cal.set(Calendar.SECOND, taSec);
cal.set(Calendar.DATE, taDay);
cal.set(Calendar.MONTH, taMonth - 1);
cal.set(Calendar.YEAR, taYear);
int fractionalSecondsLength = Integer.toString(taNano).length();
for (int i = 0; i < (9 - fractionalSecondsLength); i++) taNano *= 10;
Timestamp ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(taNano);
switch(srcJdbcType) {
case java.sql.Types.TIMESTAMP:
return ts;
case java.sql.Types.TIME:
// Time is returned as Timestamp to preserve nano seconds.
cal.set(connection.baseYear(), 00, 01);
ts = new java.sql.Timestamp(cal.getTimeInMillis());
ts.setNanos(taNano);
return new java.sql.Timestamp(ts.getTime());
case java.sql.Types.DATE:
return new java.sql.Date(ts.getTime());
case microsoft.sql.Types.DATETIMEOFFSET:
return DateTimeOffset.valueOf(ts, taOffsetSec / 60);
}
} catch (DateTimeExceptionArithmeticException | e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ParsingError"));
Object[] msgArgs = { JDBCType.of(srcJdbcType) };
throw new SQLServerException(sqlServerBC, form.format(msgArgs), null, 0, false);
}
// unreachable code. Need to do to compile from Eclipse.
return valueStrUntrimmed;
}Example 84
| Project: openjdk-master File: Bug8134250.java View source code |
public static void main(String[] args) {
LocalDate d = LocalDate.of(1980, Month.JANUARY, 1);
// en-GB inherits from en-001 where its short tz name for
// America/Los_Angeles is "non-inheritance marker". Thus the
// resulting formatted text should be a custom ID.
DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
dtfb.appendZoneText(TextStyle.SHORT);
DateTimeFormatter dtf = dtfb.toFormatter(Locale.UK).withZone(ZoneId.of("America/Los_Angeles"));
String result = dtf.format(d);
System.out.println(result);
if (!"GMT-08:00".equals(result)) {
throw new RuntimeException("short time zone name for America/Los_Angeles in en_GB is incorrect. Got: " + result + ", expected: GMT-08:00");
}
// Islamic Um-Alqura calendar is an alias to Islamic calendar.
// In Islamic calendar data, only month names are localized, also
// date/time format for FULL style should be inherited from "generic"
// calendar, where it includes ERA field.
Locale locale = Locale.forLanguageTag("en-US-u-ca-islamic-umalqura");
Chronology chrono = Chronology.ofLocale(locale);
dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(locale).withChronology(chrono);
result = dtf.format(d);
System.out.println(dtf.format(d));
if (!"Tuesday, Safar 12, 1400 AH".equals(result)) {
throw new RuntimeException("FULL date format of Islamic Um-Alqura calendar in en_US is incorrect. Got: " + result + ", expected: Tuesday, Safar 12, 1400 AH");
}
}Example 85
| Project: perfload-perfalyzer-master File: TestMetadata.java View source code |
public static TestMetadata create(final String rawResultsDir, final Properties properties) {
ZonedDateTime start = ZonedDateTime.parse(properties.getProperty("test.start"), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
ZonedDateTime end = ZonedDateTime.parse(properties.getProperty("test.finish"), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
String duration = DurationFormatUtils.formatDurationHMS(Duration.between(start, end).toMillis());
String operationsString = properties.getProperty("operations");
Set<String> operations = newTreeSet(on(',').trimResults().split(operationsString));
return new TestMetadata(start, end, duration, properties.getProperty("test.file"), rawResultsDir, properties.getProperty("perfload.implementation.version"), properties.getProperty("test.comment"), operations);
}Example 86
| Project: quickstart-master File: DateService.java View source code |
@GET
@Path("daysuntil/{targetdate}")
@Produces(MediaType.TEXT_PLAIN)
public long showDaysUntil(@PathParam("targetdate") String targetDate) {
DateLogger.LOGGER.logDaysUntilRequest(targetDate);
final long days;
try {
final LocalDate date = LocalDate.parse(targetDate, DateTimeFormatter.ISO_DATE);
days = ChronoUnit.DAYS.between(LocalDate.now(), date);
} catch (DateTimeParseException ex) {
DateTimeParseException nex = DateExceptionsBundle.EXCEPTIONS.targetDateStringDidntParse(targetDate, ex.getParsedString(), ex.getErrorIndex());
DateLogger.LOGGER.logStringCouldntParseAsDate(targetDate, nex);
throw new WebApplicationException(Response.status(400).entity(nex.getLocalizedMessage()).type(MediaType.TEXT_PLAIN).build());
}
return days;
}Example 87
| Project: risky-master File: AdHocMain.java View source code |
public static void main(String[] args) throws IOException {
long start = ZonedDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse("2014-05-13T00:00:00Z")).toEpochSecond() * 1000;
long finish = ZonedDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse("2014-05-27T00:00:00Z")).toEpochSecond() * 1000;
Pattern pattern = Pattern.compile(".*\\.track");
PrintStream out = new PrintStream("target/output.txt");
out.println("mmsi\ttime\tlat\tlong\tcourse\tspeedKnots");
List<File> files = Files.find(new File("/media/an/binary-fixes-5-minute/2014"), pattern);
Observable.from(files).flatMap(//
file -> extract(file, start, finish).subscribeOn(Schedulers.computation())).filter(// only valid mmsi
fix -> MmsiValidator2.INSTANCE.isValid(fix.mmsi())).map(//
f -> String.format("%s\t%s\t%s\t%s\t%s\t%s", f.mmsi(), formatDateTime(f.time()), f.lat(), f.lon(), get(f.courseOverGroundDegrees()), get(f.speedOverGroundKnots()))).doOnNext(//
out::println).lift(//
Logging.<String>logger().showCount().every(10000).log()).count().doOnTerminate(//
out::close).toBlocking().single();
}Example 88
| Project: SimpleWeb4j-master File: WebjarHandler.java View source code |
/**
* Handle a request.
*
* @param target The target of the request - either a URI or a name.
* @param baseRequest The original unwrapped request object.
* @param request The request either as the {@link Request}
* object or a wrapper of that request.
* @param response The response as the {@link org.eclipse.jetty.server.Response}
* object or a wrapper of that request.
* @throws IOException in case of IO error.
*/
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
if (baseRequest.isHandled() || !baseRequest.getPathInfo().startsWith("/webjars/")) {
return;
}
URL classpathUrl = ClassLoader.getSystemResource("META-INF/resources" + baseRequest.getPathInfo());
if (classpathUrl == null) {
return;
}
baseRequest.setHandled(true);
if (baseRequest.getHeader("if-modified-since") != null) {
// webjar are never modified (version is in path).
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// FIXME Use try with resources when jacoco can handle this correctly
InputStream in = getInputStream(classpathUrl);
try {
OutputStream out = response.getOutputStream();
try {
response.setContentType(ContentTypes.get(Paths.get(baseRequest.getPathInfo())));
response.addHeader("cache-control", "public, max-age=31536000");
response.addHeader("last-modified", startTime.format(DateTimeFormatter.RFC_1123_DATE_TIME));
response.addHeader("expires", ZonedDateTime.now().plusWeeks(1).format(DateTimeFormatter.RFC_1123_DATE_TIME));
int count;
byte[] buffer = new byte[BUFFER_SIZE];
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
} finally {
out.close();
}
} finally {
in.close();
}
}Example 89
| Project: spring4ws-demos-master File: BrainService.java View source code |
private static void handleIncomingIdea(BrainMessage bm) {
Board board = Board.get(bm.getBoard());
boolean isNew = false;
Idea idea;
if (bm.getId() != null) {
idea = board.getIdea(bm.getId());
} else {
isNew = true;
idea = Idea.createIdea();
}
idea.setDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
idea.setGroup(bm.getGroup());
idea.setText(bm.getText());
idea.setNext(bm.getNext());
if (isNew) {
board.addIdea(idea);
} else {
board.moveIdea(idea);
}
board.sendToAllUsers(idea);
}Example 90
| Project: SpringSecurityDemo-master File: SecuredUI.java View source code |
private void updateTimeAndUser() {
// Demonstrate that server push works, but the security context is not available inside the Timer thread
// since it is thread-local and populated by a servlet filter.
access(() -> timeAndUser.setValue(String.format("The server-side time is %s and the authentication token in this thread is %s", LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), SecurityContextHolder.getContext().getAuthentication())));
}Example 91
| Project: stork-master File: Deployments.java View source code |
public static Deployment install(Assembly assembly, Target target, DeployOptions options) {
String baseDir = baseDir(assembly.getName(), options);
String currentDir = baseDir + "/current";
String versionDir = baseDir + "/v" + assembly.getVersion();
if (assembly.isSnapshot()) {
Instant instant = Instant.ofEpochMilli(assembly.getCreatedAt());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
String date = ldt.format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss", Locale.US));
versionDir += "-" + date;
}
return new Deployment(baseDir, currentDir, versionDir, options.getUser(), options.getGroup());
}Example 92
| Project: syslog4j-graylog2-master File: CiscoSyslogServerEvent.java View source code |
@Override
protected void parseDate() {
// Skip leading spaces
while (message.charAt(0) == ' ') {
message = message.substring(1);
}
// Skip leading asterisk
if (message.charAt(0) == '*') {
message = message.substring(1);
}
int dateLength = message.indexOf(": ");
if (this.message.length() > dateLength) {
boolean isYearMissing = Character.isLetter(message.charAt(0));
String originalDate = this.message.substring(0, dateLength);
DateTimeFormatter formatter = DEFAULT_FORMATTER;
// Hacky override for: "Mar 06 2016 12:53:10 DEVICENAME :"
if (Character.isDigit(message.charAt(7)) && Character.isDigit(message.charAt(8)) && Character.isDigit(message.charAt(9)) && Character.isDigit(message.charAt(10))) {
dateLength = 20;
isYearMissing = false;
originalDate = this.message.substring(0, dateLength);
formatter = DateTimeFormatter.ofPattern("MMM ppd yyyy HH:mm:ss", Locale.ROOT).withZone(ZoneOffset.UTC);
}
try {
if (isYearMissing) {
String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));
String modifiedDate = year + " " + originalDate;
final ZonedDateTime dateTime = ZonedDateTime.parse(modifiedDate, formatter);
this.date = Date.from(dateTime.toInstant());
} else {
final ZonedDateTime dateTime = ZonedDateTime.parse(originalDate, formatter);
this.date = Date.from(dateTime.toInstant());
}
this.message = this.message.substring(dateLength + 1);
} catch (DateTimeParseException pe) {
this.date = new Date();
}
}
}Example 93
| Project: testcontainers-java-master File: DockerStatus.java View source code |
/**
* Based on this status, is this container running, and has it been doing so for the specified amount of time?
*
* @param state the state provided by InspectContainer
* @param minimumRunningDuration minimum duration to consider this as "solidly" running, or null
* @param now the time to consider as the current time
* @return true if we can conclude that the container is running, false otherwise
*/
public static boolean isContainerRunning(InspectContainerResponse.ContainerState state, Duration minimumRunningDuration, Instant now) {
if (state.getRunning()) {
if (minimumRunningDuration == null) {
return true;
}
Instant startedAt = DateTimeFormatter.ISO_INSTANT.parse(state.getStartedAt(), Instant::from);
if (startedAt.isBefore(now.minus(minimumRunningDuration))) {
return true;
}
}
return false;
}Example 94
| Project: trusted-overlord-master File: ReporterBuilder.java View source code |
private void writeToFile(StringBuffer content) {
try {
String summaryFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY_MM_dd_hh_mm_ss")) + "_summary.md";
Files.write(Paths.get(summaryFileName), content.toString().getBytes());
logger.info(summaryFileName + " markdown file generated ");
} catch (IOException e) {
logger.error(e);
}
}Example 95
| Project: web-budget-master File: UserMessage.java View source code |
/**
* Calcula o tempo que se passou desde o envio da mensagem
*/
public void calculateElapsedTime() {
final LocalDateTime sentOn = LocalDateTime.ofInstant(this.message.getInclusion().toInstant(), ZoneId.systemDefault());
if (sentOn.toLocalDate().isBefore(LocalDate.now())) {
this.elapsedTime = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm").format(sentOn);
} else {
long difference = ChronoUnit.MINUTES.between(sentOn.toLocalTime(), LocalTime.now());
if (difference > 60) {
difference = ChronoUnit.HOURS.between(sentOn.toLocalTime(), LocalTime.now());
this.elapsedTime = String.valueOf(difference);
this.timeUnit = "message-box.hours";
} else {
this.elapsedTime = String.valueOf(difference);
this.timeUnit = "message-box.minutes";
}
}
}Example 96
| Project: wss4j-master File: TimestampOutputProcessor.java View source code |
/*
<wsu:Timestamp wsu:Id="Timestamp-1247751600"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
2009-08-31T05:37:57.391Z
</wsu:Created>
<wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
2009-08-31T05:52:57.391Z
</wsu:Expires>
</wsu:Timestamp>
*/
@Override
public void processEvent(XMLSecEvent xmlSecEvent, OutputProcessorChain outputProcessorChain) throws XMLStreamException, XMLSecurityException {
outputProcessorChain.processEvent(xmlSecEvent);
if (WSSUtils.isSecurityHeaderElement(xmlSecEvent, ((WSSSecurityProperties) getSecurityProperties()).getActor())) {
final QName headerElementName = WSSConstants.TAG_WSU_TIMESTAMP;
OutputProcessorUtils.updateSecurityHeaderOrder(outputProcessorChain, headerElementName, getAction(), false);
Instant created = Instant.now();
int ttl = ((WSSSecurityProperties) getSecurityProperties()).getTimestampTTL();
Instant expires = created.plusSeconds(ttl);
OutputProcessorChain subOutputProcessorChain = outputProcessorChain.createSubChain(this);
//wsu:id is optional and will be added when signing...
createStartElementAndOutputAsEvent(subOutputProcessorChain, headerElementName, true, null);
createStartElementAndOutputAsEvent(subOutputProcessorChain, WSSConstants.TAG_WSU_CREATED, false, null);
DateTimeFormatter formatter = DateUtil.getDateTimeFormatter(true);
createCharactersAndOutputAsEvent(subOutputProcessorChain, created.atZone(ZoneOffset.UTC).format(formatter));
createEndElementAndOutputAsEvent(subOutputProcessorChain, WSSConstants.TAG_WSU_CREATED);
createStartElementAndOutputAsEvent(subOutputProcessorChain, WSSConstants.TAG_WSU_EXPIRES, false, null);
createCharactersAndOutputAsEvent(subOutputProcessorChain, expires.atZone(ZoneOffset.UTC).format(formatter));
createEndElementAndOutputAsEvent(subOutputProcessorChain, WSSConstants.TAG_WSU_EXPIRES);
createEndElementAndOutputAsEvent(subOutputProcessorChain, headerElementName);
outputProcessorChain.removeProcessor(this);
}
}Example 97
| Project: AsciidocFX-master File: ParserService.java View source code |
public Optional<String> toImageBlock(Image image) {
Path currentPath = directoryService.currentParentOrWorkdir();
IOHelper.createDirectories(currentPath.resolve("images"));
List<String> buffer = new LinkedList<>();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(asciiDocController.getClipboardImageFilePattern());
Path path = Paths.get(dateTimeFormatter.format(LocalDateTime.now()));
Path targetImage = currentPath.resolve("images").resolve(path.getFileName());
try {
BufferedImage fromFXImage = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(fromFXImage, "png", targetImage.toFile());
} catch (Exception e) {
logger.error("Problem occured while saving clipboard image {}", targetImage);
}
buffer.add(String.format("image::images/%s[]", path.getFileName()));
if (buffer.size() > 0)
return Optional.of(String.join("\n", buffer));
return Optional.empty();
}Example 98
| Project: assertj-core-java8-master File: ZonedDateTimeAssert_isAfter_Test.java View source code |
@Theory
public void test_isAfter_assertion(ZonedDateTime referenceDate, ZonedDateTime dateBefore, ZonedDateTime dateAfter) {
// GIVEN
testAssumptions(referenceDate, dateBefore, dateAfter);
// WHEN
assertThat(dateAfter).isAfter(referenceDate);
assertThat(dateAfter).isAfter(referenceDate.format(DateTimeFormatter.ISO_DATE_TIME));
// THEN
verify_that_isAfter_assertion_fails_and_throws_AssertionError(referenceDate, referenceDate);
verify_that_isAfter_assertion_fails_and_throws_AssertionError(dateBefore, referenceDate);
}Example 99
| Project: bgfinancas-master File: Tabela.java View source code |
public TableColumn<T, LocalDate> adicionarColunaData(TableView<T> tabela, String titulo, String atributo) {
TableColumn<T, LocalDate> coluna = new TableColumn<>(titulo);
tabela.getColumns().add(coluna);
coluna.setCellValueFactory( p -> new PropertyValueFactory<T, LocalDate>(atributo).call(p));
coluna.setCellFactory( e -> new TableCell<T, LocalDate>() {
@Override
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
setText(item == null ? null : item.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)));
}
});
return coluna;
}Example 100
| Project: Chronicle-Engine-master File: MainClusterClient.java View source code |
public static void main(String[] args) {
YamlLogging.setAll(false);
//YamlLogging.showServerWrites = true;
ClassAliasPool.CLASS_ALIASES.addAlias(ChronicleMapGroupFS.class);
ClassAliasPool.CLASS_ALIASES.addAlias(FilePerKeyGroupFS.class);
// TCPRegistry.createServerSocketChannelFor("host.port1", "host.port2");
@NotNull char[] xa = new char[VALUE_SIZE - new Random().nextInt(VALUE_SIZE / 10)];
Arrays.fill(xa, 'X');
@NotNull final String x = new String(xa);
@NotNull char[] ya = new char[VALUE_SIZE - new Random().nextInt(VALUE_SIZE / 10)];
Arrays.fill(ya, 'Y');
@NotNull final String y = new String(ya);
// Executors.newSingleThreadExecutor().submit(() -> {
@NotNull VanillaAssetTree tree5 = new VanillaAssetTree("tree1").forRemoteAccess(DESCRIPTION, WIRE_TYPE);
@NotNull final ConcurrentMap<String, String> map1 = tree5.acquireMap(NAME1, String.class, String.class);
@NotNull final ConcurrentMap<String, String> map2 = tree5.acquireMap(NAME2, String.class, String.class);
for (int count = 0; ; count++) {
@NotNull String v = DateTimeFormatter.ISO_LOCAL_TIME.format(LocalDateTime.now()) + " - " + (count % 2 == 0 ? x : y);
long start = System.currentTimeMillis();
for (int i = 0; i < entries; i++) {
try {
map1.put("" + i, v);
map2.put("" + i, v);
} catch (Throwable t) {
t.printStackTrace();
}
}
map1.size();
map2.size();
long time = System.currentTimeMillis() - start;
System.out.println("Send " + entries * 2 + " puts in " + time + " ms");
}
// });
/* Executors.newSingleThreadExecutor().submit(() -> {
VanillaAssetTree tree5 = new VanillaAssetTree("tree1").forRemoteAccess("localhost:8083",
WIRE_TYPE, x -> x.printStackTrace());
final ConcurrentMap<String, String> map1 = tree5.acquireMap(NAME, String.class,
String.class);
for (; ; ) {
for (int i = 0; i < entries; i++) {
try {
map1.remove("" + i);
// Jvm.pause(20);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
});
*/
/*
YamlLogging.setAll(false);
final ConcurrentMap<String, String> map;
AssetTree tree3 = new VanillaAssetTree("tree3").forRemoteAccess("localhost:8083",
WIRE_TYPE, z -> z.printStackTrace());
tree3.acquireMap(NAME, String.class, String.class).size();
int[] count = {0};
tree3.registerSubscriber(NAME, MapEvent.class, me -> {
System.out.print((me == null) ? "null" : me.getKey());
if (++count[0] >= 20) {
System.out.println();
count[0] = 0;
} else {
System.out.print("\t");
}
}
);
System.in.read();
*/
}Example 101
| Project: eclipse.platform.ui-master File: CSSSWTTestCase.java View source code |
@Before
public void setUp() {
System.out.println("[" + DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()) + "] " + getClass().getName() + "#" + testName.getMethodName());
System.out.format(" memory (free/max/total): %s/%s/%s MB\n", Runtime.getRuntime().freeMemory() / 1000000, Runtime.getRuntime().maxMemory() / 1000000, Runtime.getRuntime().totalMemory() / 1000000);
display = Display.getDefault();
}