org.apache.commons.lang3.time.DateFormatUtils Java Examples

The following examples show how to use org.apache.commons.lang3.time.DateFormatUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TimeConvertForm.java    From MooTool with MIT License 6 votes vote down vote up
public static void init() {
    timeConvertForm = getInstance();

    ThreadUtil.execute(() -> {
        while (true) {
            timeConvertForm.getCurrentTimestampLabel().setText(String.valueOf(System.currentTimeMillis() / 1000));
            timeConvertForm.getCurrentGmtLabel().setText(DateFormatUtils.format(new Date(), TIME_FORMAT));
            ThreadUtil.safeSleep(1000);
        }
    });

    if ("".equals(timeConvertForm.getTimestampTextField().getText())) {
        timeConvertForm.getTimestampTextField().setText(String.valueOf(System.currentTimeMillis()));
    }
    if ("".equals(timeConvertForm.getGmtTextField().getText())) {
        timeConvertForm.getGmtTextField().setText(DateFormatUtils.format(new Date(), TIME_FORMAT));
    }

    timeConvertForm.getTimeConvertPanel().updateUI();
}
 
Example #2
Source File: FilesGenerator.java    From QuickProject with Apache License 2.0 6 votes vote down vote up
public void generate() throws GlobalConfigException {
    Configuration cfg = new Configuration();
    File tmplDir = globalConfig.getTmplFile();
    try {
        cfg.setDirectoryForTemplateLoading(tmplDir);
    } catch (IOException e) {
        throw new GlobalConfigException("tmplPath", e);
    }
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    for (Module module : modules) {
        logger.debug("module:" + module.getName());
        for (Bean bean : module.getBeans()) {
            logger.debug("bean:" + bean.getName());
            Map dataMap = new HashMap();
            dataMap.put("bean", bean);
            dataMap.put("module", module);
            dataMap.put("generate", generate);
            dataMap.put("config", config);
            dataMap.put("now", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));

            generate(cfg, dataMap);
        }
    }
}
 
Example #3
Source File: SpdxDocument.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param documentContainer
 * @param node
 * @throws InvalidSPDXAnalysisException
 */
public SpdxDocument(SpdxDocumentContainer documentContainer, Node node)
		throws InvalidSPDXAnalysisException {
	super(documentContainer, node);
	this.documentContainer = documentContainer;
	getMyPropertiesFromModel();
	if (this.getCreationInfo() == null){
		String licenseListVersion = ListedLicenses.getListedLicenses().getLicenseListVersion();
		String creationDate = DateFormatUtils.format(Calendar.getInstance(), SpdxRdfConstants.SPDX_DATE_FORMAT);
		SPDXCreatorInformation creationInfo = new SPDXCreatorInformation(new String[] {  }, creationDate, null, licenseListVersion);
		setCreationInfo(creationInfo);
	}
	else if (StringUtils.isBlank(this.getCreationInfo().getLicenseListVersion())){
		this.getCreationInfo().setLicenseListVersion(ListedLicenses.getListedLicenses().getLicenseListVersion());
	}

}
 
Example #4
Source File: OpenTest.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 文件上传接口测试
 */
@Test
public void fileuploadTest() throws IOException {
    //入参
    String appid = "670";
    String appsecret = "cPs6euPuvtsru2I3vmYb2Q";
    String partnerApplyNo = JadyerUtil.randomNumeric(16);
    String filepath = "D:\\JavaSE\\Picture\\Wallpaper\\观海云远.jpg";
    String reqURL = "http://127.0.0.1/open/router/rest";
    //调用
    Map<String, String> dataMap = new HashMap<>();
    dataMap.put("partnerApplyNo", partnerApplyNo);
    Map<String, String> paramMap = new HashMap<>();
    paramMap.put("appid", appid);
    paramMap.put("version", SeedConstants.OPEN_VERSION_21);
    paramMap.put("method", SeedConstants.OPEN_METHOD_boot_file_upload);
    paramMap.put("timestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
    paramMap.put("data", CodecUtil.buildAESEncrypt(JSON.toJSONString(dataMap), appsecret));
    HTTPUtil.upload(reqURL, "观海云远.jpg", FileUtils.openInputStream(new File(filepath)), "fileData", paramMap);
}
 
Example #5
Source File: BaseTableJdbcSourceIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected static String getStringRepOfFieldValueForInsert(Field field) {
  switch (field.getType()) {
    case BYTE_ARRAY:
      //Do a hex encode.
      return Hex.encodeHexString(field.getValueAsByteArray());
    case BYTE:
      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());
  }
}
 
Example #6
Source File: OpenTest.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 申请单查询接口
 */
@Test
public void loanGetViaAES(){
    //入参
    String appid = "770";
    String appsecret = "PDlTxZ8Vql5Y8owPSU6hzw";
    String applyNo = JadyerUtil.randomNumeric(16);
    String partnerApplyNo = JadyerUtil.randomNumeric(16);
    String reqURL = "http://127.0.0.1/open/router/rest";
    //调用
    Map<String, String> dataMap = new HashMap<>();
    dataMap.put("applyNo", applyNo);
    dataMap.put("partnerApplyNo", partnerApplyNo);
    Map<String, String> paramMap = new HashMap<>();
    paramMap.put("appid", appid);
    paramMap.put("version", SeedConstants.OPEN_VERSION_21);
    paramMap.put("method", SeedConstants.OPEN_METHOD_boot_loan_get);
    paramMap.put("timestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
    paramMap.put("data", CodecUtil.buildAESEncrypt(JSON.toJSONString(dataMap), appsecret));
    String respData = HTTPUtil.post(reqURL, JSON.toJSONString(paramMap), "application/json; charset=UTF-8");
    Map<String, String> respMap = JSON.parseObject(respData, new TypeReference<Map<String, String>>(){});
    if("0".equals(respMap.get("code"))){
        System.out.println("解密后的明文为-->" + CodecUtil.buildAESDecrypt(respMap.get("data"), appsecret));
    }
}
 
Example #7
Source File: HistoryItemScoreReportContentQueryUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
public static List<String> getLineChartCategories(String dateVal, int dataSize) throws Exception {
	List<String> categories = new LinkedList<String>();
	if (dataSize < 0) {
		throw new ServiceException("data-size error!");
	}		
	Date endDate = DateUtils.parseDate(dateVal, new String[]{"yyyyMMdd"});
	int dateRange = dataSize -1;
	if (dateRange < 0) {
		dateRange = 0;
	}
	if (dateRange == 0) {
		categories.add( DateFormatUtils.format(endDate, "yyyy/MM/dd") );
		return categories;
	}
	Date startDate = DateUtils.addDays(endDate, (dateRange * -1) );
	for (int i=0; i<dataSize; i++) {
		Date currentDate = DateUtils.addDays(startDate, i);
		String currentDateStr = DateFormatUtils.format(currentDate, "yyyy/MM/dd");
		categories.add(currentDateStr);
	}
	return categories;
}
 
Example #8
Source File: JPARealmTest.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void loginTest() throws SignatureException {
    Subject subject = SecurityUtils.getSubject();

    String date = DateFormatUtils.SMTP_DATETIME_FORMAT.format(new Date());

    String resource = "/questionnaires/58";
    String method = "GET";
    String stringToSign = new StringBuilder().append(method).append(" ").append(resource).append("\n").append(date)
            .toString();
    String apiKey = "B868UOHUTKUDWXM";
    String secret = "IQO27YUZO8NJ7RADIK6SJ9BQZNYP4EMO";
    String signature = HMACSignature.calculateRFC2104HMAC(stringToSign, secret);

    AuthenticationToken token = new HmacAuthToken.Builder().apiKey(apiKey).signature(signature).dateUTC(date)
            .message(stringToSign).build();
    subject.login(token);

    assertThat(subject.getPrincipal()).isInstanceOf(User.class);
    assertThat(subject.getPrincipal()).isEqualTo(User.with().id(3).build());

    boolean isPermitted = subject.isPermitted("questionnaire:read:58");
    assertThat(isPermitted).isTrue();
}
 
Example #9
Source File: ImageListener.java    From MooTool with MIT License 6 votes vote down vote up
/**
 * save for manual
 */
private static void saveImage() {
    if (StringUtils.isEmpty(selectedName)) {
        selectedName = "未命名_" + DateFormatUtils.format(new Date(), "yyyy-MM-dd_HH-mm-ss");
    }
    String name = JOptionPane.showInputDialog("名称", selectedName);
    if (StringUtils.isNotBlank(name)) {
        try {
            if (selectedImage != null) {
                File imageFile = FileUtil.touch(new File(IMAGE_PATH_PRE_FIX + name + ".png"));
                ImageIO.write(ImageUtil.toBufferedImage(selectedImage), "png", imageFile);
                ImageForm.initListTable();
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(App.mainFrame, "保存失败!\n\n" + ex.getMessage(), "失败", JOptionPane.ERROR_MESSAGE);
            log.error(ExceptionUtils.getStackTrace(ex));
        }
    }
}
 
Example #10
Source File: WatermarkController.java    From kbase-doc with Apache License 2.0 5 votes vote down vote up
/**
 * 输出文件demo https://o7planning.org/en/11765/spring-boot-file-download-example
 * @author eko.zhan at 2018年9月2日 下午4:26:10
 * @param file
 * @param text
 * @param color
 * @return
 * @throws IOException
 */
@ApiOperation(value="传入文件并返回水印文件", response=ResponseMessage.class)
@ApiImplicitParams({
        @ApiImplicitParam(name="file", value="待添加水印的文件", dataType="__file", required=true, paramType="form"),
        @ApiImplicitParam(name="text", value="水印内容", dataType="string", required=false, paramType="form"),
        @ApiImplicitParam(name="color", value="颜色码,以#开头", dataType="string", required=false, paramType="form")
})
@PostMapping("/handle")
public ResponseEntity<ByteArrayResource> handle(@RequestParam("file") MultipartFile file, @RequestParam(value="text", required=false) String text, @RequestParam(value="color", required=false) String color) throws IOException {
	if (!file.getOriginalFilename().toLowerCase().endsWith(".docx")) {
		log.error("上传的文件必须是 docx 类型");
	}
	File dir = ResourceUtils.getFile("classpath:static/DATAS");
	String pardir = DateFormatUtils.format(new Date(), "yyyyMMdd");
	String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "." + FilenameUtils.getExtension(file.getOriginalFilename());
	File originFile = new File(dir + "/" + pardir + "/" + filename);
	FileUtils.copyInputStreamToFile(file.getInputStream(), originFile);
	byte[] bytes = watermarkService.handle(originFile, text, color);
	ByteArrayResource resource = new ByteArrayResource(bytes);
	return ResponseEntity.ok()
			// Content-Disposition
			.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + originFile.getName())
			// Content-Type
			.contentType(getMediaType(originFile.getName()))
			// Contet-Length
			.contentLength(bytes.length)
			.body(resource);
}
 
Example #11
Source File: OnlineEditorController.java    From es with Apache License 2.0 5 votes vote down vote up
@RequestMapping("compress")
public String compress(
        @RequestParam(value = "parentPath") String parentPath,
        @RequestParam(value = "paths") String[] paths,
        RedirectAttributes redirectAttributes) throws IOException {


    String rootPath = sc.getRealPath(ROOT_DIR);
    parentPath = URLDecoder.decode(parentPath, Constants.ENCODING);

    Date now = new Date();
    String pattern = "yyyyMMddHHmmss";

    String compressPath = parentPath + File.separator + "[系统压缩]" + DateFormatUtils.format(now, pattern) + "-" + System.nanoTime() + ".zip";

    for(int i = 0, l = paths.length; i < l; i++) {
        String path = paths[i];
        path = URLDecoder.decode(path, Constants.ENCODING);
        paths[i] = rootPath + File.separator + path;
    }

    try {
        CompressUtils.zip(rootPath + File.separator + compressPath, paths);
        String msg = "压缩成功,<a href='%s/%s?path=%s' target='_blank' class='btn btn-primary'>点击下载</a>,下载完成后,请手工删除生成的压缩包";
        redirectAttributes.addFlashAttribute(Constants.MESSAGE,
                String.format(msg,
                        sc.getContextPath(),
                        viewName("download"),
                        URLEncoder.encode(compressPath, Constants.ENCODING)));

    } catch (Exception e) {
        redirectAttributes.addFlashAttribute(Constants.ERROR, e.getMessage());
    }

    redirectAttributes.addAttribute("path", URLEncoder.encode(parentPath, Constants.ENCODING));
    return redirectToUrl(viewName("list"));
}
 
Example #12
Source File: AppServiceImpl.java    From Moss with Apache License 2.0 5 votes vote down vote up
private static Duration durationBuilder() {
    Date endDate = new Date();
    String end = DateFormatUtils.format(endDate, "yyyy-MM-dd HHmm");
    Date StartDate = DateUtils.addMinutes(endDate, -15);
    String start = DateFormatUtils.format(StartDate, "yyyy-MM-dd HHmm");

    Duration duration = new Duration();
    duration.setStart(start);
    duration.setEnd(end);
    duration.setStep("MINUTE");
    return duration;
}
 
Example #13
Source File: FileUtils.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件到指定路径
 *
 * @param file     文件
 * @param filePath 路径
 * @return 文件信息
 */
public static File upload(MultipartFile file, String filePath) {
    //校验文件名大小
    int fileNameLength = file.getOriginalFilename().length();
    if (fileNameLength > DEFAULT_FILE_NAME_LENGTH) {
        throw new FileNameLengthLimitExceededException(DEFAULT_FILE_NAME_LENGTH);
    }

    String name = getFileNameNoExtension(file.getOriginalFilename());
    String suffix = getExtensionName(file.getOriginalFilename());
    String nowStr = DateFormatUtils.format(new Date(), "yyyyMMddhhmmss");
    try {
        String fileName = name + nowStr + "." + suffix;
        String path = filePath + fileName;
        //getCanonicalPath会将文件路径解析为与操作系统相关的唯一的规范形式的字符串,而getAbsolutePath并不会
        File dest = new File(path).getCanonicalFile();
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        // 文件写入
        file.transferTo(dest);
        return dest;
    } catch (IOException e) {
        log.error("上传文件出错,{}", e.getMessage());
    }
    return null;
}
 
Example #14
Source File: WxMaAnalysisServiceImplTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVisitDistribution() throws Exception {
  final WxMaAnalysisService service = wxMaService.getAnalysisService();
  Date twoDaysAgo = DateUtils.addDays(new Date(), -2);
  WxMaVisitDistribution distribution = service.getVisitDistribution(twoDaysAgo, twoDaysAgo);
  assertNotNull(distribution);
  String date = DateFormatUtils.format(twoDaysAgo, "yyyyMMdd");
  assertEquals(date, distribution.getRefDate());
  assertTrue(distribution.getList().containsKey("access_source_session_cnt"));
  assertTrue(distribution.getList().containsKey("access_staytime_info"));
  assertTrue(distribution.getList().containsKey("access_depth_info"));
  System.out.println(distribution);
}
 
Example #15
Source File: DateUtils.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * 格式化日期为日期字符串<br>
 * 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 = TIMESTAMP_PATTERN;
    if (patterns != null && patterns.length > 0
            && StringUtils.isNotBlank(patterns[0])) {
        pattern = patterns[0];
    }
    return DateFormatUtils.format(date, pattern);
}
 
Example #16
Source File: BaseWorkTime.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean inDefinedHoliday(Calendar c) {
	if (ArrayUtils.isNotEmpty(this.definedHolidays)) {
		if (ArrayUtils.indexOf(this.definedHolidays,
				DateFormatUtils.format(c, DATEPARTFORMATPATTERN[0])) > ArrayUtils.INDEX_NOT_FOUND) {
			return true;
		}
	}
	return false;
}
 
Example #17
Source File: MailTemplateHelpers.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public String humanizeTimestamp(long timestamp) {
  if (taskDatePattern.isPresent() && timeZone.isPresent()) {
    return DateFormatUtils.format(timestamp, taskDatePattern.get(), timeZone.get());
  } else if (taskDatePattern.isPresent()) {
    return DateFormatUtils.formatUTC(timestamp, taskDatePattern.get());
  } else if (timeZone.isPresent()) {
    return DateFormatUtils.format(timestamp, DEFAULT_TIMESTAMP_FORMAT, timeZone.get());
  } else {
    return DateFormatUtils.format(timestamp, DEFAULT_TIMESTAMP_FORMAT);
  }
}
 
Example #18
Source File: DateUtils.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * 格式化日期为指定格式<br>
 * generate by: vakin jiang at 2012-3-7
 * 
 * @param orig
 * @param patterns
 * @return
 */
public static Date formatDate(Date orig, String... patterns) {
    String pattern = TIMESTAMP_PATTERN;
    if (patterns != null && patterns.length > 0
            && StringUtils.isNotBlank(patterns[0])) {
        pattern = patterns[0];
    }
    return parseDate(DateFormatUtils.format(orig, pattern));
}
 
Example #19
Source File: ImageRenameHandler.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * 根据配置重新设置 imageName
 *
 * @param data          the data
 * @param imageIterator the image iterator
 * @param markdownImage the markdown image
 * @return the boolean
 */
@Override
public void invoke(EventData data, Iterator<MarkdownImage> imageIterator, MarkdownImage markdownImage) {

    String imageName = markdownImage.getImageName();
    MikState state = MikPersistenComponent.getInstance().getState();
    // 处理文件名有空格导致上传 gif 变为静态图的问题
    imageName = imageName.replaceAll("\\s*", "");
    int sufixIndex = state.getSuffixIndex();
    Optional<SuffixEnum> sufix = EnumsUtils.getEnumObject(SuffixEnum.class, e -> e.getIndex() == sufixIndex);
    SuffixEnum suffixEnum = sufix.orElse(SuffixEnum.FILE_NAME);
    switch (suffixEnum) {
        case FILE_NAME:
            break;
        case DATE_FILE_NAME:
            // 删除原来的时间前缀
            imageName = imageName.replace(DateFormatUtils.format(new Date(), "yyyy-MM-dd-"), "");
            imageName =  DateFormatUtils.format(new Date(), "yyyy-MM-dd-") + imageName;
            break;
        case RANDOM:
            if(!imageName.startsWith(PREFIX)){
                imageName = PREFIX + CharacterUtils.getRandomString(6) + ImageUtils.getFileExtension(imageName);
            }
            break;
        default:
            break;
    }

    markdownImage.setImageName(imageName);
}
 
Example #20
Source File: StringUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 创建一个随机数.
 *
 * @return 随机六位数+当前时间yyyyMMddHHmmss
 */
public static String randomCodeUtil() {
    String cteateTime = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
    int num = RandomUtils.nextInt(100000, 1000000);
    String result = cteateTime + StringUtils.leftPad(num + "", 6, "0");
    return result;
}
 
Example #21
Source File: QssController.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 验证动态密码是否正确(每个动态密码有效期为10分钟)
 */
private void verifyDynamicPassword(String dynamicPassword){
    if(StringUtils.isBlank(dynamicPassword)){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "动态密码不能为空");
    }
    if(!dynamicPassword.contains("jadyer")){
        String timeFlag = DateFormatUtils.format(new Date(), "HHmm").substring(0, 3) + "0";
        String generatePassword = DigestUtils.md5Hex(timeFlag + "https://jadyer.cn/" + timeFlag);
        if(!generatePassword.equals(dynamicPassword)){
            throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "动态密码不正确");
        }
    }
}
 
Example #22
Source File: DateTimeUtil.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * 动态表示方式的时间差函数
 *
 * @param startDate
 *            指定时间
 * @param endDate
 *            结束时间
 * @return 时间差指定格式字符串
 */
public static String dynDiff(Date startDate, Date endDate) {

    String startDay = DateFormatUtils.format(startDate, "dd");
    String endtDay = DateFormatUtils.format(endDate, "dd");
    String value = "";
    if (startDay.equals(endtDay)) {
        value = DateFormatUtils.format(startDate, " HH:mm");
    } else {
        value = otherDiff(startDate, endDate);
    }
    return value;
}
 
Example #23
Source File: DateTimeUtil.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * 资源表示方式的时间差函数
 *
 * @param startDate
 *            指定时间
 * @param endDate
 *            结束时间
 * @return 时间差指定格式字符串
 */
public static String resDiff(Date startDate, Date endDate) {
    Object[] obj = timeDifference(startDate, endDate);
    String value = "";
    if (Long.parseLong(obj[3].toString()) > 7) {
        value = DateFormatUtils.format(startDate, "yyyy-MM-dd HH:mm");
    } else {
        value = otherDiff(startDate, endDate);
    }
    return value;
}
 
Example #24
Source File: DefaultEventcheckReceiver.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
private void initReceiverTimes(){
    todayStartTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
    todayEndTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59");
    allStartTime = DateFormatUtils.format(new Date(), "10000-01-01  00:00:00");
    allEndTime = DateFormatUtils.format(new Date(), "9999-12-31  23:59:59");
    nowStartTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
}
 
Example #25
Source File: EventCheckSender.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
@Override
public boolean sendMsg(int jobId, Properties props, Logger log) {
        boolean result = false;
        PreparedStatement pstmt = null;
        Connection msgConn = null;
        String sendTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sqlForSendMsg = "INSERT INTO event_queue (sender,send_time,topic,msg_name,msg,send_ip) VALUES(?,?,?,?,?,?)";
        try {
            String vIP = getLinuxLocalIp(log);
            msgConn = getEventCheckerConnection(props,log);
            if(msgConn==null) return false;
            pstmt = msgConn.prepareCall(sqlForSendMsg);
            pstmt.setString(1, sender);
            pstmt.setString(2, sendTime);
            pstmt.setString(3, topic);
            pstmt.setString(4, msgName);
            pstmt.setString(5, msg);
            pstmt.setString(6, vIP);
            int rs = pstmt.executeUpdate();
            if (rs == 1) {
                result = true;
                log.info("Send msg success!");
            } else {
                log.error("Send msg failed for update database!");
            }
        } catch (SQLException e) {
            throw new RuntimeException("Send EventChecker msg failed!" + e);
        } finally {
            closeQueryStmt(pstmt, log);
            closeConnection(msgConn, log);
        }
        return result;
}
 
Example #26
Source File: UtilTest.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * FTP上传测试
 */
@Test
public void FTPUtilForUploadTest() throws IOException {
    //InputStream is = FileUtils.openInputStream(new File("E:\\Wallpaper\\三大名迹.jpg"));
    //String remoteURL = "/mytest/02/03/" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg";
    //Assert.assertTrue(FTPUtil.upload("192.168.2.60", "ftpupload", "HUvueMGWg92y8SSN", remoteURL, is));
    //is = FileUtils.openInputStream(new File("E:\\Wallpaper\\Wentworth.Miller.jpg"));
    //remoteURL = "/mytest/02/03/" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss_2") + ".jpg";
    //Assert.assertTrue(FTPUtil.upload("192.168.2.60", "ftpupload", "HUvueMGWg92y8SSN", remoteURL, is));
    //FTPUtil.logout();
    InputStream is = FileUtils.openInputStream(new File("F:\\Tool\\Enterprise_Architect_8.0.858.zip"));
    String remoteURL = "/mytest/02/03/" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg";
    Assert.assertTrue(FTPUtil.uploadAndLogout("192.168.2.60", "ftpupload", "HUvueMGWg92y8SSN", remoteURL, is));
}
 
Example #27
Source File: ClockStamp.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private Date stamp(String memo) {
	Date date = new Date();
	long total = date.getTime() - start.getTime();
	Log pre = logs.get(logs.size() - 1);
	long elapsed = date.getTime() - pre.getDate().getTime();
	System.out.println(
			"ClockStamp(" + this.name + ") start at(" + DateFormatUtils.format(date, FORMAT) + "), arrived(" + memo
					+ ") total(" + total + ")ms, form(" + pre.getMemo() + ") elapsed(" + elapsed + ")ms.");
	Log log = new Log(memo, date, elapsed);
	logs.add(log);
	return date;
}
 
Example #28
Source File: EhcacheMonitorController.java    From es with Apache License 2.0 5 votes vote down vote up
@RequestMapping("{cacheName}/{key}/details")
@ResponseBody
public Object keyDetail(
        @PathVariable("cacheName") String cacheName,
        @PathVariable("key") String key,
        Model model
) {

    Element element = cacheManager.getCache(cacheName).get(key);


    String dataPattern = "yyyy-MM-dd hh:mm:ss";
    Map<String, Object> data = Maps.newHashMap();
    data.put("objectValue", element.getObjectValue().toString());
    data.put("size", PrettyMemoryUtils.prettyByteSize(element.getSerializedSize()));
    data.put("hitCount", element.getHitCount());

    Date latestOfCreationAndUpdateTime = new Date(element.getLatestOfCreationAndUpdateTime());
    data.put("latestOfCreationAndUpdateTime", DateFormatUtils.format(latestOfCreationAndUpdateTime, dataPattern));
    Date lastAccessTime = new Date(element.getLastAccessTime());
    data.put("lastAccessTime", DateFormatUtils.format(lastAccessTime, dataPattern));
    if(element.getExpirationTime() == Long.MAX_VALUE) {
        data.put("expirationTime", "不过期");
    } else {
        Date expirationTime = new Date(element.getExpirationTime());
        data.put("expirationTime", DateFormatUtils.format(expirationTime, dataPattern));
    }

    data.put("timeToIdle", element.getTimeToIdle());
    data.put("timeToLive", element.getTimeToLive());
    data.put("version", element.getVersion());

    return data;

}
 
Example #29
Source File: LookoutMeasurement.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
private StringBuilder map2json(StringBuilder stringBuilder, Map<String, Object> map) {
    if (!map.isEmpty()) {
        int size = map.size();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            //key print
            stringBuilder.append(QUOTE).append(entry.getKey()).append(QUOTE).append(COLON);
            //key:tags,tags:value
            if (entry.getValue() instanceof Map) {
                stringBuilder.append(BRACES_LEFT);
                map2json(stringBuilder, (Map<String, Object>) entry.getValue());
                stringBuilder.append(BRACES_RIGHT);
            }
            //key:time,time:value
            else if (entry.getValue() instanceof Date) {
                String timestamp = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
                    .format((Date) (entry.getValue()));
                stringBuilder.append(QUOTE).append(timestamp).append(QUOTE);
            }
            //value:number
            else if (entry.getValue() instanceof Number) {
                stringBuilder.append(entry.getValue());
            } else {
                stringBuilder.append(QUOTE)
                    .append(StringEscapeUtils.escapeJson(entry.getValue().toString()))
                    .append(QUOTE);
            }
            if (--size > 0) {
                stringBuilder.append(COMMA);
            }
        }
    }
    return stringBuilder;
}
 
Example #30
Source File: JarManagerService.java    From DBus with Apache License 2.0 5 votes vote down vote up
private void uploadStormJars(String user, String host, String port, String homePath, String category, String type, String jarName) {
    long time = System.currentTimeMillis();
    String minorVersion = StringUtils.join(new String[]{DateFormatUtils.format(time, "yyyyMMdd"), DateFormatUtils.format(time, "HHmmss")}, "_");
    String savePath = StringUtils.join(new String[]{homePath, KeeperConstants.RELEASE_VERSION, type, minorVersion}, "/");
    String cmd = MessageFormat.format("ssh -p {0} {1}@{2} mkdir -pv {3}", port, user, host, savePath);
    logger.info("mdkir command: {}", cmd);
    int retVal = execCmd(cmd, null);
    if (retVal == 0) {
        logger.info("mkdir success.");
        File file = new File(SystemUtils.getUserDir() + "/../extlib/" + jarName);
        cmd = MessageFormat.format("scp -P {0} {1} {2}@{3}:{4}", port, file.getPath(), user, host, savePath + "/" + jarName);
        logger.info("scp command: {}", cmd);
        retVal = execCmd(cmd, null);
        if (retVal == 0) {
            logger.info("scp success.");
        }
    }
    TopologyJar topologyJar = new TopologyJar();
    topologyJar.setName(jarName);
    topologyJar.setCategory(category);
    topologyJar.setVersion(KeeperConstants.RELEASE_VERSION);
    topologyJar.setType(type);
    topologyJar.setMinorVersion(minorVersion);
    topologyJar.setPath(savePath + "/" + jarName);
    topologyJar.setCreateTime(new Date());
    topologyJar.setUpdateTime(new Date());
    topologyJarMapper.insert(topologyJar);
}