List of usage examples for java.time.format DateTimeFormatter ofPattern
public static DateTimeFormatter ofPattern(String pattern)
From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java
/** * Gets the information for the given ElectionID from the bulletin board and returns it as a election object * @param electionId/*w ww . ja va 2 s . c o m*/ * the identifier (id) for the desired election * @return returns tje election object for a given id */ public Election getElectionById(int electionId) { Election election = null; try { URL url = new URL(bulletinBoardUrl + "/elections/" + electionId); InputStream urlInputStream = url.openStream(); JsonReader jsonReader = Json.createReader(urlInputStream); JsonObject obj = jsonReader.readObject(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); Parameters parameters = this.getParameters(); //gets the json string and transforms it into a election object //translates the header information of the election String title = obj.getString("electionTitle"); LocalDateTime beginDate = LocalDateTime.parse(obj.getString("beginDate"), format); LocalDateTime endDate = LocalDateTime.parse(obj.getString("endDate"), format); String appVersion = obj.getString("appVersion"); String coefficientsString = obj.getString("coefficients"); String h_HatString = obj.getString("electionGenerator"); List<Voter> voterlist = new ArrayList<Voter>(); //get th list of voters for (JsonObject result : obj.getJsonArray("voters").getValuesAs(JsonObject.class)) { String voterEmail = result.getString("email"); String voterPublicCredential = result.getString("publicCredential"); String voterAppVersion = result.getString("appVersion"); Voter voter = new Voter(voterEmail, voterPublicCredential, voterAppVersion); voterlist.add(voter); } //get the votingTopic JsonObject electionTopicObj = obj.getJsonObject("votingTopic"); String topic = electionTopicObj.getString("topic"); int pick = electionTopicObj.getInt("pick"); ElectionTopic electionTopic = new ElectionTopic(topic, pick); JsonArray optionsArray = electionTopicObj.getJsonArray("options"); for (int i = 0; i < optionsArray.size(); i++) { electionTopic.addOption(optionsArray.getString(i)); } election = new Election(electionId, title, voterlist, parameters, beginDate, endDate, electionTopic, appVersion, h_HatString, coefficientsString); } catch (IOException x) { System.err.println(x); } return election; }
From source file:com.gnadenheimer.mg3.utils.Utils.java
public Boolean exectueBackUp(String backupDirectory) { try {/*from w ww .j a v a 2s . c o m*/ //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); //String backupfile = backupDirectory + "\\BackUp_" + sdf.format(new LocalDateTime()); String backupfile = backupDirectory + "\\BackUp_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")); Connection conn = DriverManager.getConnection(getPersistenceMap().get("javax.persistence.jdbc.url"), getPersistenceMap().get("javax.persistence.jdbc.user"), getPersistenceMap().get("javax.persistence.jdbc.password")); try (CallableStatement cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)")) { cs.setString(1, backupfile); cs.execute(); cs.close(); } catch (Exception ex) { LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); App.showException(Thread.currentThread().getStackTrace()[1].getMethodName(), ex.getMessage(), ex); } App.showInfo("BackUp", "BackUp guardado con exito en: " + backupfile); return true; } catch (Exception ex) { LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); App.showException(Thread.currentThread().getStackTrace()[1].getMethodName(), ex.getMessage(), ex); return false; } }
From source file:squash.booking.lambdas.core.RuleManagerTest.java
@Test public void testCreateRuleThrowsWhenTheOptimisticPersisterThrows() throws Exception { // N.B. This applies except when the optimistic persister throws a // conditional check failed exclusion, which is covered by other tests. // ARRANGE//from ww w . j av a2 s . c o m thrown.expect(Exception.class); String message = "Test OptimisticPersister exception"; thrown.expectMessage(message); // Set up a rule to create that does not clash with existing rules BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule); // Change day-of-week so it no longer clashes String existingDate = nonClashingRule.getBooking().getDate(); String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1) .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); nonClashingRule.getBooking().setDate(newDate); // Wednesday mockery.checking(new Expectations() { { oneOf(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()), with(anything())); will(throwException(new Exception(message))); } }); // ACT doTestCreateRuleClashesOrNotWithExistingRule(nonClashingRule, true); }
From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java
public String formatTimestamp(Date date) { String definedPattern = properties.get(TIMESTAMP_PATTERN); if (definedPattern != null) { DateTimeFormatter formatter = null; try {//from w ww . jav a 2 s. c om formatter = DateTimeFormatter.ofPattern(definedPattern); return formatter.format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), UTC)); } catch (Exception e) { log.debugf("Not able to format [%s] with pattern [%s]", date, formatter); } } return DEFAULT_DATE_FORMATS[0].format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), UTC)); }
From source file:com.gnadenheimer.mg.utils.Utils.java
public Boolean exectueBackUp(String backupDirectory) { try {//from w w w.java 2 s .c om //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); //String backupfile = backupDirectory + "\\BackUp_" + sdf.format(new LocalDateTime()); String backupfile = backupDirectory + "\\BackUp_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")); Connection conn = getDatabaseConnection(); try (CallableStatement cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)")) { cs.setString(1, backupfile); cs.execute(); cs.close(); } catch (Exception ex) { LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); JOptionPane.showMessageDialog(null, Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage()); } JOptionPane.showMessageDialog(null, "BackUp guardado con exito en: " + backupfile); return true; } catch (Exception ex) { LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); JOptionPane.showMessageDialog(null, Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage()); return false; } }
From source file:org.openhab.binding.ntp.test.NtpOSGiTest.java
private void assertFormat(String initialDate, String formatPattern) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern); final ZonedDateTime date; date = ZonedDateTime.parse(initialDate, formatter); String formattedDate = formatter.format(date); assertEquals(initialDate, formattedDate); }
From source file:squash.booking.lambdas.core.RuleManagerTest.java
@Test public void testCreateRuleThrowsIfTheOptimisticPersisterThrowsAConditionalCheckFailedExceptionThreeTimesRunning() throws Exception { // The optimistic persister can throw a conditional check failed exclusion // if two database writes happen to get interleaved. Almost always, a retry // should fix this, and we allow up to three tries. This tests that if all // three tries fail then the rule manager will give up and throw. // ARRANGE//from ww w . j av a 2 s .c o m thrown.expect(Exception.class); String message = "Database put failed - conditional check failed"; thrown.expectMessage(message); int versionToUse = 1; // Arbitrary expectOptimisticPersisterToReturnVersionedAttributes(versionToUse, 3); initialiseRuleManager(); // Set up a rule to create that does not clash with existing rules BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule); // Change day-of-week so it no longer clashes String existingDate = nonClashingRule.getBooking().getDate(); String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1) .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); nonClashingRule.getBooking().setDate(newDate); // Wednesday mockery.checking(new Expectations() { { // All three tries throw exactly(3).of(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()), with(anything())); will(throwException(new Exception(message))); } }); // ACT // This should throw - albeit after three tries internally. // N.B. The second parameter is arbitrary here. ruleManager.createRule(nonClashingRule, true); }
From source file:squash.booking.lambdas.core.RuleManager.java
@Override public List<Booking> applyRules(String date, boolean isSquashServiceUserCall) throws Exception { if (!initialised) { throw new IllegalStateException("The rule manager has not been initialised"); }/*from w ww . j a v a 2s . c o m*/ lifecycleManager.throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall); List<Booking> ruleBookings = new ArrayList<>(); try { // Apply rules only if date is not in the past. Boolean applyDateIsInPast = (new SimpleDateFormat("yyyy-MM-dd").parse(date)) .before((new SimpleDateFormat("yyyy-MM-dd") .parse(getCurrentLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))); if (!applyDateIsInPast) { logger.log("About to apply booking rules for date: " + date); for (BookingRule rule : getRules(false)) { logger.log("Considering booking rule: " + rule); Boolean ruleIsNonRecurringAndForApplyDate = !rule.getIsRecurring() && rule.getBooking().getDate().equals(date); Boolean ruleIsRecurringAndStartsOnOrBeforeApplyDate = rule.getIsRecurring() && dayOfWeekFromDate(rule.getBooking().getDate()).equals(dayOfWeekFromDate(date)) && !((new SimpleDateFormat("yyyy-MM-dd")).parse(date).before( (new SimpleDateFormat("yyyy-MM-dd")).parse(rule.getBooking().getDate()))); if (ruleIsNonRecurringAndForApplyDate || ruleIsRecurringAndStartsOnOrBeforeApplyDate) { if (ruleIsRecurringAndStartsOnOrBeforeApplyDate) { logger.log( "Booking rule recurring and starts before date that rules are being applied to: " + rule.toString()); // Does this rule have a relevant exclusion? if (ArrayUtils.contains(rule.getDatesToExclude(), date)) { logger.log("Recurring rule does not apply as it has a matching rule exclusion"); continue; } } else { logger.log( "Booking rule non-recurring but applies to date that rules are being applied to."); } logger.log("Applying booking rule to create booking: " + rule.toString()); Booking booking = rule.getBooking(); booking.setDate(date); bookingManager.createBooking(booking, false); ruleBookings.add(booking); // Short sleep to minimise chance of getting TooManyRequests error try { Thread.sleep(10); } catch (InterruptedException interruptedException) { logger.log("Sleep before applying next rule has been interrupted."); } logger.log("Rule-based booking created."); } else { logger.log("Rule does not apply to date that rules are being applied to."); } } } } catch (Exception exception) { logger.log("Exception caught while applying booking rules - so notifying sns topic"); getSNSClient().publish(adminSnsTopicArn, "Apologies - but there was an error applying the booking rules for " + date + ". Please make the rule bookings for this date manually instead. The error message was: " + exception.getMessage(), "Sqawsh booking rules failed to apply"); // Rethrow throw exception; } logger.log("About to purge expired rules and exclusions."); purgeExpiredRulesAndRuleExclusions(); logger.log("Purged expired rules and exclusions."); return ruleBookings; }
From source file:org.codelibs.fess.service.SearchLogService.java
private void buildSearchCondition(final SearchLogPager searchLogPager, final SearchLogCB cb1, final ClickLogCB cb2) { if (StringUtil.isNotBlank(searchLogPager.searchWord)) { cb1.query().setSearchWord_LikeSearch(searchLogPager.searchWord, op -> op.likeContain()); if (cb2 != null) { cb2.query().querySearchLog().setSearchWord_LikeSearch(searchLogPager.searchWord, op -> op.likeContain()); }// w w w.j av a 2 s . c o m } if (StringUtil.isNotBlank(searchLogPager.userCode)) { cb1.setupSelect_UserInfo(); cb1.query().queryUserInfo().setCode_Equal(searchLogPager.userCode); } if (StringUtil.isNotBlank(searchLogPager.startDate)) { final StringBuilder buf = new StringBuilder(20); buf.append(searchLogPager.startDate); buf.append('+'); if (StringUtil.isNotBlank(searchLogPager.startHour)) { buf.append(searchLogPager.startHour); } else { buf.append("00"); } buf.append(':'); if (StringUtil.isNotBlank(searchLogPager.startMin)) { buf.append(searchLogPager.startMin); } else { buf.append("00"); } final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm"); try { final LocalDateTime startDate = LocalDateTime.parse(buf.toString(), formatter); cb1.query().setRequestedTime_GreaterEqual(startDate); if (cb2 != null) { cb2.query().querySearchLog().setRequestedTime_GreaterEqual(startDate); } } catch (final DateTimeParseException e) { searchLogPager.startDate = null; searchLogPager.startHour = null; searchLogPager.startMin = null; } } if (StringUtil.isNotBlank(searchLogPager.endDate)) { final StringBuilder buf = new StringBuilder(20); buf.append(searchLogPager.endDate); buf.append('+'); if (StringUtil.isNotBlank(searchLogPager.endHour)) { buf.append(searchLogPager.endHour); } else { buf.append("00"); } buf.append(':'); if (StringUtil.isNotBlank(searchLogPager.endMin)) { buf.append(searchLogPager.endMin); } else { buf.append("00"); } final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm"); try { final LocalDateTime endDate = LocalDateTime.parse(buf.toString(), formatter); cb1.query().setRequestedTime_LessThan(endDate); if (cb2 != null) { cb2.query().querySearchLog().setRequestedTime_LessThan(endDate); } } catch (final DateTimeParseException e) { searchLogPager.endDate = null; searchLogPager.endHour = null; searchLogPager.endMin = null; } } if (StringUtil.isNotBlank(searchLogPager.startPage)) { cb1.query().setQueryOffset_Equal(0); if (cb2 != null) { cb2.query().querySearchLog().setQueryOffset_Equal(0); } } }
From source file:org.talend.dataprep.transformation.actions.date.ComputeTimeSinceTest.java
/** * Compute time since .//from w w w .j a va2 s .com * * @param date the date to compute from. * @param pattern the pattern to use. * @param unit the unit for the result. * @param sinceWhen the date to calculate since when * @return time since now in the wanted unit. */ String computeTimeSince(String date, String pattern, ChronoUnit unit, String sinceWhen) { DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern); Temporal since; if (sinceWhen == null) { since = LocalDateTime.now(); } else { since = LocalDateTime.parse(sinceWhen, format); } LocalDateTime start; try { start = LocalDateTime.parse(date, format); } catch (Exception e) { start = null; } if (start == null) { LocalDate temp = LocalDate.parse(date, format); start = temp.atStartOfDay(); } Temporal result = LocalDateTime.from(start); return String.valueOf(unit.between(result, since)); }