下面列出了怎么用org.apache.commons.lang.time.FastDateFormat的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Lists all logins with their assigned sessions
*/
public static Map<String, List<Object>> getLoginToSessionIDMappings() {
FastDateFormat sessionCreatedDateFormatter = FastDateFormat.getInstance(DateUtil.PRETTY_FORMAT);
Map<String, List<Object>> result = new TreeMap<>();
for (Entry<String, HttpSession> entry : loginMapping.entrySet()) {
HttpSession session = entry.getValue();
UserDTO user = (UserDTO) session.getAttribute(AttributeNames.USER);
List<Object> sessionInfo = new LinkedList<>();
sessionInfo.add(user.getFirstName());
sessionInfo.add(user.getLastName());
sessionInfo.add(new Date(session.getLastAccessedTime()));
sessionInfo.add(sessionCreatedDateFormatter.format(new Date(session.getCreationTime())));
sessionInfo.add(session.getId());
result.put(entry.getKey(), sessionInfo);
}
return result;
}
@Override
public void configure(Context context) {
String dateFormatString = context.getString(DATE_FORMAT);
String timeZoneString = context.getString(TIME_ZONE);
if (StringUtils.isBlank(dateFormatString)) {
dateFormatString = DEFAULT_DATE_FORMAT;
}
if (StringUtils.isBlank(timeZoneString)) {
timeZoneString = DEFAULT_TIME_ZONE;
}
fastDateFormat = FastDateFormat.getInstance(dateFormatString,
TimeZone.getTimeZone(timeZoneString));
indexPrefix = context.getString(ElasticSearchHighSinkConstants.INDEX_NAME);
}
@Override
@SuppressWarnings("deprecation")
public void update(ClusterStats item) {
try {
numBlacklistedTrackers = item.getStatus().getBlacklistedTrackers();
numActiveTrackers = item.getStatus().getTaskTrackers();
maxMapTasks = item.getStatus().getMaxMapTasks();
maxReduceTasks = item.getStatus().getMaxReduceTasks();
} catch (Exception e) {
long time = System.currentTimeMillis();
LOG.info("Error in processing cluster status at "
+ FastDateFormat.getInstance().format(time));
}
}
@Override
@SuppressWarnings("deprecation")
public void update(ClusterStats item) {
try {
numBlacklistedTrackers = item.getStatus().getBlacklistedTrackers();
numActiveTrackers = item.getStatus().getTaskTrackers();
maxMapTasks = item.getStatus().getMaxMapTasks();
maxReduceTasks = item.getStatus().getMaxReduceTasks();
} catch (Exception e) {
long time = System.currentTimeMillis();
LOG.info("Error in processing cluster status at "
+ FastDateFormat.getInstance().format(time));
}
}
@Override
public void configure(Context context) {
String dateFormatString = context.getString(DATE_FORMAT);
String timeZoneString = context.getString(TIME_ZONE);
if (StringUtils.isBlank(dateFormatString)) {
dateFormatString = DEFAULT_DATE_FORMAT;
}
if (StringUtils.isBlank(timeZoneString)) {
timeZoneString = DEFAULT_TIME_ZONE;
}
fastDateFormat = FastDateFormat.getInstance(dateFormatString,
TimeZone.getTimeZone(timeZoneString));
indexPrefix = context.getString(ElasticSearchSinkConstants.INDEX_NAME);
}
@Override
public void configure(Context context) {
String dateFormatString = context.getString(DATE_FORMAT);
String timeZoneString = context.getString(TIME_ZONE);
if (StringUtils.isBlank(dateFormatString)) {
dateFormatString = DEFAULT_DATE_FORMAT;
}
if (StringUtils.isBlank(timeZoneString)) {
timeZoneString = DEFAULT_TIME_ZONE;
}
fastDateFormat = FastDateFormat.getInstance(dateFormatString,
TimeZone.getTimeZone(timeZoneString));
indexPrefix = context.getString(ElasticSearchSinkConstants.INDEX_NAME);
}
@VisibleForTesting
FastDateFormat getFastDateFormat() {
return fastDateFormat;
}
protected EventSerializerIndexRequestBuilderFactory(
ElasticSearchEventSerializer serializer, FastDateFormat fdf) {
super(fdf);
this.serializer = serializer;
}
@VisibleForTesting
FastDateFormat getFastDateFormat() {
return fastDateFormat;
}
/**
* Constructor for subclasses
* @param fastDateFormat {@link FastDateFormat} to use for index names
*/
protected AbstractElasticSearchIndexRequestBuilderFactory(
FastDateFormat fastDateFormat) {
this.fastDateFormat = fastDateFormat;
}
/**
* {@inheritDoc}
*/
@Override
public boolean changesSince(SCMRevision revision, @NonNull OutputStream changeLogStream)
throws UnsupportedOperationException, IOException, InterruptedException {
if (Objects.equals(getRevision(), revision)) {
// special case where somebody is asking one of two stupid questions:
// 1. what has changed between the latest and the latest
// 2. what has changed between the current revision and the current revision
return false;
}
int count = 0;
FastDateFormat iso = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZ");
StringBuilder log = new StringBuilder(1024);
String endHash;
if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) {
endHash = ((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash().toLowerCase(Locale.ENGLISH);
} else {
endHash = null;
}
// this is the format expected by GitSCM, so we need to format each GHCommit with the same format
// commit %H%ntree %T%nparent %P%nauthor %aN <%aE> %ai%ncommitter %cN <%cE> %ci%n%n%w(76,4,4)%s%n%n%b
for (GHCommit commit: repo.queryCommits().from(ref).pageSize(GitSCM.MAX_CHANGELOG).list()) {
if (commit.getSHA1().toLowerCase(Locale.ENGLISH).equals(endHash)) {
break;
}
log.setLength(0);
log.append("commit ").append(commit.getSHA1()).append('\n');
log.append("tree ").append(commit.getTree().getSha()).append('\n');
log.append("parent");
for (String parent: commit.getParentSHA1s()) {
log.append(' ').append(parent);
}
log.append('\n');
GHCommit.ShortInfo info = commit.getCommitShortInfo();
log.append("author ")
.append(info.getAuthor().getName())
.append(" <")
.append(info.getAuthor().getEmail())
.append("> ")
.append(iso.format(info.getAuthoredDate()))
.append('\n');
log.append("committer ")
.append(info.getCommitter().getName())
.append(" <")
.append(info.getCommitter().getEmail())
.append("> ")
.append(iso.format(info.getCommitDate()))
.append('\n');
log.append('\n');
String msg = info.getMessage();
if (msg.endsWith("\r\n")) {
msg = msg.substring(0, msg.length() - 2);
} else if (msg.endsWith("\n")) {
msg = msg.substring(0, msg.length() - 1);
}
msg = msg.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\n ");
log.append(" ").append(msg).append('\n');
changeLogStream.write(log.toString().getBytes(StandardCharsets.UTF_8));
changeLogStream.flush();
count++;
if (count >= GitSCM.MAX_CHANGELOG) {
break;
}
}
return count > 0;
}
public static Format getDateFormatter(String pattern) {
return DateUtil.DEFAULT_DATE_FORMAT.equals(pattern)
? DateUtil.DEFAULT_DATE_FORMATTER
: FastDateFormat.getInstance(pattern, DateUtil.DEFAULT_TIME_ZONE);
}
public static Format getTimeFormatter(String pattern) {
return DateUtil.DEFAULT_TIME_FORMAT.equals(pattern)
? DateUtil.DEFAULT_TIME_FORMATTER
: FastDateFormat.getInstance(pattern, DateUtil.DEFAULT_TIME_ZONE);
}
public static Format getTimestampFormatter(String pattern) {
return DateUtil.DEFAULT_TIMESTAMP_FORMAT.equals(pattern)
? DateUtil.DEFAULT_TIMESTAMP_FORMATTER
: FastDateFormat.getInstance(pattern, DateUtil.DEFAULT_TIME_ZONE);
}
private static String getFormatString(Date date, FastDateFormat format){
String formatString = format.format(date);
return extractDateTime(formatString);
}
protected EventSerializerIndexRequestBuilderFactory(
ElasticSearchEventSerializer serializer, FastDateFormat fdf) {
super(fdf);
this.serializer = serializer;
}
/**
* Constructor for subclasses
* @param fastDateFormat {@link FastDateFormat} to use for index names
*/
protected AbstractElasticSearchIndexRequestBuilderFactory(
FastDateFormat fastDateFormat) {
this.fastDateFormat = fastDateFormat;
}
public CustomElasticSearchIndexRequestBuilderFactory() {
super(FastDateFormat.getInstance("HH_mm_ss_SSS",
TimeZone.getTimeZone("EST5EDT")));
}
protected EventSerializerIndexRequestBuilderFactory(
ElasticSearchEventSerializer serializer, FastDateFormat fdf) {
super(fdf);
this.serializer = serializer;
}
@VisibleForTesting
FastDateFormat getFastDateFormat() {
return fastDateFormat;
}
/**
* Constructor for subclasses
* @param fastDateFormat {@link FastDateFormat} to use for index names
*/
protected AbstractElasticSearchIndexRequestBuilderFactory(
FastDateFormat fastDateFormat) {
this.fastDateFormat = fastDateFormat;
}
public CustomElasticSearchIndexRequestBuilderFactory() {
super(FastDateFormat.getInstance("HH_mm_ss_SSS",
TimeZone.getTimeZone("EST5EDT")));
}
public static Format getDateFormatter(String pattern) {
return DateUtil.DEFAULT_DATE_FORMAT.equals(pattern) ? DateUtil.DEFAULT_DATE_FORMATTER : FastDateFormat.getInstance(pattern, DateUtil.DATE_TIME_ZONE);
}
/**
* Formats a commit into the raw format.
*
* @param commit
* Commit to format.
* @param parent
* Optional parent commit to produce the diff against. This only matters
* for merge commits, and git-log/git-whatchanged/etc behaves differently with respect to this.
*/
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE",
justification = "Windows git implementation requires specific line termination")
void format(RevCommit commit, RevCommit parent, PrintWriter pw, Boolean useRawOutput) throws IOException {
if (parent!=null)
pw.printf("commit %s (from %s)\n", commit.name(), parent.name());
else
pw.printf("commit %s\n", commit.name());
pw.printf("tree %s\n", commit.getTree().name());
for (RevCommit p : commit.getParents())
pw.printf("parent %s\n",p.name());
FastDateFormat iso = FastDateFormat.getInstance(ISO_8601);
PersonIdent a = commit.getAuthorIdent();
pw.printf("author %s <%s> %s\n", a.getName(), a.getEmailAddress(), iso.format(a.getWhen()));
PersonIdent c = commit.getCommitterIdent();
pw.printf("committer %s <%s> %s\n", c.getName(), c.getEmailAddress(), iso.format(c.getWhen()));
// indent commit messages by 4 chars
String msg = commit.getFullMessage();
if (msg.endsWith("\n")) msg=msg.substring(0,msg.length()-1);
msg = msg.replace("\n","\n ");
msg="\n "+msg+"\n";
pw.println(msg);
// see man git-diff-tree for the format
try (Repository repo = getRepository();
ObjectReader or = repo.newObjectReader();
TreeWalk tw = new TreeWalk(or)) {
if (parent != null) {
/* Caller provided a parent commit, use it */
tw.reset(parent.getTree(), commit.getTree());
} else {
if (commit.getParentCount() > 0) {
/* Caller failed to provide parent, but a parent
* is available, so use the parent in the walk
*/
tw.reset(commit.getParent(0).getTree(), commit.getTree());
} else {
/* First commit in repo has 0 parent count, but
* the TreeWalk requires exactly two nodes for its
* walk. Use the same node twice to satisfy
* TreeWalk. See JENKINS-22343 for details.
*/
tw.reset(commit.getTree(), commit.getTree());
}
}
tw.setRecursive(true);
tw.setFilter(TreeFilter.ANY_DIFF);
final RenameDetector rd = new RenameDetector(repo);
rd.reset();
rd.addAll(DiffEntry.scan(tw));
List<DiffEntry> diffs = rd.compute(or, null);
if (useRawOutput) {
for (DiffEntry diff : diffs) {
pw.printf(":%06o %06o %s %s %s\t%s",
diff.getOldMode().getBits(),
diff.getNewMode().getBits(),
diff.getOldId().name(),
diff.getNewId().name(),
statusOf(diff),
diff.getChangeType()==ChangeType.ADD ? diff.getNewPath() : diff.getOldPath());
if (hasNewPath(diff)) {
pw.printf(" %s",diff.getNewPath()); // copied to
}
pw.println();
pw.println();
}
}
}
}
/**
* Format given date using given format pattern.
*
* @param date the date to format
* @param pattern the pattern to use ({@link SimpleDateFormat})
* @return the resulting string
*/
public static String format(Date date, String pattern) {
FastDateFormat formatter = FastDateFormat.getInstance(pattern);
return formatter.format(date);
}
/**
* Format given date using given format pattern and locale
*
* @param date the date to format
* @param pattern the pattern to use ({@link SimpleDateFormat})
* @return the resulting string
*/
public static String format(Date date, String pattern, Locale locale) {
FastDateFormat formatter = FastDateFormat.getInstance(pattern, locale);
return formatter.format(date);
}