Example usage for java.time.format DateTimeFormatter ofPattern

List of usage examples for java.time.format DateTimeFormatter ofPattern

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter ofPattern.

Prototype

public static DateTimeFormatter ofPattern(String pattern) 

Source Link

Document

Creates a formatter using the specified pattern.

Usage

From source file:alfio.manager.CheckInManager.java

private TicketAndCheckInResult extractStatus(Optional<Event> maybeEvent, Optional<Ticket> maybeTicket,
        String ticketIdentifier, Optional<String> ticketCode) {

    if (!maybeEvent.isPresent()) {
        return new TicketAndCheckInResult(null, new DefaultCheckInResult(EVENT_NOT_FOUND, "Event not found"));
    }/*from   w w w .jav  a 2 s . c o m*/

    if (!maybeTicket.isPresent()) {
        return new TicketAndCheckInResult(null, new DefaultCheckInResult(TICKET_NOT_FOUND,
                "Ticket with uuid " + ticketIdentifier + " not found"));
    }

    if (!ticketCode.filter(StringUtils::isNotEmpty).isPresent()) {
        return new TicketAndCheckInResult(null,
                new DefaultCheckInResult(EMPTY_TICKET_CODE, "Missing ticket code"));
    }

    Ticket ticket = maybeTicket.get();
    Event event = maybeEvent.get();
    String code = ticketCode.get();

    TicketCategory tc = ticketCategoryRepository.getById(ticket.getCategoryId());

    ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    if (!tc.hasValidCheckIn(now, event.getZoneId())) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm");
        String from = tc.getValidCheckInFrom() == null ? ".."
                : formatter.format(tc.getValidCheckInFrom(event.getZoneId()));
        String to = tc.getValidCheckInTo() == null ? ".."
                : formatter.format(tc.getValidCheckInTo(event.getZoneId()));
        String formattedNow = formatter.format(now);
        return new TicketAndCheckInResult(ticket,
                new DefaultCheckInResult(INVALID_TICKET_CATEGORY_CHECK_IN_DATE, String.format(
                        "Invalid check-in date: valid range for category %s is from %s to %s, current time is: %s",
                        tc.getName(), from, to, formattedNow)));
    }

    log.trace("scanned code is {}", code);
    log.trace("true code    is {}", ticket.ticketCode(event.getPrivateKey()));

    if (!code.equals(ticket.ticketCode(event.getPrivateKey()))) {
        return new TicketAndCheckInResult(null,
                new DefaultCheckInResult(INVALID_TICKET_CODE, "Ticket qr code does not match"));
    }

    final TicketStatus ticketStatus = ticket.getStatus();

    if (ticketStatus == TicketStatus.TO_BE_PAID) {
        return new TicketAndCheckInResult(ticket, new OnSitePaymentResult(MUST_PAY, "Must pay for ticket",
                MonetaryUtil.centsToUnit(ticket.getFinalPriceCts()), event.getCurrency()));
    }

    if (ticketStatus == TicketStatus.CHECKED_IN) {
        return new TicketAndCheckInResult(ticket,
                new DefaultCheckInResult(ALREADY_CHECK_IN, "Error: already checked in"));
    }

    if (ticket.getStatus() != TicketStatus.ACQUIRED) {
        return new TicketAndCheckInResult(ticket, new DefaultCheckInResult(INVALID_TICKET_STATE,
                "Invalid ticket state, expected ACQUIRED state, received " + ticket.getStatus()));
    }

    return new TicketAndCheckInResult(ticket,
            new DefaultCheckInResult(OK_READY_TO_BE_CHECKED_IN, "Ready to be checked in"));
}

From source file:io.stallion.utils.GeneralUtils.java

@Deprecated
public static String formatLocalDateFromZonedDate(ZonedDateTime date, String formatPattern) {
    if (date == null) {
        return "";
    }//from   w  w  w .j  a va  2s. c  o m

    ZonedDateTime localDt = date.withZoneSameInstant(Context.getSettings().getTimeZoneId());

    DateTimeFormatter formatter;
    if (StringUtils.isEmpty(formatPattern)) {
        formatter = DEFAULT_FORMAT;
    } else if ("iso".equals(formatPattern.toLowerCase())) {
        formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    } else {
        formatter = DateTimeFormatter.ofPattern(formatPattern);
    }
    return localDt.format(formatter);
}

From source file:fi.csc.emrex.smp.ThymeController.java

private String generatePersonalLogLine(HttpServletRequest httpRequest, Person person, String source)
        throws Exception {
    String personalLogLine = source + "\t" + person.getFullName();
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDateTime startTime = (LocalDateTime) context.getSession().getAttribute("sessionStartTime");
    if (startTime == null) {
        startTime = LocalDateTime.now();
    }//  w ww  .j  a  va2  s  .com
    personalLogLine += "\t" + startTime.format(dateFormatter);

    String url = httpRequest.getHeader("Referer");
    String NCPDomain = "";
    if (url != null) {
        URI uri = new URI(url);
        NCPDomain = uri.getHost();
    }

    personalLogLine += "\t" + NCPDomain;
    personalLogLine += "\t" + httpRequest.getParameter("returnCode");
    return personalLogLine;
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = true)// w ww  .  j  a  va  2 s.co m
public List<ComboItemDto> getMoisOuvertCantine() throws TechnicalException {
    final Activite activite = this.getCantineActivite();
    final List<Ouverture> ouvertures = this.ouvertureRepository.findByActivite(activite);
    final Set<YearMonth> moisActs = new HashSet<>();
    moisActs.add(YearMonth.now());
    ouvertures.sort((o1, o2) -> o1.getDate().compareTo(o2.getDate()));
    ouvertures.forEach(o -> {
        moisActs.add(YearMonth.from(((java.sql.Date) o.getDate()).toLocalDate()));
    });
    final List<ComboItemDto> comboMois = new ArrayList<>();
    moisActs.forEach(ma -> {
        final Integer id = Integer
                .valueOf(ma.format(DateTimeFormatter.ofPattern(GeDateUtils.DATE_FORMAT_YYYYMM)));
        final String libelle = ma.format(DateTimeFormatter.ofPattern(GeDateUtils.DATE_FORMAT_ANNEE_MOIS_FULL));
        comboMois.add(new ComboItemDto(id, libelle));
    });
    comboMois.sort((c1, c2) -> c1.getId().compareTo(c2.getId()));
    return comboMois;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.postgres.PostgresCDCSource.java

private Optional<List<ConfigIssue>> validatePostgresCDCConfigBean(PostgresCDCConfigBean configBean) {
    List<ConfigIssue> issues = new ArrayList<>();

    if (configBean.minVersion == null) {
        this.getConfigBean().minVersion = PgVersionValues.NINEFOUR;
    }//from   w w  w .  jav a  2 s.c o  m

    if (configBean.decoderValue == null) {
        this.getConfigBean().decoderValue = DecoderValues.WAL2JSON;
    }

    if (configBean.replicationType == null) {
        this.getConfigBean().replicationType = "database";
    }

    switch (configBean.startValue) {

    case LSN:
        //Validate startLSN
        if (configBean.startLSN == null || configBean.startLSN.isEmpty()
                || (LogSequenceNumber.valueOf(configBean.startLSN).equals(LogSequenceNumber.INVALID_LSN))) {
            issues.add(getContext().createConfigIssue(Groups.CDC.name(),
                    configBean.startLSN + " is invalid LSN.", JdbcErrors.JDBC_408));
            this.setOffset("0/0"); //Valid "non-LSN" LSN or set to latest.
        } else {
            this.setOffset(configBean.startLSN);
        }
        break;

    case DATE:
        //Validate startDate
        zoneId = ZoneId.of(configBean.dbTimeZone);
        dateTimeColumnHandler = new DateTimeColumnHandler(zoneId);
        try {
            startDate = LocalDateTime.parse(configBean.startDate,
                    DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss"));
            /* Valid offset that should be as early as possible to get the most number of WAL
            records available for the date filter to process. */
            this.setOffset(LogSequenceNumber.valueOf(1L).asString());
        } catch (DateTimeParseException e) {
            issues.add(getContext().createConfigIssue(Groups.CDC.name(),
                    configBean.startDate + " doesn't parse as DateTime.", JdbcErrors.JDBC_408));
        }
        break;

    case LATEST:
        this.setOffset("0/0"); //Valid "non-LSN" LSN or set to latest.
        break;

    default:
        //Should never happen
        issues.add(getContext().createConfigIssue(Groups.CDC.name(), configBean.startValue.getLabel(),
                JdbcErrors.JDBC_408));
    }

    return Optional.ofNullable(issues);
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

private String indexRowWithDateAndType(JsonEvent event) {

    Optional<String> formattedType = type.format(event);
    if (!formattedType.isPresent()) {
        throw new IllegalStateException(
                "Issue with type, could not extract field from event " + type.original());
    }//from   w  w  w  . j a va2s. c o  m

    Optional<String> formattedIndex = index.format(event);
    if (!formattedIndex.isPresent()) {
        throw new IllegalStateException(
                "Issue with index, could not extract field from event: " + index.original());
    }

    Optional<String> formattedDocumentId = Optional.empty();
    if (documentId.isPresent()) {
        formattedDocumentId = documentId.get().format(event);
        if (!formattedDocumentId.isPresent()) {
            throw new IllegalStateException(
                    "Issue with index, could not extract field from event: " + index.original());
        }
    }

    ObjectNode objectNode = OBJECT_MAPPER.createObjectNode();
    ObjectNode data = OBJECT_MAPPER.createObjectNode();

    // Prepare for adding day to index for each event
    if (indexIsPrefix) {
        LocalDate indexDate;
        // TODO: Not sure how to handle this... what should be the behaviour if the specified timestamp field
        //       does not exist
        if (event.has(this.timestampField)) {
            indexDate = LocalDate.parse(event.valueAsString(this.timestampField).substring(0, 10),
                    DateTimeFormatter.ISO_DATE);
        } else {
            indexDate = LocalDate.now();
        }
        data.put("_index", formattedIndex.get() + indexDate.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")));
    } else {
        data.put("_index", formattedIndex.get());
    }
    data.put("_type", formattedType.get());

    if (formattedDocumentId.isPresent()) {
        data.put("_id", formattedDocumentId.get());
    }
    objectNode.set("index", data);

    return objectNode.toString();
}

From source file:squash.booking.lambdas.core.BookingManager.java

@Override
public void deleteYesterdaysBookings(boolean isSquashServiceUserCall) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The booking manager has not been initialised");
    }//from w  w w .j a v  a 2 s.c o m

    getLifecycleManager().throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall);

    try {
        // Remove the previous day's bookings from database
        String yesterdaysDate = getCurrentLocalDate().minusDays(1)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        logger.log("About to remove bookings from database for yesterday, i.e. : " + yesterdaysDate);
        getOptimisticPersister().deleteAllAttributes(yesterdaysDate);
        logger.log("Removed yesterday's bookings from database");
    } catch (Exception exception) {
        logger.log("Exception caught while deleting yesterday's bookings - so notifying sns topic");
        getSNSClient().publish(adminSnsTopicArn,
                "Apologies - but there was an error deleting yesterday's bookings from the database. Please check that the database is not accumulating stale data. The error message was: "
                        + exception.getMessage(),
                "Sqawsh bookings for yesterday failed to delete");
        // Rethrow
        throw exception;
    }
}

From source file:ua.com.ecotep.debtprevention.VnaklController.java

@Override
public void initialize(URL url, ResourceBundle rb) {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

    dateFieldFormatter = new TextFormatter(new LocalDateStringConverter(dateTimeFormatter, null));
    dateField.setTextFormatter(dateFieldFormatter);

    dateMaxFieldFormatter = new TextFormatter(new LocalDateStringConverter(dateTimeFormatter, null));
    dateMaxField.setTextFormatter(dateMaxFieldFormatter);

    TableColumn numCol = new TableColumn(".");
    numCol.setPrefWidth(100);/* ww  w .j a va 2s .c om*/
    numCol.setCellValueFactory(new PropertyValueFactory<DebPrevDetailBean, String>("num"));
    invTable.getColumns().add(numCol);

    TableColumn dateCol = new TableColumn("");
    dateCol.setPrefWidth(90);
    dateCol.setCellValueFactory(new PropertyValueFactory<DebPrevDetailBean, String>("date"));
    dateCol.setCellFactory(CellDateBox.forTableColumn(dateCol, CellDateBox.DATE_NORMAL_VIEW));
    invTable.getColumns().add(dateCol);

    TableColumn sumCol = new TableColumn("");
    sumCol.setPrefWidth(90);
    sumCol.setCellValueFactory(new PropertyValueFactory<DebPrevDetailBean, String>("sum"));
    sumCol.setCellFactory(CellMoneyBox.forTableColumn(sumCol, " ", 2));
    invTable.getColumns().add(sumCol);
    invTable.autosize();

    invTable.getItems().addListener(new ListChangeListener<DebPrevDetailBean>() {
        @Override
        public void onChanged(ListChangeListener.Change<? extends DebPrevDetailBean> c) {
            double sumDpm = 0;
            for (DebPrevDetailBean bean : c.getList()) {
                sumDpm += bean.getSum();
            }
            sumField.setText(String.format("%.2f ", sumDpm));
            if (sumDpm > 0) {
                saveButon.setDisable(false);
            } else {
                saveButon.setDisable(true);
            }
        }
    });

    TableColumn numVCol = new TableColumn(".");
    numVCol.setPrefWidth(100);
    numVCol.setCellValueFactory(new PropertyValueFactory<DebPrevDetailBean, String>("num"));
    vnaklTable.getColumns().add(numVCol);

    TableColumn dateVCol = new TableColumn("");
    dateVCol.setPrefWidth(90);
    dateVCol.setCellValueFactory(new PropertyValueFactory<DebPrevDetailBean, String>("date"));
    dateVCol.setCellFactory(CellDateBox.forTableColumn(dateVCol, CellDateBox.DATE_NORMAL_VIEW));
    vnaklTable.getColumns().add(dateVCol);

    TableColumn sumVCol = new TableColumn("");
    sumVCol.setPrefWidth(90);
    sumVCol.setCellValueFactory(new PropertyValueFactory<DebPrevDetailBean, String>("sum"));
    sumVCol.setCellFactory(CellMoneyBox.forTableColumn(sumVCol, " ", 2));
    vnaklTable.getColumns().add(sumVCol);
    vnaklTable.autosize();

    TextMaxLengthFieldInstaller mlControl = new TextMaxLengthFieldInstaller();
    mlControl.install(clientField, 150);

    try {

        dateFieldFormatter.setValue(currentDate);
        dateMaxFieldFormatter.setValue(currentDate);
    } catch (Exception ex) {
        Logger.getLogger(FilterController.class.getName()).log(Level.SEVERE, null, ex);
        AlertDialog.showSimpleMessage(" ?    !",
                AlertDialog.ICON_ERROR, parentInterface.getCurrentWindow());
    }

}

From source file:org.cgiar.ccafs.marlo.action.summaries.StudiesSummaryAction.java

@Override
public String execute() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {//from w ww .  j av  a  2 s . c  o  m
        Resource reportResource;
        if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/CaseStudiesExcel.prpt"), MasterReport.class);
        } else {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/StudiesPDF.prpt"), MasterReport.class);
        }
        MasterReport masterReport = (MasterReport) reportResource.getResource();
        String center = this.getLoggedCrp().getAcronym();

        // Get datetime
        ZonedDateTime timezone = ZonedDateTime.now();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
        String zone = timezone.getOffset() + "";
        if (zone.equals("Z")) {
            zone = "+0";
        }
        String date = timezone.format(format) + "(GMT" + zone + ")";

        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear()));
        sdf.addTable(masterQueryName, model);
        masterReport.setDataFactory(cdf);
        // Set i8n for pentaho
        masterReport = this.addi8nParameters(masterReport);
        // Get details band
        ItemBand masteritemBand = masterReport.getItemBand();
        // Create new empty subreport hash map
        HashMap<String, Element> hm = new HashMap<String, Element>();
        // method to get all the subreports in the prpt and store in the HashMap
        this.getAllSubreports(hm, masteritemBand);
        // Uncomment to see which Subreports are detecting the method getAllSubreports
        // System.out.println("Pentaho SubReports: " + hm);

        this.fillSubreport((SubReport) hm.get("case_studies"), "case_studies");

        if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
            ExcelReportUtil.createXLSX(masterReport, os);
            bytesXLSX = os.toByteArray();
        } else {
            PdfReportUtil.createPDF(masterReport, os);
            bytesPDF = os.toByteArray();
        }
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating CaseStudy" + this.getSelectedFormat() + ": " + e.getMessage());
        throw e;
    }
    // Calculate time of generation
    long stopTime = System.currentTimeMillis();
    stopTime = stopTime - startTime;
    LOG.info("Downloaded successfully: " + this.getFileName() + ". User: "
            + this.getCurrentUser().getComposedCompleteName() + ". CRP: " + this.getLoggedCrp().getAcronym()
            + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}

From source file:org.cgiar.ccafs.marlo.action.summaries.StudySummaryAction.java

@Override
public String execute() throws Exception {
    if (projectExpectedStudyID == null
            || projectExpectedStudyManager.getProjectExpectedStudyById(projectExpectedStudyID) == null
            || projectExpectedStudyManager.getProjectExpectedStudyById(projectExpectedStudyID)
                    .getProjectExpectedStudyInfo(this.getSelectedPhase()) == null) {
        LOG.error("ProjectExpectedStudy " + projectExpectedStudyID + " Not found");
        return NOT_FOUND;
    } else {/*w  w w  . j  av a2  s  .  c om*/
        projectExpectedStudyInfo = projectExpectedStudyManager
                .getProjectExpectedStudyById(projectExpectedStudyID)
                .getProjectExpectedStudyInfo(this.getSelectedPhase());
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        Resource reportResource = resourceManager
                .createDirectly(this.getClass().getResource("/pentaho/crp/StudyPDF.prpt"), MasterReport.class);
        MasterReport masterReport = (MasterReport) reportResource.getResource();
        String center = this.getLoggedCrp().getAcronym();

        // Get datetime
        ZonedDateTime timezone = ZonedDateTime.now();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
        String zone = timezone.getOffset() + "";
        if (zone.equals("Z")) {
            zone = "+0";
        }
        String date = timezone.format(format) + "(GMT" + zone + ")";

        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear()));
        sdf.addTable(masterQueryName, model);
        masterReport.setDataFactory(cdf);
        // Set i8n for pentaho
        masterReport = this.addi8nParameters(masterReport);
        // Get details band
        ItemBand masteritemBand = masterReport.getItemBand();
        // Create new empty subreport hash map
        HashMap<String, Element> hm = new HashMap<String, Element>();
        // method to get all the subreports in the prpt and store in the HashMap
        this.getAllSubreports(hm, masteritemBand);
        // Uncomment to see which Subreports are detecting the method getAllSubreports
        // System.out.println("Pentaho SubReports: " + hm);

        this.fillSubreport((SubReport) hm.get("study"), "study");

        PdfReportUtil.createPDF(masterReport, os);
        bytesPDF = os.toByteArray();
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating Study Summary: " + e.getMessage());
        throw e;
    }
    // Calculate time of generation
    long stopTime = System.currentTimeMillis();
    stopTime = stopTime - startTime;
    LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getDownloadByUser()
            + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}