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:currency.converter.openexchangerate.OpenExchangeCurrencyConverter.java

/**
 * Retrieves latest exchange rates from <a href="https://openexchangerates.org">OpenExchangeRates</a> by using
 * REST template. Retrieved rates are stored as search history for the specific user.
 * //www  .  jav a2s  .co  m
 * @param baseCurrency Base currency for exchange rates
 * @param amount Amount
 * @param dateOfRate Date for getting the historical exchange rate
 * 
 * @return {@link CurrencyRateModel}
 * 
 * @throws InvalidParameterException for invalid date
 */
public CurrencyRateModel getHistoricalCurrencyRates(String baseCurrency, double amount, LocalDate dateOfRate)
        throws InvalidParameterException {

    if (dateOfRate == null) {
        throw new InvalidParameterException("Date of rate is mandatory for historical currency rates!");
    }

    if (StringUtils.isNullOrEmpty(baseCurrency)) {
        baseCurrency = SupportedCurrencies.USD.name();
    }

    if (amount <= ZERO) {
        amount = MINIMUM_AMOUNT;
    }

    String apiKey = configuration.getOpenExchangeApiKey();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    StringBuilder builder = new StringBuilder();
    builder.append("https://openexchangerates.org/api/historical/").append(dateOfRate.format(formatter))
            .append(".json?app_id=").append(apiKey).append("&base=").append(baseCurrency);

    boolean isCommercialApi = configuration.isOpenExchangeCommercialLicense();
    if (isCommercialApi) {
        builder.append(getTargetCurrencies(baseCurrency));
    }

    logger.info("Historical rate API URL : " + builder.toString());

    RestTemplate restTemplate = new RestTemplate();
    CurrencyRateModel rates = restTemplate.getForObject(builder.toString(), CurrencyRateModel.class);

    multiplyAmount(rates, amount, baseCurrency);
    logger.info(rates.toString());

    // save currency history
    String userName = userService.getLoggedInUserName();
    saveExchangeRate(rates, baseCurrency, amount, dateOfRate, userName);

    return rates;
}

From source file:com.omertron.slackbot.model.sheets.SheetInfo.java

public String getFormattedDate(String format) {
    if (gameDate != null) {
        return gameDate.format(DateTimeFormatter.ofPattern(format));
    } else {/* ww  w  .java2s . com*/
        return null;
    }
}

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

@Override
public Set<BookingRule> createRule(BookingRule bookingRuleToCreate, boolean isSquashServiceUserCall)
        throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The rule manager has not been initialised");
    }/*from  www  .  ja va 2s  .  c o m*/

    lifecycleManager.throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall);

    // We retry the put of the rule 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(() -> {
        Set<BookingRule> bookingRules = null;

        // Check that non-recurring rule is not for a date in the past.
        if (!bookingRuleToCreate.getIsRecurring()) {
            if ((new SimpleDateFormat("yyyy-MM-dd")).parse(bookingRuleToCreate.getBooking().getDate())
                    .before(new SimpleDateFormat("yyyy-MM-dd")
                            .parse(getCurrentLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))) {
                logger.log(
                        "Cannot add non-recurring booking rule for a date in the past, so throwing a 'Booking rule creation failed' exception");
                throw new Exception("Booking rule creation failed");
            }
        }

        // We should POST or DELETE to the BookingRuleExclusion resource,
        // with a BookingRule, and an exclusion date. This will call through
        // to the addBookingRuleExclusion or deleteBookingRuleExclusion
        // methods on this manager.
        logger.log("About to create booking rule in simpledb: " + bookingRuleToCreate);
        ImmutablePair<Optional<Integer>, Set<BookingRule>> versionedBookingRules = getVersionedBookingRules();
        bookingRules = versionedBookingRules.right;

        // Check that the rule we're creating does not clash with an
        // existing rule.
        if (doesRuleClash(bookingRuleToCreate, bookingRules)) {
            logger.log(
                    "Cannot create rule as it clashes with existing rule, so throwing a 'Booking rule creation failed - rule would clash' exception");
            throw new Exception("Booking rule creation failed - rule would clash");
        }

        logger.log("The new rule does not clash with existing rules - so proceeding to create rule");

        String attributeName = getAttributeNameFromBookingRule(bookingRuleToCreate);
        String attributeValue = "";
        if (bookingRuleToCreate.getDatesToExclude().length > 0) {
            attributeValue = StringUtils.join(bookingRuleToCreate.getDatesToExclude(), ",");
        }
        logger.log("ItemName: " + ruleItemName);
        logger.log("AttributeName: " + attributeName);
        logger.log("AttributeValue: " + attributeValue);
        ReplaceableAttribute bookingRuleAttribute = new ReplaceableAttribute();
        bookingRuleAttribute.setName(attributeName);
        bookingRuleAttribute.setValue(attributeValue);

        optimisticPersister.put(ruleItemName, versionedBookingRules.left, bookingRuleAttribute);
        bookingRules.add(bookingRuleToCreate);
        return bookingRules;
    }, Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:svc.managers.SMSManagerTest.java

@Test
public void citationDetailMessageGetsGenerated() throws TwiMLException, ParseException {
    setStageInSession(session, SMS_STAGE.VIEW_CITATION);
    session.setAttribute("dob", "06/01/1963");
    session.setAttribute("license_number", "F917801962");

    Citation citation = new Citation();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    citation.citation_date = LocalDate.parse("02/03/1990", formatter);
    citation.citation_number = "a1234";
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
    citation.court_dateTime = LocalDateTime.parse("11/20/2015 04:22", formatter2);
    citation.court_id = new HashableEntity<Court>(Court.class, 1L);
    List<Citation> citations = new ArrayList<Citation>();
    citations.add(citation);//from  w ww.  j  a  v  a  2s  .  c o  m

    Court court = new Court();
    court.address = "1 Anystreet";
    court.city = "myCity";
    court.state = "myState";
    court.zip = "myZip";

    Violation violation = new Violation();
    violation.violation_number = "Y246";
    violation.violation_description = "myDescription";
    violation.status = VIOLATION_STATUS.CONT_FOR_PAYMENT;
    violation.fine_amount = new BigDecimal(200.54);
    violation.court_cost = new BigDecimal(22.34);
    List<Violation> violations = new ArrayList<Violation>();
    violations.add(violation);

    when(citationManagerMock.findCitations((CitationSearchCriteria) notNull())).thenReturn(citations);
    when(courtManagerMock.getCourtById(citations.get(0).court_id.getValue())).thenReturn(court);
    when(violationManagerMock.getViolationsByCitationNumber(anyString())).thenReturn(violations);
    TwimlMessageRequest twimlMessageRequest = new TwimlMessageRequest();
    twimlMessageRequest.setBody("1");
    String message = "Ticket Date: 02/03/1990\nCourt Date: 11/20/2015\nCourt Time: 04:22 AM\nTicket #: "
            + citation.citation_number;
    message += "\nCourt Address: " + court.address + " " + court.city + ", " + court.state + " " + court.zip;
    message += "\nViolation #: " + violation.violation_number + "\nViolation: "
            + violation.violation_description;
    message += "\nStatus: " + violation.status.toString();
    message += "\nFine Amount: $" + violation.fine_amount;
    message += "\nCourt Costs: $" + violation.court_cost;
    message += "\nReply with '1' to view another ticket";
    message += "\nReply with '2' for payment options";
    message += "\nReply with '3' to receive text message reminders about this court date";
    message += "\nReply with '4' to remove text message reminders about this court date";
    MessagingResponse twimlResponse = manager.getTwimlResponse(twimlMessageRequest, requestMock, session);
    assertEquals(createTwimlResponse(message).toXml(), twimlResponse.toXml());
}

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

@Override
public String execute() throws Exception {

    final ByteArrayOutputStream os = new ByteArrayOutputStream();

    final Resource reportResource = resourceManager
            .createDirectly(this.getClass().getResource("/pentaho/center/Capdev.prpt"), MasterReport.class);

    final MasterReport masterReport = (MasterReport) reportResource.getResource();
    String center = this.getCurrentCrp().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";
    }/*from  w w w.java  2s . c o  m*/
    String currentDate = 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, currentDate);
    sdf.addTable(masterQueryName, model);
    masterReport.setDataFactory(cdf);

    // Get details band
    final ItemBand masteritemBand = masterReport.getItemBand();
    // Create new empty subreport hash map
    final 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

    // Subreport list of capdev
    this.fillSubreport((SubReport) hm.get("capdev_interventions"), "capdev_interventions");
    this.fillSubreport((SubReport) hm.get("capdev_participants"), "capdev_participants");
    this.fillSubreport((SubReport) hm.get("individual_types"), "individual_types");
    this.fillSubreport((SubReport) hm.get("groupTypes"), "groupTypes");
    this.fillSubreport((SubReport) hm.get("disciplines"), "disciplines");
    this.fillSubreport((SubReport) hm.get("target_groups"), "target_groups");
    this.fillSubreport((SubReport) hm.get("programs"), "programs");
    this.fillSubreport((SubReport) hm.get("crp"), "crp");
    this.fillSubreport((SubReport) hm.get("capdevSummary"), "capdevSummary");
    this.fillSubreport((SubReport) hm.get("citizenship"), "citizenship");
    this.fillSubreport((SubReport) hm.get("funding_type"), "funding_type");
    this.fillSubreport((SubReport) hm.get("institution"), "institution");
    this.fillSubreport((SubReport) hm.get("institutions_type"), "institutions_type");

    ExcelReportUtil.createXLSX(masterReport, os);
    bytesXLS = os.toByteArray();
    os.close();

    return SUCCESS;
}

From source file:com.match_tracker.twitter.TwitterSearch.java

public String constructSearchQuery(String queryString, ZonedDateTime startTime, ZonedDateTime endTime) {
    DateTimeFormatter ISO_Datetime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX");
    return queryString + " " + "posted:" + startTime.format(ISO_Datetime) + "," + endTime.format(ISO_Datetime);
}

From source file:controller.SignUpController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  ww  . java  2 s  . c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    CreditDao creditDao = new CreditDaoImpl();

    try {

        boolean creditExist = false;

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();
        HttpSession session = request.getSession(false);
        User user = new User();
        Credit credit = new Credit();
        UserDao userDaoImpl = new UserDaoImpl();
        ArrayList<String> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());

                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    credit.setNumber(item.getString());
                    if (creditDao.checkCredit(credit)) {//credit number is exist is 
                        if (!(userDaoImpl.isCreditNumberAssigned(credit))) {
                            creditExist = true;
                            System.out.println("creditExist = true;");
                        } else {

                            creditExist = false;
                            System.out.println("creditExist = falsefalse;");

                        }
                    } else {
                        creditExist = false;

                        System.out.println("creditExist=false;");

                    }
                    break;

                default:
                    newInterests.add(item.getString());
                    System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }

        // check if user exist in Db 
        if (creditExist) {
            user.setInterests(newInterests);
            UserDaoImpl userDao = new UserDaoImpl();

            //
            userDao.signUp(user);
            session.setAttribute("user", user);

            System.out.println(user.getInterests());
            System.out.println(user.getImage());

            response.sendRedirect("index.jsp");
        } else {

            response.sendRedirect("sign_up.jsp");
            System.out.println("user didnt saved");

        }
    } catch (FileUploadException ex) {
        Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:fi.helsinki.opintoni.service.CalendarService.java

private DateTime calDateTimeAsUtc(LocalDateTime localDateTime) {
    String utc = localDateTime.format(DateTimeFormatter.ofPattern(DateFormatter.UTC_TIME_FORMAT));
    try {/*  w  w w  .j a  v  a  2s .  c o  m*/
        return new DateTime(utc, DateFormatter.UTC_TIME_FORMAT, true);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.straylightlabs.archivo.net.MindCommandRecordingSearch.java

private LocalDateTime parseUTCDateTime(String utcDateTime) {
    ZonedDateTime utc = ZonedDateTime.parse(utcDateTime + " +0000",
            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss ZZ"));
    return utc.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}

From source file:agendavital.modelo.data.Noticia.java

/**
 * Funcion coloreadora del calendario/*w  ww  .j  a v  a2 s.  co m*/
 *
 * @return
 * @throws agendavital.modelo.excepciones.ConexionBDIncorrecta
 *
 */
public static TreeMap<LocalDate, String> getNoticiasFecha() throws ConexionBDIncorrecta {
    ResultSet rs = null;
    TreeMap<LocalDate, String> noticias = new TreeMap<>();
    try (Connection conexion = ConfigBD.conectar()) {
        String consulta = String.format("SELECT categoria, fecha from Noticias;");
        rs = conexion.createStatement().executeQuery(consulta);
        while (rs.next()) {
            String categoria = rs.getString("categoria");
            String fecha = rs.getString("fecha");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
            LocalDate date = LocalDate.parse(fecha, formatter);
            noticias.put(date, categoria);
        }
    } catch (SQLException e) {
        throw new ConexionBDIncorrecta();
    }
    return noticias;
}