Example usage for java.time.format DateTimeFormatter BASIC_ISO_DATE

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

Introduction

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

Prototype

DateTimeFormatter BASIC_ISO_DATE

To view the source code for java.time.format DateTimeFormatter BASIC_ISO_DATE.

Click Source Link

Document

The ISO date formatter that formats or parses a date without an offset, such as '20111203'.

Usage

From source file:lumbermill.internal.aws.AWSV4SignerImpl.java

private byte[] getSignatureKey(LocalDateTime now, AWSCredentials credentials) {
    final byte[] kSecret = (AWS4 + credentials.getAWSSecretKey()).getBytes(Charsets.UTF_8);
    final byte[] kDate = hmacSHA256(now.format(DateTimeFormatter.BASIC_ISO_DATE), kSecret);
    final byte[] kRegion = hmacSHA256(region, kDate);
    final byte[] kService = hmacSHA256(service, kRegion);
    return hmacSHA256(AWS_4_REQUEST, kService);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
* Mthode ralisant l'export des FEC (Fichiers des critures Comptables)
* @throws AxelorException/*  w ww  . ja va2  s .c o  m*/
* @throws IOException
*/
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public void exportMoveLineTypeSelect1000(MoveLineReport moveLineReport) throws AxelorException, IOException {

    log.info("In Export type 1000 service : ");
    List<String[]> allMoveLineData = new ArrayList<String[]>();
    Company company = moveLineReport.getCompany();

    String moveLineQueryStr = "";
    moveLineQueryStr += String.format(" AND self.move.company = %s", company.getId());
    moveLineQueryStr += String.format(" AND self.move.period.year = %s", moveLineReport.getYear().getId());

    if (moveLineReport.getPeriod() != null) {
        moveLineQueryStr += String.format(" AND self.move.period = %s", moveLineReport.getPeriod().getId());
    } else {
        if (moveLineReport.getDateFrom() != null) {
            moveLineQueryStr += String.format(" AND self.date >= '%s'",
                    moveLineReport.getDateFrom().toString());
        }
        if (moveLineReport.getDateTo() != null) {
            moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
        }
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }

    moveLineQueryStr += String
            .format("AND self.move.accountingOk = false AND self.move.ignoreInAccountingOk = false");

    List<MoveLine> moveLineList = moveLineRepo.all()
            .filter("self.move.statusSelect = ?1" + moveLineQueryStr, MoveRepository.STATUS_VALIDATED)
            .order("date").order("name").fetch();
    if (moveLineList.size() > 0) {

        for (MoveLine moveLine : moveLineList) {
            String items[] = new String[18];
            Move move = moveLine.getMove();
            Journal journal = move.getJournal();
            items[0] = journal.getCode();
            items[1] = journal.getName();
            items[2] = moveLine.getName();
            items[3] = moveLine.getDate().format(DateTimeFormatter.BASIC_ISO_DATE);
            items[4] = moveLine.getAccount().getCode();
            items[5] = moveLine.getAccount().getName();
            items[6] = null; //Le numro de compte auxiliaire ( blanc pour le moment) 
            items[7] = null; //Le libell de compte auxiliaire ( blanc pour le moment) 
            items[8] = moveLine.getOrigin();
            items[9] = moveLine.getDate().format(DateTimeFormatter.BASIC_ISO_DATE); // Pour le moment on va utiliser la date des lignes d'criture. 
            items[10] = moveLine.getDescription();
            items[11] = moveLine.getDebit().toString();
            items[12] = moveLine.getCredit().toString();
            if (moveLine.getDebit().compareTo(BigDecimal.ZERO) > 0) {
                List<String> ReconcileSeqList = new ArrayList<String>();
                List<String> ReconcileDateList = new ArrayList<String>();

                for (Reconcile reconcile : moveLine.getDebitReconcileList()) {
                    ReconcileSeqList.add(reconcile.getReconcileSeq());
                    ReconcileDateList.add(
                            reconcile.getReconciliationDate().format(DateTimeFormatter.ofPattern("YYYYMMdd")));
                }
                items[13] = StringUtils.join(ReconcileSeqList, "; ");
                items[14] = StringUtils.join(ReconcileDateList, "; ");
            } else {
                List<String> ReconcileSeqList = new ArrayList<String>();
                List<String> ReconcileDateList = new ArrayList<String>();
                for (Reconcile reconcile : moveLine.getCreditReconcileList()) {
                    ReconcileSeqList.add(reconcile.getReconcileSeq());
                    ReconcileDateList
                            .add(reconcile.getReconciliationDate().format(DateTimeFormatter.BASIC_ISO_DATE));
                }
                items[13] = StringUtils.join(ReconcileSeqList, "; ");
                items[14] = StringUtils.join(ReconcileDateList, "; ");
            }
            items[15] = move.getValidationDate().format(DateTimeFormatter.BASIC_ISO_DATE);
            items[16] = moveLine.getCurrencyAmount().toString();
            if (move.getCurrency() != null) {
                items[17] = move.getCurrency().getCode();
            }
            allMoveLineData.add(items);
        }
    }

    String fileName = this.setFileName(moveLineReport);
    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    //TODO create a template Helper

    new File(filePath).mkdirs();
    log.debug("Full path to export : {}{}", filePath, fileName);
    //      CsvTool.csvWriter(filePath, fileName, '|', null, allMoveLineData);
    CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(moveLineReport.getTypeSelect()),
            allMoveLineData);
    moveLineReportRepo.save(moveLineReport);

    Path path = Paths.get(filePath + fileName);

    try (InputStream is = new FileInputStream(path.toFile())) {
        Beans.get(MetaFiles.class).attach(is, fileName, moveLineReport);
    }

}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public String setFileName(MoveLineReport moveLineReport) throws AxelorException, IOException {
    Company company = moveLineReport.getCompany();
    Partner partner = company.getPartner();

    //Pour le moment: on utilise le format par dfaut: SIREN+FEC+DATE DE CLTURE DE L'EXERCICE.Extension
    String fileName = partnerService.getSIRENNumber(partner) + "FEC";
    // On rcupre la date de clture de l'exercice/priode
    if (moveLineReport.getDateTo() != null) {
        fileName += moveLineReport.getDateTo().format(DateTimeFormatter.BASIC_ISO_DATE);
    } else if (moveLineReport.getPeriod() != null) {
        fileName += moveLineReport.getPeriod().getToDate().format(DateTimeFormatter.BASIC_ISO_DATE);
    } else {//from  w w w .  j av  a  2 s .  c  o  m
        fileName += moveLineReport.getYear().getToDate().format(DateTimeFormatter.BASIC_ISO_DATE);
    }
    fileName += ".csv";

    return fileName;
}

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  ww .  j a va2s.  c  om

    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:onl.area51.gfs.grib2.job.GribRetriever.java

/**
 * Select the specified run./*from w w  w  . j  av a2s  .  c  om*/
 * <p>
 * @param date The date and hour of the required run
 * <p>
 * @throws java.io.IOException
 */
public void selectRun(LocalDateTime date) throws IOException {
    LOG.log(Level.INFO, "Retrieving directory listing");
    client.changeWorkingDirectory(DIR);
    Stream<FTPFile> dirs = client.directories().filter(f -> f.getName().startsWith("gfs."));

    if (date == null) {
        // Look for the most recent date
        dirs = dirs.sorted((a, b) -> b.getName().compareToIgnoreCase(a.getName()));
    } else {
        // Look for a specific date
        String filter = "gfs." + toGFSRunTime(date).format(DateTimeFormatter.BASIC_ISO_DATE);
        dirs = dirs.filter(f -> filter.equals(f.getName()));
    }

    @SuppressWarnings("ThrowableInstanceNotThrown")
    FTPFile dir = dirs.findFirst()
            .orElseThrow(() -> new FileNotFoundException("Failed to find remote gfs directory "));

    client.changeWorkingDirectory(dir.getName());
    String pwd = client.printWorkingDirectory();
    LOG.log(Level.INFO, () -> "Now in directory " + pwd);
}

From source file:org.talend.dataquality.statistics.datetime.utils.PatternListGenerator.java

@SuppressWarnings("unused")
private static void validateISOPattens(List<String> isoPatternList) {

    Set<String> formattedDateTimeSet = new HashSet<String>();
    for (String pattern : isoPatternList) {
        formattedDateTimeSet.add(getFormattedDateTime(pattern, Locale.US));
    }//from  w  ww . j  ava 2 s  .c o m

    DateTimeFormatter[] formatters = new DateTimeFormatter[] { DateTimeFormatter.BASIC_ISO_DATE, // 1
            DateTimeFormatter.ISO_DATE, // 2
            DateTimeFormatter.ISO_DATE_TIME, // 3
            // DateTimeFormatter.ISO_TIME, //
            DateTimeFormatter.ISO_INSTANT, // 4
            DateTimeFormatter.ISO_LOCAL_DATE, // 5
            DateTimeFormatter.ISO_LOCAL_DATE_TIME, // 6
            // DateTimeFormatter.ISO_LOCAL_TIME, //
            DateTimeFormatter.ISO_OFFSET_DATE, // 7
            DateTimeFormatter.ISO_OFFSET_DATE_TIME, // 8
            // DateTimeFormatter.ISO_OFFSET_TIME, //
            DateTimeFormatter.ISO_ORDINAL_DATE, // 9
            DateTimeFormatter.ISO_WEEK_DATE, // 10
            DateTimeFormatter.ISO_ZONED_DATE_TIME, // 11
            DateTimeFormatter.RFC_1123_DATE_TIME, // 12
    };

    System.out.println("-------------Validate ISO PattenText-------------");
    for (int i = 0; i < formatters.length; i++) {

        System.out.print((i + 1) + "\t");
        try {
            String formattedDateTime = ZONED_DATE_TIME.format(formatters[i]);
            System.out.print(formattedDateTimeSet.contains(formattedDateTime) ? "YES\t" : "NO\t");
            System.out.println(formattedDateTime);
        } catch (Throwable t) {
            System.out.println(t.getMessage());
        }
    }

}