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

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

Introduction

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

Prototype

public static String format(final Calendar calendar, final String pattern) 

Source Link

Document

Formats a calendar into a specific pattern.

Usage

From source file:cn.mypandora.util.MyDateUtils.java

/**
 * ???X//from   www.  j a  v a 2 s  .  co m
 *
 * @param specifiedTime ,?yyyy-MM-dd HH:mm:ss
 * @param offset        ??
 * @return
 * @throws ParseException
 */
public static String getSpecifiedOffsetTime(String specifiedTime, int offset) throws ParseException {
    Date date = DateUtils.parseDate(specifiedTime, TIME_FORMAT);
    Calendar cal = DateUtils.toCalendar(date);
    cal.add(Calendar.DAY_OF_MONTH, offset);
    String returnDate = DateFormatUtils.format(cal, TIME_FORMAT);
    return returnDate;
}

From source file:architecture.common.adaptor.connector.jdbc.AbstractJdbcConnector.java

/**
 * Batch .../* w ww .  j  a  v  a  2s .  com*/
 * 
 * @param queryString
 * @param parameterMappings
 * @param rows
 * @return
 */
protected Object deliver(final String queryString, final List<ParameterMapping> parameterMappings,
        final List<Map<String, Object>> rows) {

    log.debug("delivering : " + rows.size());

    int[] cnt = getJdbcTemplate().batchUpdate(queryString, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Map<String, Object> row = rows.get(i);
            for (ParameterMapping mapping : parameterMappings) {
                JdbcType jdbcType = mapping.getJdbcType();
                Object value = row.get(mapping.getProperty());
                Object valueToUse = value;

                if (valueToUse == null && mapping.getJavaType() == Date.class) {
                    valueToUse = new Date();
                }

                if (valueToUse instanceof Date && jdbcType == JdbcType.VARCHAR) {
                    valueToUse = DateFormatUtils.format((Date) valueToUse, mapping.getPattern());
                }

                if (valueToUse instanceof String && jdbcType == JdbcType.VARCHAR) {
                    String stringValue = (String) valueToUse;
                    if (!StringUtils.isEmpty(mapping.getEncoding())) {
                        if (!StringUtils.isEmpty(stringValue)) {
                            String[] encoding = StringUtils.split(mapping.getEncoding(), ">");
                            try {
                                if (encoding.length == 2)
                                    valueToUse = new String(stringValue.getBytes(encoding[0]), encoding[1]);
                                else if (encoding.length == 1)
                                    valueToUse = new String(stringValue.getBytes(), encoding[0]);

                            } catch (UnsupportedEncodingException e) {
                                LOG.error(e);
                            }
                        }
                    }
                }

                if (valueToUse == null)
                    ps.setNull(mapping.getIndex(), jdbcType.TYPE_CODE);
                else
                    ps.setObject(mapping.getIndex(), valueToUse, jdbcType.TYPE_CODE);
            }
        }

        public int getBatchSize() {
            return rows.size();
        }
    });
    int sum = 0;
    for (int c : cnt) {
        sum = sum + c;
    }
    return sum;
}

From source file:com.glaf.core.web.springmvc.FileUploadController.java

@ResponseBody
@RequestMapping("/upload")
public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/plain;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    String serviceKey = request.getParameter("serviceKey");
    String responseType = request.getParameter("responseType");
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String type = req.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }/*from  w w  w . j  a v a  2  s.  c o  m*/
    int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
    if (maxUploadSize == 0) {
        maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
    }
    maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;

    /**
     * ?maxDiskSize,5MB
     */
    int maxDiskSize = conf.getInt(serviceKey + ".maxDiskSize", 0);
    if (maxDiskSize == 0) {
        maxDiskSize = conf.getInt("upload.maxDiskSize", 1024 * 1024 * 2);// 2MB
    }

    logger.debug("maxUploadSize:" + maxUploadSize);
    String uploadDir = Constants.UPLOAD_PATH;
    InputStream inputStream = null;
    try {
        PrintWriter out = response.getWriter();
        Map<String, MultipartFile> fileMap = req.getFileMap();
        Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
        for (Entry<String, MultipartFile> entry : entrySet) {
            MultipartFile mFile = entry.getValue();
            logger.debug("fize size:" + mFile.getSize());
            if (mFile.getOriginalFilename() != null && mFile.getSize() > 0 && mFile.getSize() < maxUploadSize) {
                String filename = mFile.getOriginalFilename();
                logger.debug("upload file:" + filename);
                logger.debug("fize size:" + mFile.getSize());
                String fileId = UUID32.getUUID();

                // ????
                String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                        autoCreatedDateDirByParttern);
                String rootDir = SystemProperties.getConfigRootPath();
                if (!rootDir.endsWith(String.valueOf(File.separatorChar))) {
                    rootDir = rootDir + File.separatorChar;
                }
                File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                if (!savePath.exists()) {
                    savePath.mkdirs();
                }

                String fileName = savePath + "/" + fileId;

                BlobItem dataFile = new BlobItemEntity();
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setFileId(fileId);
                dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                dataFile.setFilename(mFile.getOriginalFilename());
                dataFile.setName(mFile.getOriginalFilename());
                dataFile.setContentType(mFile.getContentType());
                dataFile.setType(type);
                dataFile.setStatus(0);
                dataFile.setServiceKey(serviceKey);
                if (mFile.getSize() <= maxDiskSize) {
                    dataFile.setData(mFile.getBytes());
                }
                blobService.insertBlob(dataFile);
                dataFile.setData(null);

                if (mFile.getSize() > maxDiskSize) {
                    FileUtils.save(fileName, inputStream);
                    logger.debug(fileName + " save ok.");
                }

                if (StringUtils.equalsIgnoreCase(responseType, "json")) {
                    StringBuilder json = new StringBuilder();
                    json.append("{");
                    json.append("'");
                    json.append("fileId");
                    json.append("':'");
                    json.append(fileId);
                    json.append("'");
                    Enumeration<String> pNames = request.getParameterNames();
                    String pName;
                    while (pNames.hasMoreElements()) {
                        json.append(",");
                        pName = (String) pNames.nextElement();
                        json.append("'");
                        json.append(pName);
                        json.append("':'");
                        json.append(request.getParameter(pName));
                        json.append("'");
                    }
                    json.append("}");
                    logger.debug(json.toString());
                    response.getWriter().write(json.toString());
                } else {
                    out.print(fileId);
                }
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:gtu._work.ui.RenameUI.java

private Object[] getXFile(XFile f, String newName) {
    if (newName == null) {
        newName = f.fileName;/*from   w w w  . j av a  2 s  .  co  m*/
    }
    return new Object[] { f, newName, DateFormatUtils.format(f.file.lastModified(), "yyyy/MM/dd HH:mm:ss") };
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.table.BaseTableJdbcSourceIT.java

protected static String getStringRepOfFieldValueForInsert(Field field) {
    switch (field.getType()) {
    case BYTE_ARRAY:
        //Do a hex encode.
        return Hex.encodeHexString(field.getValueAsByteArray());
    case BYTE://from   w  ww. j  a v  a  2 s. c  o m
        return String.valueOf(field.getValueAsInteger());
    case TIME:
        return DateFormatUtils.format(field.getValueAsDate(), "HH:mm:ss.SSS");
    case DATE:
        return DateFormatUtils.format(field.getValueAsDate(), "yyyy-MM-dd");
    case DATETIME:
        return DateFormatUtils.format(field.getValueAsDate(), "yyyy-MM-dd HH:mm:ss.SSS");
    case ZONED_DATETIME:
        return DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
                .format(field.getValueAsZonedDateTime().toInstant().toEpochMilli());
    default:
        return String.valueOf(field.getValue());
    }
}

From source file:gtu._work.ui.RenameUI.java

private void usePatternNewNameBtnActionPerformed() {
    try {//from   w ww. j  a v  a  2 s .  c o m
        String findFileRegex = Validate.notBlank(findFileRegexText.getText(), "??Regex");
        String renameRegex = Validate.notBlank(renameRegexText.getText(), "??");
        Pattern renameRegexPattern = Pattern.compile("\\#(\\w+)\\#");
        Matcher matcher2 = null;

        Pattern findFileRegexPattern = Pattern.compile(findFileRegex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = null;
        DefaultTableModel model = JTableUtil.createModel(false, "??", "??", "");

        int ind = 1;
        for (XFile f : fileList) {
            matcher = findFileRegexPattern.matcher(f.fileName);
            if (matcher.matches()) {
                StringBuffer sb = new StringBuffer();
                matcher2 = renameRegexPattern.matcher(renameRegex);
                while (matcher2.find()) {
                    String val = matcher2.group(1);
                    if (val.matches("\\d+L")) {
                        int index = Integer.parseInt(val.substring(0, val.length() - 1));
                        matcher2.appendReplacement(sb, DateFormatUtils
                                .format(Long.parseLong(matcher.group(index)), "yyyyMMdd_HHmmss"));
                    } else if (val.equalsIgnoreCase("date")) {
                        matcher2.appendReplacement(sb,
                                DateFormatUtils.format(f.file.lastModified(), "yyyyMMdd_HHmmss"));
                    } else if (val.equalsIgnoreCase("serial")) {
                        matcher2.appendReplacement(sb, String.valueOf(ind++));
                    } else if (StringUtils.isNumeric(val)) {
                        int index = Integer.parseInt(val);
                        matcher2.appendReplacement(sb, matcher.group(index));
                    }
                }
                matcher2.appendTail(sb);
                model.addRow(this.getXFile(f, sb.toString()));
            }
        }
        renameTable.setModel(model);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:edu.virginia.iath.oxygenplugins.dateparser.helpers.SNACDate.java

private String formattedDate(Calendar d) {
    return (d == null) ? "null" : DateFormatUtils.format(d.getTime(), outputFormat);
}

From source file:cn.mypandora.util.MyDateUtils.java

/**
 * ./*from   w  ww .  j  a v a 2 s .c  om*/
 *
 * @param begin  .
 * @param end   ? .
 * @return
 */
public static List<String> getDaysListBetweenDates(String begin, String end) {
    List<String> dateList = new ArrayList<String>();
    Date d1;
    Date d2;
    try {
        d1 = DateUtils.parseDate(begin, DATE_FORMAT);
        d2 = DateUtils.parseDate(end, DATE_FORMAT);
        if (d1.compareTo(d2) > 0) {
            return dateList;
        }
        do {
            dateList.add(DateFormatUtils.format(d1, DATE_FORMAT));
            d1 = DateUtils.addDays(d1, 1);
        } while (d1.compareTo(d2) <= 0);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateList;
}

From source file:architecture.common.adaptor.connector.jdbc.AbstractJdbcConnector.java

protected Object deliver(final String queryString, final List<ParameterMapping> parameterMappings,
        final Map<String, Object> row) {

    // log.debug("delivering : 1");

    return getJdbcTemplate().update(queryString, new PreparedStatementSetter() {

        public void setValues(PreparedStatement ps) throws SQLException {

            for (ParameterMapping mapping : parameterMappings) {
                JdbcType jdbcType = mapping.getJdbcType();
                Object value = row.get(mapping.getProperty());
                Object valueToUse = value;

                if (valueToUse == null && mapping.getJavaType() == Date.class) {
                    valueToUse = new Date();
                }/* w  ww  . j  a v  a 2s.  c  om*/
                if (valueToUse instanceof Date && jdbcType == JdbcType.VARCHAR) {
                    valueToUse = DateFormatUtils.format((Date) valueToUse, mapping.getPattern());
                }

                if (valueToUse instanceof String && jdbcType == JdbcType.VARCHAR) {
                    String stringValue = (String) valueToUse;
                    if (!StringUtils.isEmpty(mapping.getEncoding())) {
                        if (!StringUtils.isEmpty(stringValue)) {
                            String[] encoding = StringUtils.split(mapping.getEncoding(), ">");
                            try {
                                if (encoding.length == 2)
                                    valueToUse = new String(stringValue.getBytes(encoding[0]), encoding[1]);
                                else if (encoding.length == 1)
                                    valueToUse = new String(stringValue.getBytes(), encoding[0]);
                            } catch (UnsupportedEncodingException e) {
                                LOG.error(e);
                            }
                        }
                    }
                }

                if (valueToUse == null)
                    ps.setNull(mapping.getIndex(), jdbcType.TYPE_CODE);
                else
                    ps.setObject(mapping.getIndex(), valueToUse, jdbcType.TYPE_CODE);
            }

        }
    });
}

From source file:cn.mypandora.util.MyDateUtils.java

/**
 * /*from   ww  w .ja  v a 2  s  .c  o  m*/
 *
 * @param begin
 * @param end
 * @return
 */
public static List<String> getMonthsListBetweenDates(String begin, String end) {
    List<String> dateList = new ArrayList<String>();
    Date d1;
    Date d2;
    try {
        d1 = DateUtils.parseDate(begin, DATE_FORMAT);
        d2 = DateUtils.parseDate(end, DATE_FORMAT);
        if (d1.compareTo(d2) > 0) {
            return dateList;
        }
        do {
            dateList.add(DateFormatUtils.format(d1, MONTH_FORMAT));
            d1 = DateUtils.addMonths(d1, 1);
        } while (d1.compareTo(d2) <= 0);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateList;
}