List of usage examples for java.time.format DateTimeFormatter ofPattern
public static DateTimeFormatter ofPattern(String pattern)
From source file:org.cgiar.ccafs.marlo.action.center.summaries.OutcomesContributionsSummaryAction.java
/** * Get the main information of the report * /*from w w w . j a v a2s .com*/ * @return */ private TypedTableModel getMasterTableModel() { // Initialization of Model TypedTableModel model = new TypedTableModel( new String[] { "current_date", "imageUrl", "research_program_id", "center", "researchProgramTitle" }, new Class[] { String.class, String.class, Long.class, String.class, String.class }); String currentDate = ""; // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); currentDate = timezone.format(format) + this.getTimeZone(); // Get CIAT imgage URL from repo String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png"; String center = null; center = researchProgram.getResearchArea().getResearchCenter().getName(); String researchProgramTitle = null; if (researchProgram.getName() != null && !researchProgram.getName().trim().isEmpty()) { researchProgramTitle = researchProgram.getName(); } model.addRow(new Object[] { currentDate, imageUrl, researchProgram.getId(), center, researchProgramTitle }); return model; }
From source file:org.cgiar.ccafs.marlo.action.center.summaries.ImpactPathwayOutcomesSummaryAction.java
/** * Get the main information of the report * //from ww w . j a v a 2 s. co m * @return */ private TypedTableModel getMasterTableModel() { // Initialization of Model TypedTableModel model = new TypedTableModel( new String[] { "title", "current_date", "imageUrl", "research_program_id" }, new Class[] { String.class, String.class, String.class, Long.class }); String title = "Impact Pathway Full Report"; String currentDate = ""; // Get title title = researchProgram.getResearchArea().getAcronym() + ", " + researchProgram.getComposedName() + ", Organized by Impact"; // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); currentDate = timezone.format(format) + this.getTimeZone(); // Get CIAT imgage URL from repo String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png"; model.addRow(new Object[] { title, currentDate, imageUrl, researchProgram.getId() }); return model; }
From source file:com.actelion.research.spiritcore.services.SampleListValidator.java
private boolean checkDateFormat(String[][] data, int col) throws Exception { DateTimeFormatter dtf = dtfBuilder.toFormatter(); DateTimeFormatter outDateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy"); for (int i = 1; i < data.length; i++) { try {//from w w w .jav a 2 s. co m if (col >= data[i].length || data[i][col] == null || data[i][col].isEmpty()) { continue; } LocalDate inDate = LocalDate.parse(data[i][col], dtf); data[i][col] = inDate.format(outDateFormatter); } catch (DateTimeParseException dtpe) { specificErrorMessage = "Found value '" + data[i][col] + "' at line " + (i + 1); throw new Exception("Some dates are not in the format '" + Arrays.toString(dtPatterns) + "'.\r\n" + specificErrorMessage); } } return true; }
From source file:squash.booking.lambdas.core.PageManager.java
/** * Creates and returns the website's booking page for a specified date. * /* ww w .ja v a 2 s . c om*/ * <p>This is not private only so that it can be unit-tested. * * @param date the date in YYYY-MM-DD format. * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format. * @param reservationFormGetUrl the Url from which to get a reservation form * @param cancellationFormGetUrl the Url from which to get a cancellation form. * @param s3WebsiteUrl the base Url of the bookings website bucket. * @param bookings the bookings for the specified date. * @param pageGuid the guid to embed within the page - used by AATs. * @param revvingSuffix the suffix to use for the linked css file, used for cache rev-ing. * @throws Exception */ protected String createBookingPage(String date, List<String> validDates, String reservationFormGetUrl, String cancellationFormGetUrl, String s3WebsiteUrl, List<Booking> bookings, String pageGuid, String revvingSuffix) throws Exception { ImmutablePair<LifecycleState, Optional<String>> lifecycleState = lifecycleManager.getLifecycleState(); // N.B. we assume that the date is known to be a valid date logger.log("About to create booking page"); logger.log("Lifecycle state is: " + lifecycleState.left.name()); if (lifecycleState.left.equals(LifecycleState.RETIRED)) { logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get()); } Integer numCourts = 5; // Get dates in longhand format for display on the dropdown DateTimeFormatter longFormatter = DateTimeFormatter.ofPattern("EE, d MMM, yyyy"); DateTimeFormatter shortFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); List<String> validDatesLong = new ArrayList<>(); validDates.stream().forEach((validDate) -> { LocalDate localDate = java.time.LocalDate.parse(validDate, shortFormatter); validDatesLong.add(localDate.format(longFormatter)); }); // In order to merge the day's bookings with our velocity template, we need // to create an object with bookings on a grid corresponding to the html // table. For each grid cell, we need to know whether the cell is booked, // and if it is, the name of the booking, and, if it's a block booking, the // span of the block and whether this cell is interior to the block. logger.log("About to set up velocity context"); List<ArrayList<Boolean>> bookedState = new ArrayList<>(); List<ArrayList<Integer>> rowSpan = new ArrayList<>(); List<ArrayList<Integer>> colSpan = new ArrayList<>(); List<ArrayList<Boolean>> isBlockInterior = new ArrayList<>(); List<ArrayList<String>> names = new ArrayList<>(); // First set up default arrays for case of no bookings for (int slot = 1; slot <= 16; slot++) { bookedState.add(new ArrayList<>()); rowSpan.add(new ArrayList<>()); colSpan.add(new ArrayList<>()); isBlockInterior.add(new ArrayList<>()); names.add(new ArrayList<>()); for (int court = 1; court <= numCourts; court++) { bookedState.get(slot - 1).add(false); rowSpan.get(slot - 1).add(1); colSpan.get(slot - 1).add(1); isBlockInterior.get(slot - 1).add(true); names.get(slot - 1).add(""); } } // Mutate cells which are in fact booked for (Booking booking : bookings) { for (int court = booking.getCourt(); court < booking.getCourt() + booking.getCourtSpan(); court++) { for (int slot = booking.getSlot(); slot < booking.getSlot() + booking.getSlotSpan(); slot++) { bookedState.get(slot - 1).set(court - 1, true); rowSpan.get(slot - 1).set(court - 1, booking.getSlotSpan()); colSpan.get(slot - 1).set(court - 1, booking.getCourtSpan()); isBlockInterior.get(slot - 1).set(court - 1, ((court == booking.getCourt()) && (slot == booking.getSlot())) ? false : true); names.get(slot - 1).set(court - 1, booking.getName()); } } } // Create the page by merging the data with the page template VelocityEngine engine = new VelocityEngine(); // Use the classpath loader so Velocity finds our template Properties properties = new Properties(); properties.setProperty("resource.loader", "class"); properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); engine.init(properties); VelocityContext context = new VelocityContext(); context.put("pageGuid", pageGuid); context.put("s3WebsiteUrl", s3WebsiteUrl); context.put("reservationFormGetUrl", reservationFormGetUrl); context.put("cancellationFormGetUrl", cancellationFormGetUrl); context.put("pagesDate", date); context.put("validDates", validDates); context.put("validDatesLong", validDatesLong); context.put("numCourts", numCourts); context.put("timeSlots", getTimeSlotLabels()); context.put("bookedState", bookedState); context.put("rowSpan", rowSpan); context.put("colSpan", colSpan); context.put("isBlockInterior", isBlockInterior); context.put("names", names); context.put("revvingSuffix", revvingSuffix); context.put("lifecycleState", lifecycleState.left.name()); context.put("forwardingUrl", lifecycleState.right.isPresent() ? lifecycleState.right.get() : ""); logger.log("Set up velocity context"); // TODO assert some sensible invariants on data sizes? // Render the page logger.log("About to render booking page"); StringWriter writer = new StringWriter(); Template template = engine.getTemplate("squash/booking/lambdas/BookingPage.vm", "utf-8"); template.merge(context, writer); logger.log("Rendered booking page: " + writer); return writer.toString(); }
From source file:org.codelibs.fess.service.SearchLogService.java
public void importCsv(final Reader reader) { final CsvReader csvReader = new CsvReader(reader, new CsvConfig()); final DateTimeFormatter formatter = DateTimeFormatter .ofPattern(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND); try {/* w w w . ja va 2 s .com*/ List<String> list; csvReader.readValues(); // ignore header while ((list = csvReader.readValues()) != null) { try { final SearchLog entity = new SearchLog(); entity.setSearchWord(list.get(0)); entity.setSearchQuery(list.get(1)); entity.setSolrQuery(list.get(2)); entity.setRequestedTime(LocalDateTime.parse(list.get(3), formatter)); entity.setResponseTime(Integer.parseInt(list.get(4))); entity.setHitCount(Long.parseLong(list.get(5))); entity.setQueryOffset(Integer.parseInt(list.get(6))); entity.setQueryPageSize(Integer.parseInt(list.get(7))); entity.setUserAgent(list.get(8)); entity.setReferer(list.get(9)); entity.setClientIp(list.get(10)); entity.setUserSessionId(list.get(11)); entity.setAccessTypeAsAccessType(AccessType.valueOf(list.get(12))); if (list.size() >= 14) { final String jsonStr = list.get(13); @SuppressWarnings("rawtypes") final List objList = JSON.decode(jsonStr); for (final Object obj : objList) { @SuppressWarnings("rawtypes") final Map objMap = (Map) obj; entity.addSearchFieldLogValue((String) objMap.get(Constants.ITEM_NAME), (String) objMap.get(Constants.ITEM_VALUE)); } } searchLogBhv.insert(entity); } catch (final Exception e) { log.warn("Failed to read a search log: " + list, e); } } } catch (final IOException e) { log.warn("Failed to read a search log.", e); } }
From source file:agendavital.modelo.data.Noticia.java
public static TreeMap<LocalDate, ArrayList<Noticia>> buscar(String _parametro) throws ConexionBDIncorrecta, SQLException { final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); ArrayList<String> _tags = UtilidadesBusqueda.separarPalabras(_parametro); TreeMap<LocalDate, ArrayList<Noticia>> busqueda = null; try (Connection conexion = ConfigBD.conectar()) { busqueda = new TreeMap<>(); for (String _tag : _tags) { String tag = ConfigBD.String2Sql(_tag, true); String buscar = String.format("SELECT id_Noticia, fecha from noticias " + "WHERE id_noticia IN (SELECT id_noticia from momentos_noticias_etiquetas " + "WHERE id_etiqueta IN (SELECT id_etiqueta from etiquetas WHERE nombre LIKE %s)) " + "OR titulo LIKE %s " + "OR cuerpo LIKE %s " + "OR categoria LIKE %s " + "OR fecha LIKE %s; ", tag, tag, tag, tag, tag); ResultSet rs = conexion.createStatement().executeQuery(buscar); while (rs.next()) { LocalDate date = LocalDate.parse(rs.getString("fecha"), dateFormatter); Noticia insertarNoticia = new Noticia(rs.getInt("id_noticia")); if (busqueda.containsKey(date)) { boolean encontrado = false; for (int i = 0; i < busqueda.get(date).size() && !encontrado; i++) if (busqueda.get(date).get(i).getId() == insertarNoticia.getId()) encontrado = true; if (!encontrado) busqueda.get(date).add(insertarNoticia); } else { busqueda.put(date, new ArrayList<>()); busqueda.get(date).add(insertarNoticia); }//www . j av a 2 s . co m } } } catch (SQLException e) { e.printStackTrace(); } Iterator it = busqueda.keySet().iterator(); return busqueda; }
From source file:org.gradoop.flink.datagen.transactions.foodbroker.config.FoodBrokerConfig.java
/** * Loads the start date.// w ww . j a v a 2s . c o m * * @return long representation of the start date */ public LocalDate getStartDate() { String startDate; DateTimeFormatter formatter; LocalDate date = LocalDate.MIN; try { startDate = root.getJSONObject("Process").getString("startDate"); formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); date = LocalDate.parse(startDate, formatter); } catch (JSONException e) { e.printStackTrace(); } return date; }
From source file:org.cgiar.ccafs.marlo.action.center.summaries.ImpactSubmissionSummaryAction.java
/** * Get the main information of the report * /*w w w. j a v a 2s.com*/ * @return */ private TypedTableModel getMasterTableModel() { // Initialization of Model TypedTableModel model = new TypedTableModel( new String[] { "title", "current_date", "impact_submission", "imageUrl" }, new Class[] { String.class, String.class, String.class, String.class }); String title = ""; String currentDate = ""; String impactSubmission = ""; // Get title composed by center-area-program if (researchProgram.getResearchArea() != null) { title += researchProgram.getResearchArea().getName() + " - "; if (researchProgram.getComposedName() != null) { title += researchProgram.getName(); } } // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); currentDate = timezone.format(format) + this.getTimeZone(); // Get submission researchCycle = cycleService.getResearchCycleById(ImpactPathwayCyclesEnum.IMPACT_PATHWAY.getId()); // Filling submission List<CenterSubmission> submissions = new ArrayList<>(); for (CenterSubmission submission : researchProgram.getCenterSubmissions().stream() .filter(s -> s.getResearchCycle().getId() == researchCycle.getId() && s.getYear() == this.getActualPhase().getYear()) .collect(Collectors.toList())) { submissions.add(submission); } if (!submissions.isEmpty()) { if (submissions.size() > 1) { LOG.error("More than one submission was found, the report will retrieve the first one"); } CenterSubmission fisrtSubmission = submissions.get(0); String submissionDate = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm") .format(fisrtSubmission.getDateTime()); impactSubmission = "Submitted on " + submissionDate + " (" + fisrtSubmission.getResearchCycle().getName() + " cycle " + fisrtSubmission.getYear() + ")"; } else { impactSubmission = "Center Submission for " + researchCycle.getName() + " cycle " + this.getActualPhase().getYear() + ": <pending>"; } // Get CIAT imgage URL from repo String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png"; model.addRow(new Object[] { title, currentDate, impactSubmission, imageUrl }); return model; }
From source file:org.cgiar.ccafs.marlo.action.center.summaries.IPOutcomesSummaryAction.java
/** * Get the main information of the report * //from w w w . j a v a 2 s. c o m * @return */ private TypedTableModel getMasterTableModel() { // Initialization of Model TypedTableModel model = new TypedTableModel(new String[] { "currentDate", "center", "researchProgram" }, new Class[] { String.class, String.class, String.class }); String currentDate = ""; // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); currentDate = timezone.format(format) + this.getTimeZone(); // Get CIAT imgage URL from repo String center = this.getCenterSession(); model.addRow(new Object[] { currentDate, center, researchProgram.getName() }); return model; }
From source file:org.onosproject.drivers.ciena.waveserver.rest.CienaRestDevice.java
private long parseAlarmTime(String time) { /*/*from w w w.j a v a 2 s .c om*/ * expecting WaveServer time to be set to UTC. */ try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT); LocalDateTime localDateTime = LocalDateTime.parse(time, formatter); return localDateTime.atZone(ZoneId.of(UTC)).toInstant().toEpochMilli(); } catch (DateTimeParseException e2) { log.error("unable to parse time {}, using system time", time); return System.currentTimeMillis(); } }