Example usage for org.apache.commons.lang.time DateFormatUtils format

List of usage examples for org.apache.commons.lang.time DateFormatUtils format

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateFormatUtils format.

Prototype

public static String format(Date date, String pattern) 

Source Link

Document

Formats a date/time into a specific pattern.

Usage

From source file:org.medici.bia.controller.search.AjaxController.java

/**
 * //w  w w .  j  av  a 2  s  .c  o m
 * @param model
 * @param httpSession
 * @param paginationFilter
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void userSearchFilters(Map<String, Object> model, HttpSession httpSession,
        PaginationFilter paginationFilter, SearchType searchType) {
    Page page = null;

    try {
        if (searchType == null) {
            page = getSearchService().getUserSearchFilters(paginationFilter);
        } else {
            page = getSearchService().getUserSearchFilters(paginationFilter, searchType);
        }
    } catch (ApplicationThrowable aex) {
        page = new Page(paginationFilter);
    }

    List resultList = new ArrayList();
    for (SearchFilter currentFilter : (List<SearchFilter>) page.getList()) {
        List singleRow = new ArrayList();
        singleRow.add(currentFilter.getFilterName());
        singleRow.add(currentFilter.getTotalResult());
        singleRow.add(currentFilter.getSearchType());
        singleRow.add(DateFormatUtils.format(currentFilter.getDateUpdated(), "MM/dd/yyyy"));
        singleRow.add(
                "<input type=\"checkbox\" name=\"unpaginated\" idElement=\"" + currentFilter.getId() + "\" >");

        resultList.add(HtmlUtils.showUserSearchFilter(singleRow, currentFilter.getId(),
                currentFilter.getSearchType()));
    }
    model.put("iEcho", "1");
    model.put("iTotalDisplayRecords", page.getTotal());
    model.put("iTotalRecords", page.getTotal());
    model.put("aaData", resultList);
}

From source file:org.onehippo.forge.cmisreplication.CmisTest.java

private void printDocument(Document document) {
    System.out.println("[Document: " + document.getName() + "]");

    for (Property<?> p : document.getProperties()) {
        if (PropertyType.DATETIME == p.getType()) {
            Calendar calValue = (Calendar) p.getValue();
            System.out.println("  - " + p.getId() + "="
                    + (calValue != null ? DateFormatUtils.format(calValue, "yyyy-MM-dd HH:mm:ss z") : ""));
        } else {//from  w w w.  j a  v  a  2s.co  m
            System.out.println("  - " + p.getId() + "=" + p.getValue());
        }
    }
}

From source file:org.onehippo.forge.content.exim.repository.jaxrs.ContentEximExportService.java

@Path("/")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@POST/*www. j a va 2 s  . c om*/
public Response exportContentToZip(@Context SecurityContext securityContext,
        @Context HttpServletRequest request,
        @Multipart(value = "batchSize", required = false) String batchSizeParam,
        @Multipart(value = "throttle", required = false) String throttleParam,
        @Multipart(value = "publishOnImport", required = false) String publishOnImportParam,
        @Multipart(value = "dataUrlSizeThreshold", required = false) String dataUrlSizeThresholdParam,
        @Multipart(value = "docbasePropNames", required = false) String docbasePropNamesParam,
        @Multipart(value = "documentTags", required = false) String documentTagsParam,
        @Multipart(value = "binaryTags", required = false) String binaryTagsParam,
        @Multipart(value = "paramsJson", required = false) String paramsJsonParam,
        @Multipart(value = "params", required = false) Attachment paramsAttachment) {

    Logger procLogger = log;

    File tempLogFile = null;
    PrintStream tempLogOut = null;
    File baseFolder = null;
    Session session = null;
    ExecutionParams params = new ExecutionParams();
    ProcessStatus processStatus = null;

    try {
        tempLogFile = File.createTempFile(TEMP_PREFIX, ".log");
        tempLogOut = new PrintStream(new BufferedOutputStream(new FileOutputStream(tempLogFile)));
        procLogger = createTeeLogger(log, tempLogOut);

        if (getProcessMonitor() != null) {
            processStatus = getProcessMonitor().startProcess();
            fillProcessStatusByRequestInfo(processStatus, securityContext, request);
            processStatus.setLogFile(tempLogFile);
        }

        baseFolder = Files.createTempDirectory(TEMP_PREFIX).toFile();
        procLogger.info("ContentEximService#exportContentToZip begins at {}.", baseFolder);

        if (paramsAttachment != null) {
            final String json = attachmentToString(paramsAttachment, "UTF-8");
            if (StringUtils.isNotBlank(json)) {
                params = getObjectMapper().readValue(json, ExecutionParams.class);
            }
        } else {
            if (StringUtils.isNotBlank(paramsJsonParam)) {
                params = getObjectMapper().readValue(paramsJsonParam, ExecutionParams.class);
            }
        }
        overrideExecutionParamsByParameters(params, batchSizeParam, throttleParam, publishOnImportParam,
                dataUrlSizeThresholdParam, docbasePropNamesParam, documentTagsParam, binaryTagsParam);

        if (processStatus != null) {
            processStatus.setExecutionParams(params);
        }

        session = createSession();
        Result result = ResultItemSetCollector.collectItemsFromExecutionParams(session, params);
        session.refresh(false);

        FileObject baseFolderObject = VFS.getManager().resolveFile(baseFolder.toURI());
        FileObject attachmentsFolderObject = baseFolderObject.resolveFile(BINARY_ATTACHMENT_REL_PATH);

        DocumentManager documentManager = new WorkflowDocumentManagerImpl(session);

        final WorkflowDocumentVariantExportTask documentExportTask = new WorkflowDocumentVariantExportTask(
                documentManager);
        documentExportTask.setLogger(log);
        documentExportTask.setBinaryValueFileFolder(attachmentsFolderObject);
        documentExportTask.setDataUrlSizeThreashold(params.getDataUrlSizeThreshold());

        final DefaultBinaryExportTask binaryExportTask = new DefaultBinaryExportTask(documentManager);
        binaryExportTask.setLogger(log);
        binaryExportTask.setBinaryValueFileFolder(attachmentsFolderObject);
        binaryExportTask.setDataUrlSizeThreashold(params.getDataUrlSizeThreshold());

        int batchCount = 0;

        Set<String> referredNodePaths = new LinkedHashSet<>();

        try {
            documentExportTask.start();
            batchCount = exportDocuments(procLogger, processStatus, params, documentExportTask, result,
                    batchCount, baseFolderObject, referredNodePaths);
        } finally {
            documentExportTask.stop();
        }

        if (!referredNodePaths.isEmpty()) {
            ResultItemSetCollector.fillResultItemsForNodePaths(session, referredNodePaths, true, null, result);
            session.refresh(false);
        }

        try {
            binaryExportTask.start();
            batchCount = exportBinaries(procLogger, processStatus, params, binaryExportTask, result, batchCount,
                    baseFolderObject);
        } finally {
            binaryExportTask.stop();
        }

        session.logout();
        session = null;

        procLogger.info("ContentEximService#exportContentToZip ends.");

        tempLogOut.close();
        tempLogOut = null;
        procLogger = log;

        final String tempLogOutString = FileUtils.readFileToString(tempLogFile, "UTF-8");
        final File zipBaseFolder = baseFolder;

        final StreamingOutput entity = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                ZipArchiveOutputStream zipOutput = null;
                try {
                    zipOutput = new ZipArchiveOutputStream(output);
                    ZipCompressUtils.addEntryToZip(EXIM_EXECUTION_LOG_REL_PATH, tempLogOutString, "UTF-8",
                            zipOutput);
                    ZipCompressUtils.addEntryToZip(EXIM_SUMMARY_BINARIES_LOG_REL_PATH,
                            binaryExportTask.getSummary(), "UTF-8", zipOutput);
                    ZipCompressUtils.addEntryToZip(EXIM_SUMMARY_DOCUMENTS_LOG_REL_PATH,
                            documentExportTask.getSummary(), "UTF-8", zipOutput);
                    ZipCompressUtils.addFileEntriesInFolderToZip(zipBaseFolder, "", zipOutput);
                } finally {
                    zipOutput.finish();
                    IOUtils.closeQuietly(zipOutput);
                    FileUtils.deleteDirectory(zipBaseFolder);
                }
            }
        };

        String fileName = "exim-export-" + DateFormatUtils.format(Calendar.getInstance(), "yyyyMMdd-HHmmss")
                + ".zip";
        return Response.ok().header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                .entity(entity).build();
    } catch (Exception e) {
        procLogger.error("Failed to export content.", e);
        if (baseFolder != null) {
            try {
                FileUtils.deleteDirectory(baseFolder);
            } catch (Exception ioe) {
                procLogger.error("Failed to delete the temporary folder at {}", baseFolder.getPath(), e);
            }
        }
        final String message = new StringBuilder().append(e.getMessage()).append("\r\n").toString();
        return Response.serverError().entity(message).build();
    } finally {
        procLogger.info("ContentEximService#exportContentToZip finally ends.");

        if (getProcessMonitor() != null) {
            try {
                getProcessMonitor().stopProcess(processStatus);
            } catch (Exception e) {
                procLogger.error("Failed to stop process.", e);
            }
        }

        if (session != null) {
            try {
                session.logout();
            } catch (Exception e) {
                procLogger.error("Failed to logout JCR session.", e);
            }
        }

        if (tempLogOut != null) {
            IOUtils.closeQuietly(tempLogOut);
        }

        if (tempLogFile != null) {
            try {
                tempLogFile.delete();
            } catch (Exception e) {
                log.error("Failed to delete temporary log file.", e);
            }
        }
    }
}

From source file:org.onehippo.forge.document.commenting.cms.impl.DefaultJcrCommentPersistenceManager.java

public String getCommentHeadText(CommentingContext commentingContext, CommentItem commentItem)
        throws CommentingException {
    StringBuilder sb = new StringBuilder(40);
    sb.append(getAuthorName(commentingContext, commentItem)).append(" - ")
            .append(DateFormatUtils.format(commentItem.getCreated(), getDateFormat(commentingContext)));
    return sb.toString();
}

From source file:org.openkoala.koala.commons.KoalaDateUtils.java

/**
 * ?<br>//w w w .ja  v  a 2  s . c o  m
 * generate by: vakin jiang at 2011-12-23
 * 
 * @param date
 * @return
 */
public static Date getDayBegin(Date date) {
    String format = DateFormatUtils.format(date, YYYY_MM_DD);
    return parseDate(format.concat(" 00:00:00"));
}

From source file:org.openkoala.koala.commons.KoalaDateUtils.java

/**
 * ??<br>/* w  w  w.  j a  v  a 2  s .  co m*/
 * generate by: vakin jiang at 2011-12-23
 * 
 * @param date
 * @return
 */
public static Date getDayEnd(Date date) {
    String format = DateFormatUtils.format(date, YYYY_MM_DD);
    return parseDate(format.concat(" 23:59:59"));
}

From source file:org.openkoala.koala.commons.KoalaDateUtils.java

/**
 * ?<br>//w ww  .  j  a va  2  s  .  co  m
 * generate by: vakin jiang at 2012-3-7
 * 
 * @param dateStr
 * @param patterns
 * @return
 */
public static String formatDateStr(String dateStr, String... patterns) {
    String pattern = YYYY_MM_DD_HH_MM_SS;
    if (patterns != null && patterns.length > 0 && StringUtils.isNotBlank(patterns[0])) {
        pattern = patterns[0];
    }
    return DateFormatUtils.format(parseDate(dateStr), pattern);
}

From source file:org.openkoala.koala.commons.KoalaDateUtils.java

/**
 * ?<br>//from ww w .ja  va2 s . c o  m
 * generate by: vakin jiang at 2012-3-7
 * 
 * @param orig
 * @param patterns
 * @return
 */
public static String format(Date date, String... patterns) {
    if (date == null)
        return "";
    String pattern = YYYY_MM_DD_HH_MM_SS;
    if (patterns != null && patterns.length > 0 && StringUtils.isNotBlank(patterns[0])) {
        pattern = patterns[0];
    }
    return DateFormatUtils.format(date, pattern);
}

From source file:org.openkoala.koala.commons.KoalaDateUtils.java

/**
 * ??<br>/*from w  ww  .  j a v  a 2 s  .c  o m*/
 * generate by: vakin jiang at 2012-3-7
 * 
 * @param orig
 * @param patterns
 * @return
 */
public static Date formatDate(Date orig, String... patterns) {
    String pattern = YYYY_MM_DD_HH_MM_SS;
    if (patterns != null && patterns.length > 0 && StringUtils.isNotBlank(patterns[0])) {
        pattern = patterns[0];
    }
    return parseDate(DateFormatUtils.format(orig, pattern));
}

From source file:org.openkoala.koala.monitor.support.ServerStatusCollector.java

/**
 * ???// ww  w  . j a  v a2 s .  c  om
 * @return
 */
public static void getServerBaseInfo(ServerStatusVo status) {
    status.setServerTime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
    status.setServerName(System.getenv().get("COMPUTERNAME"));
    //      status.setJavaServer(RuntimeContext.getContext().getServerName());
    //      status.setDeployPath(RuntimeContext.getContext().getDeployPath());

    Runtime rt = Runtime.getRuntime();
    status.setJvmTotalMem(rt.totalMemory() / (1024 * 1024));
    status.setJvmFreeMem(rt.freeMemory() / (1024 * 1024));

    Properties props = System.getProperties();
    status.setServerOs(props.getProperty("os.name") + " " + props.getProperty("os.arch") + " "
            + props.getProperty("os.version"));
    status.setJavaHome(props.getProperty("java.home"));
    status.setJavaVersion(props.getProperty("java.version"));
    status.setJavaTmpPath(props.getProperty("java.io.tmpdir"));

}