List of usage examples for java.time.format DateTimeFormatter ofPattern
public static DateTimeFormatter ofPattern(String pattern)
From source file:squash.booking.lambdas.core.RuleManager.java
@Override public Optional<BookingRule> addRuleExclusion(String dateToExclude, BookingRule bookingRuleToAddExclusionTo, boolean isSquashServiceUserCall) throws Exception { if (!initialised) { throw new IllegalStateException("The rule manager has not been initialised"); }// w w w . j a va 2s. co m lifecycleManager.throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall); logger.log("About to add exclusion for " + dateToExclude + " to booking rule: " + bookingRuleToAddExclusionTo.toString()); // We retry the addition of the exclusion if necessary if we get a // ConditionalCheckFailed exception, i.e. if someone else modifies // the database between us reading and writing it. return RetryHelper.DoWithRetries((ThrowingSupplier<Optional<BookingRule>>) (() -> { ImmutablePair<Optional<Integer>, Set<BookingRule>> versionedBookingRules = getVersionedBookingRules(); Set<BookingRule> existingBookingRules = versionedBookingRules.right; // Check the BookingRule we're adding the exclusion to still // exists Optional<BookingRule> existingRule = existingBookingRules.stream() .filter(rule -> rule.equals(bookingRuleToAddExclusionTo)).findFirst(); if (!existingRule.isPresent()) { logger.log("Trying to add an exclusion to a booking rule that does not exist."); throw new Exception("Booking rule exclusion addition failed"); } // Check rule is recurring - we cannot add exclusions to // non-recurring rules if (!existingRule.get().getIsRecurring()) { logger.log("Trying to add an exclusion to a non-recurring booking rule."); throw new Exception("Booking rule exclusion addition failed"); } // Check that the rule exclusion we're creating does not exist // already. if (ArrayUtils.contains(existingRule.get().getDatesToExclude(), dateToExclude)) { logger.log("An identical booking rule exclusion exists already - so quitting early"); return Optional.empty(); } // Check the exclusion is for the right day of the week. DayOfWeek dayToExclude = dayOfWeekFromDate(dateToExclude); DayOfWeek dayOfBookingRule = dayOfWeekFromDate(existingRule.get().getBooking().getDate()); if (!dayToExclude.equals(dayOfBookingRule)) { logger.log("Exclusion being added and target booking rule are for different days of the week."); throw new Exception("Booking rule exclusion addition failed"); } // Check it is not in the past, relative to now, or to the // Booking rule start date. Date bookingRuleStartDate = new SimpleDateFormat("yyyy-MM-dd") .parse(existingRule.get().getBooking().getDate()); Date excludedDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateToExclude); if (excludedDate.before(bookingRuleStartDate)) { logger.log("Exclusion being added is before target booking rule start date."); throw new Exception("Booking rule exclusion addition failed"); } if (excludedDate.before(new SimpleDateFormat("yyyy-MM-dd") .parse(getCurrentLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))) { logger.log("Exclusion being added is in the past."); throw new Exception("Booking rule exclusion addition failed"); } // Check we'll not exceed the maximum number of dates to exclude // (this limit is here as SimpleDB has a 1024-byte limit for // attribute // values). Set<String> datesToExclude = Sets.newHashSet(bookingRuleToAddExclusionTo.getDatesToExclude()); if (datesToExclude.size() >= maxNumberOfDatesToExclude) { logger.log("The maximum number of booking rule exclusions(" + maxNumberOfDatesToExclude + ") exists already."); throw new Exception("Booking rule exclusion addition failed - too many exclusions"); } logger.log("Proceeding to add the new rule exclusion"); datesToExclude.add(dateToExclude); String attributeName = getAttributeNameFromBookingRule(bookingRuleToAddExclusionTo); String attributeValue = StringUtils.join(datesToExclude, ","); logger.log("ItemName: " + ruleItemName); logger.log("AttributeName: " + attributeName); logger.log("AttributeValue: " + attributeValue); ReplaceableAttribute bookingRuleAttribute = new ReplaceableAttribute(); bookingRuleAttribute.setName(attributeName); bookingRuleAttribute.setValue(attributeValue); bookingRuleAttribute.setReplace(true); optimisticPersister.put(ruleItemName, versionedBookingRules.left, bookingRuleAttribute); BookingRule updatedBookingRule = new BookingRule(bookingRuleToAddExclusionTo); updatedBookingRule.setDatesToExclude(datesToExclude.toArray(new String[datesToExclude.size()])); logger.log("Added new rule exclusion"); return Optional.of(updatedBookingRule); }), Exception.class, Optional.of("Database put failed - conditional check failed"), logger); }
From source file:com.acapulcoapp.alloggiatiweb.FileReader.java
public static Person extractPerson(String line) { Person p = new Person(); // String part = line.substring(start, start + COGNOME.getLength()).trim().toLowerCase(); // if (containsSpecialChar(part)) { // part = part.substring(0, part.length() - 1).trim().toLowerCase(); // start--; // }//w ww. j a v a2 s .co m p.setSurname(COGNOME.parse(line)); p.setName(NOME.parse(line)); String part = SESSO.parse(line); p.setGender(part.equals("1") ? Gender.male : Gender.female); part = DATA_NASCITA.parse(line); p.setDateOfBirth(LocalDate.parse(part, DateTimeFormatter.ofPattern(DATE_PATTERN))); part = COMUNE_NASCITA.parse(line); District d = districtRepository.find(part); p.setDistrictOfBirth(d); part = STATO_NASCITA.parse(line); Country c = countryRepository.find(part); p.setCountryOfBirth(c); part = CITTADINANZA.parse(line); c = countryRepository.find(part); p.setCitizenship(c); part = TIPO_DOCUMENTO.parse(line); IdentityDocument id = identityDocumentRepository.find(part); p.setIdentityDocument(id); part = NUMERO_DOCUMENTO.parse(line); if (!part.isEmpty()) { p.setDocumentNumber(part); } part = LUOGO_RILASCIO.parse(line); d = districtRepository.find(part); p.setDocumentReleaseDistrict(d); if (d == null) { c = countryRepository.find(part); p.setDocumentReleaseCountry(c); } return p; }
From source file:com.objy.se.ClassAccessor.java
void setMapper(IngestMapper mapper) { this.mapper = mapper; this.dateFormatter = DateTimeFormatter.ofPattern(mapper.getDateFormat()); this.dateTimeFormatter = DateTimeFormatter.ofPattern(mapper.getDateTimeFormat()); }
From source file:com.example.app.support.service.AppUtil.java
/** * Get a DateTimeFormatter to use for rendering time information within a time tag's datetime attribute * * @return a DateTimeFormatter//from w ww. java 2 s .co m */ @Nonnull public static DateTimeFormatter getDateTimeAttributeTimeFormat() { return DateTimeFormatter.ofPattern("hh:mm a"); }
From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java
/** * Gets a List of ElectionHeaders from the Bulletin Board and returns it. Fetched list depends on the given ElectionFilterTyp * @param filter/*ww w .j a va2 s. c o m*/ * The filter can be set to All, Open or Closed * @return returns a list of election headers */ public List<ElectionHeader> getElectionHeaders(ElectionFilterTyp filter) { List<ElectionHeader> electionHeaderlist = new ArrayList<ElectionHeader>(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime actualDateTime = LocalDateTime.now(); String dateTimeString = actualDateTime.format(format); URL url = null; //depending on the filter a different request is sent to the bulletin board switch (filter) { // if the filter is set to ALL, all the electionheaders on the bulletin board are requested case ALL: { try { url = new URL(bulletinBoardUrl + "/elections"); } catch (MalformedURLException ex) { Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex); } } break; // if the filter is set to OPEN only ElectionHeaders where the VotingPeriod is still going are requested from the bulletin board case OPEN: { try { url = new URL(bulletinBoardUrl + "/elections/open?date=" + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20")); } catch (UnsupportedEncodingException | MalformedURLException ex) { System.err.println(ex); } } break; // if the filter is set to CLOSED only ElectionHeaders where the VotingPeriod is already over are requested from the bulletin board case CLOSED: { try { url = new URL(bulletinBoardUrl + "/elections/closed?date=" + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20")); } catch (UnsupportedEncodingException | MalformedURLException ex) { System.err.println(ex); } } break; } try { InputStream urlInputStream = url.openStream(); JsonReader jsonReader = Json.createReader(urlInputStream); JsonArray obj = jsonReader.readArray(); //Recieved Json String is transformed into a list of ElectionHeader objects for (JsonObject result : obj.getValuesAs(JsonObject.class)) { int id = Integer.parseInt(result.getString("id")); String title = result.getString("electionTitle"); LocalDateTime beginDate = LocalDateTime.parse(result.getString("beginDate"), format); LocalDateTime endDate = LocalDateTime.parse(result.getString("endDate"), format); ElectionHeader electionHeader = new ElectionHeader(id, title, beginDate, endDate); electionHeaderlist.add(electionHeader); } } catch (IOException x) { System.err.println(x); } return electionHeaderlist; }
From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java
/** * This function saves an event. The function is invoked by POSTint the parameters to the URI /api/admin/event. * @param eventFlag This flag either stores the ID of the event, or true, if a new event is created. * @param eventName The name of the event. * @param eventDescription The description of the event. * @param startDate The start date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter. * @param startTime The start time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter. * @param endDate The end date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter. * @param endTime The end time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter. * @param location The name of the location of the event. * @param locationLat The latitude of the location of the event. * @param locationLng The longitude of the location of the event. * @param invitedDivisions A comma separated list of invited divisions. * @param currentUser The currently logged in user. * @return An HTTP response with a status code together with a JSON map object, containing an 'errorMessage', or a 'successMessage' respectively. If the operation was successful the id of the event is accessible via 'eventID'. *//*from w w w.j ava 2 s . com*/ @RequestMapping(method = RequestMethod.POST, produces = "application/json") public ResponseEntity<Map<String, String>> saveEvent(@RequestParam String eventFlag, @RequestParam String eventName, @RequestParam String eventDescription, @RequestParam String startDate, @RequestParam String startTime, @RequestParam String endDate, @RequestParam String endTime, @RequestParam String location, @RequestParam String locationLat, @RequestParam String locationLng, @RequestParam String invitedDivisions, @CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Saving event"); Map<String, String> responseMap = new HashMap<>(); Event event; if (eventFlag.isEmpty()) { logger.warn("[" + currentUser + "] The event flag is empty"); responseMap.put("errorMessage", "The event flag is not allowed to be empty"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } else if (eventFlag.equals("true")) { logger.debug("[" + currentUser + "] A new event is created"); event = new Event(); } else { logger.debug("[" + currentUser + "] The event with id " + eventFlag + " is altered"); event = eventRepository.findEventById(eventFlag); if (event == null) { logger.warn("[" + currentUser + "] Unable to find the specified event with id " + eventFlag); responseMap.put("errorMessage", "Unable to find the specified event"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } else if (!currentUser.isAllowedToAdministrate(event)) { logger.warn( "[" + currentUser + "] The user is not allowed to alter the selected event " + eventFlag); responseMap.put("errorMessage", "You are not allowed to edit the selected event"); return new ResponseEntity<>(responseMap, HttpStatus.FORBIDDEN); } } event.setName(eventName); event.setDescription(eventDescription); if (startDate.isEmpty() || startTime.isEmpty() || endDate.isEmpty() || endTime.isEmpty()) { logger.warn("[" + currentUser + "] The date and times defining the event (ID " + eventFlag + ") are not allowed to be empty."); responseMap.put("errorMessage", "The date and times defining the event are not allowed to be empty"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } else { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/y'T'H:m"); try { event.setStartDateTime(LocalDateTime.parse(startDate + "T" + startTime, formatter)); } catch (DateTimeParseException e) { logger.warn("[" + currentUser + "] Unrecognized date format " + startDate + "T" + startTime); responseMap.put("errorMessage", "Unrecognized date or time format within start time"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } try { event.setEndDateTime(LocalDateTime.parse(endDate + "T" + endTime, formatter)); } catch (DateTimeParseException e) { logger.warn("[" + currentUser + "] Unrecognized date format " + endDate + "T" + endTime); responseMap.put("errorMessage", "Unrecognized date or time format within end time"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } } event.setLocation(location); if (!locationLat.isEmpty()) { try { event.setLocationLat(Double.parseDouble(locationLat)); } catch (NumberFormatException e) { logger.warn("[" + currentUser + "] Unable to paste lat " + locationLat); responseMap.put("errorMessage", "Unable to parse latitude coordinate"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } } if (!locationLng.isEmpty()) { try { event.setLocationLng(Double.parseDouble(locationLng)); } catch (NumberFormatException e) { logger.warn("[" + currentUser + "] Unable to paste lng " + locationLng); responseMap.put("errorMessage", "Unable to parse longitude coordinate"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } } if (!invitedDivisions.isEmpty()) { String[] divArray = invitedDivisions.split(","); for (String division : divArray) { Division div = divisionRepository.findByName(division); if (div == null) { logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")"); responseMap.put("errorMessage", "Division " + division + " does not exist"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } event.addDivision(div); } event.updateInvitedUser(divisionRepository); } else if (event.getInvitedDivision() != null && !event.getInvitedDivision().isEmpty()) { event.updateInvitedUser(divisionRepository); } //Updating several fields. event.setEventAdmin(currentUser); event.setLastChanged(LocalDateTime.now()); event.updateMultiDate(); try { eventRepository.save(event); logger.info("[" + currentUser + "] Successfully saved event " + eventFlag); responseMap.put("successMessage", "Successfully saved the event"); responseMap.put("eventID", event.getId()); return new ResponseEntity<>(responseMap, HttpStatus.OK); } catch (ConstraintViolationException e) { logger.warn( "[" + currentUser + "] A database constraint was violated while saving the event " + eventFlag); responseMap.put("errorMessage", "A database constraint was violated while saving the event"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java
@Test public void testConfUpdate() throws Exception { LocalDateTime now = LocalDateTime.now(); Date nbf = DateUtils.localDateTime2Date(now); LocalDateTime expiration = now.plus(10, ChronoUnit.MINUTES); Date expirationDate = DateUtils.localDateTime2Date(expiration); JWTClaimsSet masterClaims = new JWTClaimsSet(); masterClaims.setSubject("master_token"); masterClaims.setExpirationTime(expirationDate); masterClaims.setNotBeforeTime(nbf);//w w w . j a va2s . c o m String newMasterToken = jwtIssuer.generate(masterClaims); Assert.assertNotNull(newMasterToken); String[] newRenewalTokens = new String[5]; JWTClaimsSet renewClaims = new JWTClaimsSet(); renewClaims.setSubject("renew_token"); renewClaims.setExpirationTime(expirationDate); renewClaims.setNotBeforeTime(nbf); for (int i = 0; i < newRenewalTokens.length; i++) { String renewToken = jwtIssuer.generate(renewClaims); Assert.assertNotNull(renewToken); newRenewalTokens[i] = renewToken; } RMAppSecurityActions actor = new TestingHopsworksActions(newMasterToken, expirationDate, newRenewalTokens); ((Configurable) actor).setConf(conf); actor.init(); TimeUnit.MILLISECONDS.sleep(500); // Renewal must have happened, check new values in ssl-server Configuration sslConf = new Configuration(); sslConf.addResource(conf.get(SSLFactory.SSL_SERVER_CONF_KEY)); String newMasterTokenConf = sslConf.get(YarnConfiguration.RM_JWT_MASTER_TOKEN, ""); Assert.assertEquals(newMasterToken, newMasterTokenConf); for (int i = 0; i < newRenewalTokens.length; i++) { String confKey = String.format(YarnConfiguration.RM_JWT_RENEW_TOKEN_PATTERN, i); String newRenewalToken = sslConf.get(confKey, ""); Assert.assertEquals(newRenewalTokens[i], newRenewalToken); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); Assert.assertEquals(expiration.format(formatter), ((HopsworksRMAppSecurityActions) actor).getMasterTokenExpiration().format(formatter)); actor.destroy(); }
From source file:daylightchart.daylightchart.calculation.RiseSetUtility.java
/** * Debug calculations./*from w w w . j a va2s.co m*/ * * @param writer * Writer to write to * @param location * Location to debug * @param daylightBandType * Types of band type to write to */ @SuppressWarnings("boxing") private static void writeCalculations(final Writer writer, final Location location, final TwilightType twilight, final DaylightBandType... daylightBandType) { if (writer == null || location == null) { return; } final DecimalFormat format = new DecimalFormat("00.000"); format.setMaximumFractionDigits(3); final int year = Year.now().getValue(); final Options options = new Options(); options.setTwilightType(twilight); final RiseSetYearData riseSetYear = createRiseSetYear(location, year, options); final PrintWriter printWriter = new PrintWriter(writer, true); // Header printWriter.printf("Location\t%s%nDate\t%s%n%n", location, year); // Bands final List<DaylightBand> bands = riseSetYear.getBands(); for (final Iterator<DaylightBand> iterator = bands.iterator(); iterator.hasNext();) { final DaylightBand band = iterator.next(); if (!ArrayUtils.contains(daylightBandType, band.getDaylightBandType())) { iterator.remove(); } } printWriter.printf("\t\t\t"); if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) { printWriter.printf("\t\t"); } for (final DaylightBand band : bands) { printWriter.printf("Band\t%s\t", band.getName()); } printWriter.println(); // Data rows printWriter.print("Date\tSunrise\tSunset"); if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) { printWriter.println("\tTwilight Rise\tTwilight Set"); } else { printWriter.println(); } final List<RawRiseSet> rawRiseSets = riseSetYear.getRawRiseSets(); final List<RawRiseSet> rawTwilights = riseSetYear.getRawTwilights(); for (int i = 0; i < rawRiseSets.size(); i++) { final RawRiseSet rawRiseSet = rawRiseSets.get(i); printWriter.printf("%s\t%s\t%s", rawRiseSet.getDate(), format.format(rawRiseSet.getSunrise()), format.format(rawRiseSet.getSunset())); if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) { final RawRiseSet rawTwilight = rawTwilights.get(i); printWriter.printf("\t%s\t%s", format.format(rawTwilight.getSunrise()), format.format(rawTwilight.getSunset())); } for (final DaylightBand band : bands) { final RiseSet riseSet = band.get(rawRiseSet.getDate()); if (riseSet == null) { printWriter.print("\t\t"); } else { printWriter.printf("\t%s\t%s", riseSet.getSunrise().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")), riseSet.getSunset().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"))); } } printWriter.println(); } }
From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java
public long parseTimestamp(String timestamp) { String definedPattern = properties.get(TIMESTAMP_PATTERN); if (definedPattern != null) { DateTimeFormatter formatter = null; try {// w ww. j av a 2 s. co m formatter = DateTimeFormatter.ofPattern(definedPattern); return ZonedDateTime.parse(timestamp, formatter).toInstant().toEpochMilli(); } catch (Exception e) { log.debugf("Not able to parse [%s] with format [%s]", timestamp, formatter); } } for (DateTimeFormatter formatter : DEFAULT_DATE_FORMATS) { try { return ZonedDateTime.parse(timestamp, formatter).toInstant().toEpochMilli(); } catch (Exception e) { log.debugf("Not able to parse [%s] with format [%s]", timestamp, formatter); } } try { return new Long(timestamp).longValue(); } catch (Exception e) { log.debugf("Not able to parse [%s] as plain timestamp", timestamp); } return System.currentTimeMillis(); }
From source file:it.tidalwave.northernwind.frontend.ui.component.blog.htmltemplate.HtmlTemplateBlogViewController.java
/******************************************************************************************************************* * * * ******************************************************************************************************************/ @Nonnull// ww w . j a v a 2 s.c om private DateTimeFormatter getDateTimeFormatter() { try { final String pattern = siteNode.getPropertyGroup(view.getId()).getProperty(PROPERTY_DATE_FORMAT) .replaceAll("EEEEE+", "EEEE").replaceAll("MMMMM+", "MMMM"); return ((pattern.length() == 2) ? STYLE_MAP.get(pattern) : DateTimeFormatter.ofPattern(pattern)) .withLocale(requestLocaleManager.getLocales().get(0)); } catch (NotFoundException | IOException e) { } return requestLocaleManager.getDateTimeFormatter(); }