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:com.qq.tars.service.config.ConfigService.java

@Transactional(rollbackFor = Exception.class)
public ConfigFile updateConfigFile(UpdateConfigFile params) {
    ConfigFile configFile = configMapper.loadConfigFile(params.getId());
    configFile.setConfig(params.getConfig());
    configFile.setPosttime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    configMapper.updateConfigFile(configFile);

    ConfigFileHistory history = new ConfigFileHistory();
    history.setConfigId(configFile.getId());
    history.setReason(params.getReason());
    history.setContent(configFile.getConfig());
    history.setPosttime(configFile.getPosttime());
    configMapper.insertConfigFileHistory(history);

    return configFile;
}

From source file:com.ikanow.aleph2.analytics.hadoop.services.MockHadoopTestingService.java

/** Returns the number of files in the designated bucket's storage service
 * @param bucket//from  w w  w  .j  a  va2 s.  c  o  m
 * @param subservice_suffix
 * @param date
 * @return
 */
public int numFilesInBucketStorage(final DataBucketBean bucket, final String subservice_suffix,
        Either<Optional<Date>, Unit> date) {
    final String bucketPath1 = _service_context.getStorageService().getBucketRootPath() + bucket.full_name();
    final String bucketReadyPath1 = bucketPath1 + subservice_suffix
            + date.either(left -> left.map(d -> DateTimeFormatter.ofPattern("yyyy-MM-dd").format(d.toInstant()))
                    .orElse(IStorageService.NO_TIME_SUFFIX), right -> "");

    return Optional.ofNullable(new File(bucketReadyPath1).listFiles()).orElseGet(() -> new File[0]).length / 2;
    //(/2 because of .crc file)
}

From source file:com.romeikat.datamessie.core.base.ui.panel.DocumentsFilterPanel.java

public static String formatLocalDate(final LocalDate localDate) {
    // No date corresponds to 0
    if (localDate == null) {
        return "0";
    }/*from   ww  w.ja  v a 2s . co  m*/
    // Today corresponds to no date
    final LocalDate today = LocalDate.now();
    if (localDate.equals(today)) {
        return null;
    }
    // Date pattern
    return localDate.format(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN));
}

From source file:org.ojbc.adapters.analyticaldatastore.personid.IndexedIdentifierGenerationStrategy.java

/**
 * This method will back up the lucene cache using the specified backup path.
 * It will create a new directory with the format yyyy_MM_dd_HH_mm_ss which will
 * contain the backed up index.  Hot backups are allowed.
 * /*from   ww w.j  a v a2 s  .  c  om*/
 */
@Override
public String backup() throws Exception {
    SnapshotDeletionPolicy snapshotter = (SnapshotDeletionPolicy) indexWriter.getConfig()
            .getIndexDeletionPolicy();

    IndexCommit commit = null;
    String backupFileDirectory = "";

    try {
        LocalDateTime today = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu_MM_dd_HH_mm_ss");
        String dateTimeStamp = today.format(dtf);

        if (!(indexBackupRoot.endsWith("/") || indexBackupRoot.endsWith("\\"))) {
            indexBackupRoot = indexBackupRoot + System.getProperty("file.separator");
        }

        backupFileDirectory = indexBackupRoot + dateTimeStamp + System.getProperty("file.separator");

        commit = snapshotter.snapshot();
        for (String fileName : commit.getFileNames()) {
            log.debug("File Name: " + fileName);

            File srcFile = new File(indexDirectoryPath + System.getProperty("file.separator") + fileName);
            File destFile = new File(backupFileDirectory + System.getProperty("file.separator") + fileName);

            FileUtils.copyFile(srcFile, destFile);

        }
    } catch (Exception e) {
        log.error("Exception", e);
    } finally {
        snapshotter.release(commit);
    }

    return backupFileDirectory;
}

From source file:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.java

private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize,
        ChartHistoMovingAverage histoAverage, ChartHistoTimeSpan histoPeriod, Integer intradayWidth,
        Integer intradayHeight) {

    Preconditions.checkNotNull(stock, "stock must not be null!");
    Preconditions.checkNotNull(type, "ChartType must not be null!");

    String guid = AuthenticationUtil.getPrincipal().getUsername();
    SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
    if (socialUser == null) {
        return;/*ww w.  j  a v a 2  s  . c  o  m*/
    }
    String token = socialUser.getAccessToken();
    Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

    if (connection != null) {
        byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type,
                histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
        String imageName = stock.getId().toLowerCase() + "_" + type.name().toLowerCase() + "_"
                + formattedDateTime + ".png";
        String pathToYahooPicture = env.getProperty("user.home").concat(env.getProperty("pictures.yahoo.path"))
                .concat(File.separator + imageName);

        try {
            Path newPath = Paths.get(pathToYahooPicture);
            Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new Error("Storage of " + pathToYahooPicture + " failed", e);
        }

        ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth,
                intradayHeight, pathToYahooPicture);
        chartStockRepository.save(chartStock);
    }
}

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

@Override
public String execute() throws Exception {
    if (projectInnovationID == null
            || projectInnovationManager.getProjectInnovationById(projectInnovationID) == null
            || projectInnovationManager.getProjectInnovationById(projectInnovationID)
                    .getProjectInnovationInfo(this.getSelectedPhase()) == null) {
        LOG.error("Project Innovation " + projectInnovationID + " Not found");
        return NOT_FOUND;
    } else {//  w  w w. java 2s .  c  om
        projectInnovationInfo = projectInnovationManager.getProjectInnovationById(projectInnovationID)
                .getProjectInnovationInfo(this.getSelectedPhase());
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        Resource reportResource = resourceManager.createDirectly(
                this.getClass().getResource("/pentaho/crp/ProjectInnovationPDF.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("project_innovation"), "project_innovation");
        PdfReportUtil.createPDF(masterReport, os);
        bytesPDF = os.toByteArray();
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating ProjectInnovation 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;
}

From source file:org.codelibs.fess.service.CrawlingSessionService.java

public void exportCsv(final Writer writer) {
    final CsvConfig cfg = new CsvConfig(',', '"', '"');
    cfg.setEscapeDisabled(false);/*from  w ww.jav a 2 s  . co m*/
    cfg.setQuoteDisabled(false);
    @SuppressWarnings("resource")
    final CsvWriter csvWriter = new CsvWriter(writer, cfg);
    try {
        final List<String> list = new ArrayList<String>();
        list.add("SessionId");
        list.add("SessionCreatedTime");
        list.add("Key");
        list.add("Value");
        list.add("CreatedTime");
        csvWriter.writeValues(list);
        final DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
        crawlingSessionInfoBhv.selectCursor(cb -> {
            cb.setupSelect_CrawlingSession();
        }, new EntityRowHandler<CrawlingSessionInfo>() {
            @Override
            public void handle(final CrawlingSessionInfo entity) {
                final List<String> list = new ArrayList<String>();
                entity.getCrawlingSession().ifPresent(crawlingSession -> {
                    addToList(list, crawlingSession.getSessionId());
                    addToList(list, crawlingSession.getCreatedTime());
                });
                // TODO
                if (!entity.getCrawlingSession().isPresent()) {
                    addToList(list, "");
                    addToList(list, "");
                }
                addToList(list, entity.getKey());
                addToList(list, entity.getValue());
                addToList(list, entity.getCreatedTime());
                try {
                    csvWriter.writeValues(list);
                } catch (final IOException e) {
                    log.warn("Failed to write a crawling session info: " + entity, e);
                }
            }

            private void addToList(final List<String> list, final Object value) {
                if (value == null) {
                    list.add(StringUtil.EMPTY);
                } else if (value instanceof LocalDateTime) {
                    list.add(((LocalDateTime) value).format(formatter));
                } else {
                    list.add(value.toString());
                }
            }
        });
        csvWriter.flush();
    } catch (final IOException e) {
        log.warn("Failed to write a crawling session info.", e);
    }
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java

private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize,
        ChartHistoMovingAverage histoAverage, ChartHistoTimeSpan histoPeriod, Integer intradayWidth,
        Integer intradayHeight) {

    Preconditions.checkNotNull(stock, "stock must not be null!");
    Preconditions.checkNotNull(type, "ChartType must not be null!");

    String guid = AuthenticationUtil.getPrincipal().getUsername();
    String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken();
    ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid);
    Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

    if (connection != null) {
        byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type,
                histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
        String imageName = stock.getId().toLowerCase() + "_" + type.name().toLowerCase() + "_"
                + formattedDateTime + ".png";
        String pathToYahooPicture = env.getProperty("pictures.yahoo.path").concat(File.separator + imageName);

        try {/*from   ww  w .  ja v a 2s .  com*/
            Path newPath = Paths.get(pathToYahooPicture);
            Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new Error("Storage of " + pathToYahooPicture + " failed", e);
        }

        ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth,
                intradayHeight, pathToYahooPicture);
        chartStockRepository.save(chartStock);
    }
}

From source file:com.amazonaws.services.kinesis.io.JsonDataExtractor.java

/**
 * Builder method which allows adding a date format string which can be used
 * to convert the data value in the dateValueAttribute, if the value is a
 * string./*from   www  . j  a  v a2  s  .  c o m*/
 * 
 * @param dateFormat Date Format in {@link java.text.SimpleDateFormat} form.
 * @return
 */
public JsonDataExtractor withDateFormat(String dateFormat) {
    if (dateFormat != null && !dateFormat.equals("")) {
        this.dateFormat = dateFormat;
        this.dateFormatter = DateTimeFormatter.ofPattern(dateFormat);
    }
    return this;
}

From source file:org.symphonyoss.simplebot.LunchBoxBot.java

private void processMessage(Message message) {
    username = message.getFromUserId().toString();
    String messageString = message.getMessage();
    if (StringUtils.isNotEmpty(messageString) && StringUtils.isNotBlank(messageString)) {
        MlMessageParser messageParser = new MlMessageParser();
        try {/* w w w.j  a  va2 s  .  c  o m*/
            messageParser.parseMessage(messageString);
            String text = messageParser.getText();
            if (isFeedback == true) {
                processFeedback(text);
                isFeedback = false;
            }

            if (StringUtils.startsWithIgnoreCase(text, "/lunchbox")) {
                LunchBotCommand cmd = getLunchBotCommand(text);

                switch (cmd) {
                case MENU:
                    HashMap lunch = parseLunchMenu(todayDateString);
                    sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body"));
                    break;
                case FEEDBACK:
                    isFeedback = true;
                    break;
                case TOMORROW:
                    LocalDate tomorrowDate = LocalDate.from(todayDate.toInstant().atZone(ZoneId.of("UTC")))
                            .plusDays(1);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy,MM,dd");
                    String tomorrowString = tomorrowDate.format(formatter);
                    lunch = parseLunchMenu(tomorrowString);
                    sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body"));
                    break;
                case FORMAT:
                    sendMessage(
                            "- For feedback on individual items on the menu, <item number> -> <number of stars (out of 5)>\n- For feedback on lunch as a whole, <overall> -> <number of stars (out of 5)>, comments (optional)\n\n\nP.S: Please provide complete feedback in a single message with each section separated by a comma");
                    break;
                case OPTIONS:
                    sendMessage(
                            "For today's menu:  '/lunchbox menu' OR '/lunchbox today's menu'\nFor tomorrow's menu: '/lunchbox tomorrow' OR '/lunchbox tomorrow's menu'\nFor tips on format for feedback: '/lunchbox format'\nFor feedback: '/lunchbox feedback' <hit enter and then provide feedback all in one message>\nFor options: '/lunchbox help'\n\n\nP.S: All commands should be typed without quotes");
                    break;
                case UNKNOWN:
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}