Example usage for java.time LocalDate parse

List of usage examples for java.time LocalDate parse

Introduction

In this page you can find the example usage for java.time LocalDate parse.

Prototype

public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of LocalDate from a text string using a specific formatter.

Usage

From source file:org.flockdata.transform.ExpressionHelper.java

public static Long parseDate(ColumnDefinition colDef, String value) {
    if (value == null || value.equals(""))
        return null;
    if (colDef.isDateEpoc()) {
        return Long.parseLong(value) * 1000;
    }/*from   w  w  w  . j  av a 2 s.  co m*/

    if (colDef.getDateFormat() == null || colDef.getDateFormat().equalsIgnoreCase("automatic")) {
        try {
            return Date.parse(value);
        } catch (IllegalArgumentException e) {
            // Try other formats
        }
    }
    if (colDef.getDateFormat() != null && colDef.getDateFormat().equalsIgnoreCase("timestamp")) {
        try {
            return Timestamp.valueOf(value).getTime();
        } catch (IllegalArgumentException e) {
            // attempt other conversions
        }
    }

    if (NumberUtils.isDigits(value)) // plain old java millis
        return Long.parseLong(value);

    // Custom Date formats
    String tz = colDef.getTimeZone();
    if (tz == null)
        tz = TimeZone.getDefault().getID();

    try {

        // Try first as DateTime
        return new SimpleDateFormat(colDef.getDateFormat()).parse(value).getTime();
    } catch (DateTimeParseException | IllegalArgumentException | ParseException e) {
        // Just a plain date
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(colDef.getDateFormat(), Locale.ENGLISH);
        LocalDate date = LocalDate.parse(value, pattern);
        return new DateTime(date.toString(), DateTimeZone.forID(tz)).getMillis();
    }
}

From source file:com.romeikat.datamessie.core.base.ui.page.AbstractDocumentsFilterPage.java

private LocalDate parseLocalDate(final StringValue stringValue) {
    final LocalDate today = LocalDate.now();
    // No date corresponds to today
    if (stringValue == null) {
        return today;
    }//from w ww  . j  ava  2s .  com
    // 0 corresponds to no date
    if (stringValue.toString().equals("0")) {
        return null;
    }
    // Negative numbers correspond to number of days from today in the past
    try {
        final int numberOfDays = Integer.parseInt(stringValue.toString());
        if (numberOfDays < 0) {
            final LocalDate localDate = today.plusDays(numberOfDays);
            return localDate;
        }
    } catch (final NumberFormatException e) {
    }
    // Date pattern
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    try {
        final LocalDate localDate = LocalDate.parse(stringValue.toString(), dateFormatter);
        return localDate;
    } catch (final IllegalArgumentException ex) {
    }
    // Ohterwise, use today
    return today;
}

From source file:de.steilerdev.myVerein.server.controller.admin.UserManagementController.java

/**
 * If a modification on a division needs to be stored durable, this function is invoked by POSTing the parameters to the URI /api/admin/user.
 * @param firstName The first name of the user.
 * @param lastName The last name of the user.
 * @param email The email (unique identifier) of the user.
 * @param birthday The birthday of the user (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param password The initial password of a new user (Only allowed for a new user).
 * @param gender The gender of the user.
 * @param street The street of the user's address.
 * @param streetNumber The street number of the user's address.
 * @param zip The zip code of the user's address.
 * @param city The city of the user's address.
 * @param country The country of the user.
 * @param activeMemberSince The date, when the user became an active member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param passiveMemberSince The date, when the user became a passive member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param resignationDate The date, when the user resigned (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param iban The IBAN of the user's bank account.
 * @param bic The BIC of the user's bank account.
 * @param divisions A comma seperated list of divisions, the user is part of.
 * @param userFlag If it is a new user, the user flag is "true", otherwise it is holding the identifier (email) of the user, in case it changed.
 * @param parameters The complete map of all parameters, containing the custom user fields.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *//*from   w  w  w . j a va  2s .c  om*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveUser(@RequestParam String firstName, @RequestParam String lastName,
        @RequestParam String email, @RequestParam String birthday, @RequestParam String password,
        @RequestParam(required = false) String gender, @RequestParam String street,
        @RequestParam String streetNumber, @RequestParam String zip, @RequestParam String city,
        @RequestParam String country, @RequestParam String activeMemberSince,
        @RequestParam String passiveMemberSince, @RequestParam String resignationDate,
        @RequestParam String iban, @RequestParam String bic, @RequestParam String divisions,
        @RequestParam String userFlag, @RequestParam Map<String, String> parameters,
        @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Starting to save a user.");
    User userObject;

    logger.debug("[" + currentUser + "] Loading user");

    if (email.isEmpty() || userFlag.isEmpty()) {
        logger.warn("[" + currentUser + "] The email/user flag can not be empty");
        return new ResponseEntity<>("The email can not be empty", HttpStatus.BAD_REQUEST);
    } else if (userFlag.equals("true")) {
        logger.info("[" + currentUser + "] A new user is created using the email " + email);
        if (userRepository.findByEmail(email) == null) {
            userObject = new User();
            if (password.isEmpty()) {
                logger.warn(
                        "[" + currentUser + "] The password of the new user " + email + " can not be empty");
                return new ResponseEntity<>("The password can not be empty", HttpStatus.BAD_REQUEST);
            } else {
                userObject.setPassword(password);
            }
        } else {
            logger.warn("[" + currentUser + "] A user with the given email " + email + " already exists");
            return new ResponseEntity<>("A user with the given email already exists.", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.info("[" + currentUser + "] An existing user " + userFlag + " is modified");
        if ((userObject = userRepository.findByEmail(userFlag)) == null) {
            logger.warn("[{}] Unable to find existing user object", currentUser);
            return new ResponseEntity<>("Unable to retrieve the user", HttpStatus.BAD_REQUEST);
        } else if (!userObject.getEmail().equals(email) && userRepository.findByEmail(email) != null) {
            logger.warn("[{}] The new email {} is already taken", currentUser, email);
            return new ResponseEntity<>("The new email is already taken", HttpStatus.BAD_REQUEST);
        }
    }

    logger.debug("[" + currentUser + "] Checking permissions");

    if (!currentUser.isAllowedToAdministrate(userObject, divisionRepository)) {
        logger.warn("[" + currentUser + "] The user is not allowed to save the user");
        return new ResponseEntity<>("You are not allowed to perform these changes.", HttpStatus.FORBIDDEN);
    }

    logger.debug("[" + currentUser + "] Parsing parameters and updating user");

    if (firstName.isEmpty() || lastName.isEmpty()) {
        logger.warn("[" + currentUser + "] Required parameter missing");
        return new ResponseEntity<>("Required parameter missing", HttpStatus.BAD_REQUEST);
    }
    userObject.setFirstName(firstName);
    userObject.setLastName(lastName);
    userObject.setEmail(email);

    if (!birthday.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing birthday for " + userObject.getEmail());
        try {
            userObject.setBirthday(LocalDate.parse(birthday, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + birthday + ")");
            return new ResponseEntity<>("Wrong date format within birthday field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing birthday field for " + userObject.getEmail());
        userObject.setBirthday(null);
    }

    if (gender != null && !gender.isEmpty() && !gender.equals("default")) {
        logger.debug("[" + currentUser + "] Parsing gender for " + userObject.getEmail());
        try {
            userObject.setGender(User.Gender.valueOf(gender));
        } catch (IllegalArgumentException e) {
            logger.warn("[" + currentUser + "] Unable to parse gender: " + e.getMessage());
            return new ResponseEntity<>("Unable to parse gender", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing gender field for " + userObject.getEmail());
        userObject.setGender(null);
    }

    userObject.setStreet(street);
    userObject.setStreetNumber(streetNumber);
    userObject.setZipCode(zip);
    userObject.setCity(city);
    userObject.setCountry(country);

    if (!activeMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing active member field for " + userObject.getEmail());
        try {
            userObject
                    .setActiveSince(LocalDate.parse(activeMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + activeMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within active member field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing active member field for " + userObject.getEmail());
        userObject.setActiveSince(null);
    }

    if (!passiveMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing passive member field for " + userObject.getEmail());
        try {
            userObject.setPassiveSince(
                    LocalDate.parse(passiveMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + passiveMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within passive member field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing passive member field for " + userObject.getEmail());
        userObject.setPassiveSince(null);
    }

    if (!resignationDate.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing resignation date field for " + userObject.getEmail());
        try {
            userObject.setResignationDate(
                    LocalDate.parse(resignationDate, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + resignationDate + ")");
            return new ResponseEntity<>("Wrong date format within resignation date field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing resignation date field for " + userObject.getEmail());
        userObject.setResignationDate(null);
    }

    userObject.setIban(iban);
    userObject.setBic(bic);

    if (!divisions.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing divisions for " + userObject.getEmail());
        String[] divArray = divisions.split(",");
        List<Division> divisionList = new ArrayList<>();
        for (String division : divArray) {
            Division div = divisionRepository.findByName(division);
            if (div == null) {
                logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")");
                return new ResponseEntity<>("Division " + division + " does not exist", HttpStatus.BAD_REQUEST);
            } else {
                divisionList.add(div);
            }
        }
        userObject.replaceDivisions(divisionRepository, eventRepository, divisionList);
    } else {
        logger.debug("[" + currentUser + "] Clearing divisions for " + userObject.getEmail());
        userObject.replaceDivisions(divisionRepository, eventRepository, (List<Division>) null);
    }

    logger.debug("[" + currentUser + "] Parsing and setting custom user fields");
    userObject.setCustomUserField(parameters.keySet().parallelStream()
            .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty()) //Filtering all custom user fields, which are not empty
            .collect(Collectors.toMap(key -> key.substring(4), key -> parameters.get(key).trim()))); //Creating map of all fields

    logger.debug("[" + currentUser + "] Saving user " + userObject.getEmail());

    try {
        logger.debug("[{}] Saving user {}", currentUser, userObject);
        userRepository.save(userObject);
        logger.info("[" + currentUser + "] Successfully saved user " + userObject.getEmail());
        return new ResponseEntity<>("Successfully saved user", HttpStatus.OK);
    } catch (ConstraintViolationException e) {
        logger.warn("[" + currentUser + "] A database constraint was violated while saving the user: "
                + e.getMessage());
        return new ResponseEntity<>("A database constraint was violated while saving the user.",
                HttpStatus.BAD_REQUEST);
    }
}

From source file:svc.managers.SMSManagerTest.java

@Test
public void licenseReadMessageGetsGeneratedAgain() throws TwiMLException, ParseException {
    setStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN);
    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);
    List<Citation> citations = new ArrayList<Citation>();
    citations.add(citation);/*from   w w  w. ja  v  a 2 s.  c o m*/

    when(citationManagerMock.findCitations((CitationSearchCriteria) notNull())).thenReturn(citations);

    TwimlMessageRequest twimlMessageRequest = new TwimlMessageRequest();
    twimlMessageRequest.setBody("1");
    String message = "1 ticket was found\n1) ticket from: 02/03/1990\nReply with the ticket number you want to view.";
    MessagingResponse twimlResponse = manager.getTwimlResponse(twimlMessageRequest, requestMock, session);
    assertEquals(createTwimlResponse(message).toXml(), twimlResponse.toXml());
}

From source file:io.manasobi.utils.DateUtils.java

public static LocalDate convertToDate(String date, String pattern) {
    java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern(pattern);
    return LocalDate.parse(date, formatter);
}

From source file:com.objy.se.ClassAccessor.java

public Object getCorrectValue(String strValue, LogicalType logicalType) {
    Object retValue = null;//from   w w w. ja  v a  2s .  c om
    switch (logicalType) {
    case INTEGER: {
        long attrValue = 0;
        try {
            if (!strValue.equals("")) {
                attrValue = Long.parseLong(strValue);
            }
        } catch (NumberFormatException nfEx) {
            //        System.out.println("... entry: " + entry.getValue() + " for raw: " + entry.getKey());
            nfEx.printStackTrace();
            throw nfEx;
        }
        retValue = Long.valueOf(attrValue);
    }
        break;
    case REAL: {
        double attrValue = 0;
        try {
            if (!strValue.equals("")) {
                attrValue = Double.parseDouble(strValue);
            }
        } catch (NumberFormatException nfEx) {
            //        System.out.println("... entry: " + entry.getValue() + " for raw: " + entry.getKey());
            nfEx.printStackTrace();
            throw nfEx;
        }
        retValue = Double.valueOf(attrValue);
    }
        break;
    case STRING:
        retValue = strValue;
        break;
    case BOOLEAN: {
        if (strValue.equalsIgnoreCase("TRUE") || strValue.equals("1")) {
            retValue = Boolean.valueOf(true);
        } else if (strValue.equalsIgnoreCase("FALSE") || strValue.equals("0")) {
            retValue = Boolean.valueOf(false);
        } else {
            LOG.error("Expected Boolean value but got: {}", strValue);
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;

    case CHARACTER: {
        if (strValue.length() == 1) {
            retValue = Character.valueOf(strValue.charAt(0));
        } else { /* not a char value... report that */
            LOG.error("Expected Character value but got: {}", strValue);
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;
    case DATE: {
        try {
            LocalDate ldate = LocalDate.parse(strValue, dateFormatter);
            //            System.out.println("... ... year: " + ldate.getYear() + " - month:" + ldate.getMonthValue());
            retValue = new com.objy.db.Date(ldate.getYear(), ldate.getMonthValue(), ldate.getDayOfMonth());
        } catch (DateTimeParseException ex) {
            LOG.error(ex.toString());
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;
    case DATE_TIME: {
        try {
            //            System.out.println(".... formatter: " + mapper.getDateTimeFormat());
            LocalDateTime ldt = LocalDateTime.parse(strValue, dateTimeFormatter);
            //            System.out.println("... ... year: " + ldt.getYear() + 
            //                    " - month:" + ldt.getMonthValue() + " - day: " +
            //                    ldt.getDayOfMonth() + " - hour: " + ldt.getHour() +
            //                    " - min: " + ldt.getMinute() + " - sec: " + 
            //                    ldt.getSecond() + " - nsec: " + ldt.getNano() );
            //retValue = new com.objy.db.DateTime(date.getTime(), TimeKind.LOCAL);
            retValue = new com.objy.db.DateTime(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(),
                    ldt.getHour(), ldt.getMinute(), ldt.getSecond(), ldt.getNano());
        } catch (DateTimeParseException ex) {
            LOG.error(ex.toString());
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;
    case TIME: {
        try {
            //            System.out.println(".... formatter: " + mapper.getTimeFormat());
            LocalDateTime ltime = LocalDateTime.parse(strValue, dateFormatter);
            //            System.out.println("... ... hour: " + ltime.getHour() +
            //                    " - min: " + ltime.getMinute() + " - sec: " + 
            //                    ltime.getSecond() + " - nsec: " + ltime.getNano() );
            //retValue = new com.objy.db.DateTime(date.getTime(), TimeKind.LOCAL);
            retValue = new com.objy.db.Time(ltime.getHour(), ltime.getMinute(), ltime.getSecond(),
                    ltime.getNano());
        } catch (DateTimeParseException ex) {
            LOG.error(ex.toString());
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
    default: {
        throw new UnsupportedOperationException("LogicalType: " + logicalType + " is not supported!!!");
    }
    }
    return retValue;
}

From source file:net.tradelib.apps.StrategyBacktest.java

public static void run(Strategy strategy) throws Exception {
    // Setup the logging
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n");
    LogManager.getLogManager().reset();
    Logger rootLogger = Logger.getLogger("");
    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) {
        FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.FINEST);
        rootLogger.addHandler(logHandler);
    }/*from  w  w  w .  ja  v  a 2 s . co  m*/

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new SimpleFormatter());
        consoleHandler.setLevel(Level.INFO);
        rootLogger.addHandler(consoleHandler);
    }

    rootLogger.setLevel(Level.INFO);

    // Setup Hibernate
    // Configuration configuration = new Configuration();
    // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    // SessionFactory factory = configuration.buildSessionFactory(builder.build());

    Context context = new Context();
    context.dbUrl = BacktestCfg.instance().getProperty("db.url");

    HistoricalDataFeed hdf = new SQLDataFeed(context);
    hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties"));
    context.historicalDataFeed = hdf;

    HistoricalReplay hr = new HistoricalReplay(context);
    context.broker = hr;

    strategy.initialize(context);
    strategy.cleanupDb();

    long start = System.nanoTime();
    strategy.start();
    long elapsedTime = System.nanoTime() - start;
    System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    start = System.nanoTime();
    strategy.updateEndEquity();
    strategy.writeExecutionsAndTrades();
    strategy.writeEquity();
    elapsedTime = System.nanoTime() - start;
    System.out
            .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    System.out.println();

    // Write the strategy totals to the database
    strategy.totalTradeStats();

    // Write the strategy report to the database and obtain the JSON
    // for writing it to the console.
    JsonObject report = strategy.writeStrategyReport();

    JsonArray asa = report.getAsJsonArray("annual_stats");

    String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix");
    if (!Strings.isNullOrEmpty(csvPath)) {
        csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE)
                + ".csv";
    }

    String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix");
    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + ordersCsvPath;
    }

    String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix");
    if (!Strings.isNullOrEmpty(actionsPath)) {
        actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + actionsPath;
    }

    // If emails are being send out
    String signalText = StrategyText.build(context.dbUrl, strategy.getName(),
            strategy.getLastTimestamp().toLocalDate(), "   ", csvPath, '|');

    System.out.println(signalText);
    System.out.println();

    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(),
                strategy.getLastTimestamp().toLocalDate(), ordersCsvPath);
    }

    File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile,
                signalText + System.getProperty("line.separator") + System.getProperty("line.separator"));
    }

    String message = "";

    if (asa.size() > 0) {
        // Sort the array
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        for (int ii = 0; ii < asa.size(); ++ii) {
            int year = asa.get(ii).getAsJsonObject().get("year").getAsInt();
            map.put(year, ii);
        }

        for (int id : map.values()) {
            JsonObject jo = asa.get(id).getAsJsonObject();
            String yearStr = String.valueOf(jo.get("year").getAsInt());
            String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt());
            String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble());
            String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt());
            String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt());
            String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble());
            String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr
                    + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr;
            message += str + "\n";
        }

        String pnlStr = String.format("$%,d", report.get("pnl").getAsInt());
        String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble());
        String ddStr = String.format("$%,d", report.get("avgdd").getAsInt());
        String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble());
        String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble());
        String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr
                + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr;
        message += str + "\n";
    } else {
        message += "\n";
    }

    // Global statistics
    JsonObject jo = report.getAsJsonObject("total_peak");
    String dateStr = jo.get("date").getAsString();
    int maxEndEq = jo.get("equity").getAsInt();
    jo = report.getAsJsonObject("total_maxdd");
    double cash = jo.get("cash").getAsDouble();
    double pct = jo.get("pct").getAsDouble();
    message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n"
            + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";

    if (report.has("latest_peak") && report.has("latest_maxdd")) {
        jo = report.getAsJsonObject("latest_peak");
        LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE);
        maxEndEq = jo.get("equity").getAsInt();
        jo = report.getAsJsonObject("latest_maxdd");
        cash = jo.get("cash").getAsDouble();
        pct = jo.get("pct").getAsDouble();
        message += "\n" + Integer.toString(ld.getYear()) + " equity peak ["
                + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n"
                + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";
    }

    message += "\n" + "Avg Trade PnL: "
            + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: "
            + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: "
            + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: "
            + Integer.toString(report.get("num_trades").getAsInt());

    System.out.println(message);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true);
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.sendgrid.net");
        props.put("mail.smtp.port", "587");

        String user = BacktestCfg.instance().getProperty("email.user");
        String pass = BacktestCfg.instance().getProperty("email.pass");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        });

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from")));
            msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients"));
            msg.setSubject(strategy.getName() + " Report ["
                    + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]");
            msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message);
            Transport.send(msg);
        } catch (Exception ee) {
            Logger.getLogger("").warning(ee.getMessage());
        }
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) {
        HashMap<String, String> fileMap = new HashMap<String, String>();
        if (!Strings.isNullOrEmpty(actionsPath))
            fileMap.put(actionsPath, actionsPath);
        if (!Strings.isNullOrEmpty(ordersCsvPath))
            fileMap.put(ordersCsvPath, ordersCsvPath);
        String user = BacktestCfg.instance().getProperty("sftp.user");
        String pass = BacktestCfg.instance().getProperty("sftp.pass");
        String host = BacktestCfg.instance().getProperty("sftp.host");
        SftpUploader sftp = new SftpUploader(host, user, pass);
        sftp.upload(fileMap);
    }
}

From source file:de.jfachwert.rechnung.Rechnungsmonat.java

private static LocalDate guessLocalDate(String monat, DateTimeParseException ex) {
    String[] datePatterns = { "d-MMM-yyyy", "d-MM-yyyy", "yyyy-MMM-d", "yyyy-MM-d", "MMM-d-yyyy" };
    for (String pattern : datePatterns) {
        for (Locale locale : Locale.getAvailableLocales()) {
            try {
                return LocalDate.parse(monat, DateTimeFormatter.ofPattern(pattern, locale));
            } catch (DateTimeParseException ignored) {
                ex.addSuppressed(new IllegalArgumentException(
                        ignored.getMessage() + " / '" + monat + "' does not match '" + pattern + "'"));
            }/*from w  w w .  j a v a  2  s  . c o m*/
        }
    }
    throw new InvalidValueException(monat, MONTH, ex);
}

From source file:org.silverpeas.core.util.DateUtil.java

public static LocalDate stringToLocalDate(String string, String language) {
    DateTimeFormatter format = getLocalDateInputFormat(language);
    return LocalDate.parse(string, format);
}

From source file:com.github.horrorho.inflatabledonkey.args.ArgsFactory.java

static String mapTimestamp(String date) {
    return "" + LocalDate.parse(date, DateTimeFormatter.ISO_DATE).atStartOfDay(ZoneId.systemDefault())
            .toEpochSecond();/*from ww w.  j  av  a 2 s.c  o m*/
}