下面列出了怎么用org.apache.commons.lang.time.DurationFormatUtils的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) throws GerbilException, IOException {
Indexer index = new Indexer(OUTPUT_FOLDER);
SimpleDateFormat format = new SimpleDateFormat();
Date start = Calendar.getInstance().getTime();
LOGGER.info("Start indexing at {}", format.format(start));
if (args[0].equals("-ram")) {
indexStreamMem(index, args[1]);
} else if (args[0].equals("-sf")) {
indexSortedFile(index, args[1]);
} else {
indexStream(index, args[0]);
}
index.close();
Date end = Calendar.getInstance().getTime();
LOGGER.info("Indexing finished at {}", format.format(end));
LOGGER.info("Indexing took: " + DurationFormatUtils.formatDurationHMS(end.getTime() - start.getTime()));
}
protected static String getQueueFirstMessageAgeAsString(Session jSession,
String queueName, long currentTime) {
try {
long age = getQueueFirstMessageAge(jSession, queueName, null,
currentTime, false);
if (age == -2) {
return "??";
} else if (age == -1) {
return null;
} else {
return DurationFormatUtils.formatDuration(age, "ddd-HH:mm:ss");
}
} catch (JMSException e) {
return "?";
}
}
public static String getAge(long value) {
long currentTime = (new Date()).getTime();
long age = currentTime - value;
String ageString = DurationFormatUtils.formatDuration(age, "d") + "d";
if ("0d".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "H") + "h";
if ("0h".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "m") + "m";
if ("0m".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "s") + "s";
if ("0s".equals(ageString)) {
ageString = age + "ms";
}
}
}
}
return ageString;
}
@Override
public void onTick(long l) {
if (l > 0) {
mTimeStr = DurationFormatUtils.formatDuration(l, mTimePattern);
//这是apache中的common的lang包中DurationFormatUtils类中的formatDuration,通过传入
//一个时间格式就会自动将倒计时转换成相应的mTimePattern的样式(HH:mm:ss或dd天HH时mm分ss秒)
setBackgroundSpan(mTimeStr);
}
}
private boolean shouldDefer() {
/* If revocationTimeMs == 0, this is an immediate uncache request.
* No clients were anchored at the time we made the request. */
if (revocationTimeMs == 0) {
return false;
}
/* Let's check if any clients still have this block anchored. */
boolean anchored =
!dataset.datanode.getShortCircuitRegistry().
processBlockMunlockRequest(key);
if (!anchored) {
LOG.debug("Uncaching {} now that it is no longer in use " +
"by any clients.", key);
return false;
}
long delta = revocationTimeMs - Time.monotonicNow();
if (delta < 0) {
LOG.warn("Forcibly uncaching {} after {} " +
"because client(s) {} refused to stop using it.", key,
DurationFormatUtils.formatDurationHMS(revocationTimeMs),
dataset.datanode.getShortCircuitRegistry().getClientNames(key));
return false;
}
LOG.info("Replica {} still can't be uncached because some " +
"clients continue to use it. Will wait for {}", key,
DurationFormatUtils.formatDurationHMS(delta));
return true;
}
private String format(long avgDuration) {
String formatted = null;
if (avgDuration>0) {
int days = (int) (avgDuration / SECONDS_DAY);
long lessThanDay = (avgDuration % SECONDS_DAY);
formatted = days + ":" +
DurationFormatUtils.formatDuration(lessThanDay*1000, "HH:mm:ss:SS");
} else {
formatted = 0 + ":" +
DurationFormatUtils.formatDuration(0, "HH:mm:ss:SS");
}
return formatted;
}
private String format(long avgDuration) {
String formatted = null;
if (avgDuration>0) {
int days = (int) (avgDuration / SECONDS_DAY);
long lessThanDay = (avgDuration % SECONDS_DAY);
formatted = days + ":" +
DurationFormatUtils.formatDuration(lessThanDay*1000, "HH:mm:ss:SS");
} else {
formatted = 0 + ":" +
DurationFormatUtils.formatDuration(0, "HH:mm:ss:SS");
}
return formatted;
}
private String format(long avgDuration) {
String formatted = null;
if (avgDuration>0) {
int days = (int) (avgDuration / SECONDS_DAY);
long lessThanDay = (avgDuration % SECONDS_DAY);
formatted = days + ":" +
DurationFormatUtils.formatDuration(lessThanDay*1000, "HH:mm:ss:SS");
} else {
formatted = 0 + ":" +
DurationFormatUtils.formatDuration(0, "HH:mm:ss:SS");
}
return formatted;
}
private String format(long avgDuration) {
String formatted = null;
if (avgDuration>0) {
int days = (int) (avgDuration / SECONDS_DAY);
long lessThanDay = (avgDuration % SECONDS_DAY);
formatted = days + ":" +
DurationFormatUtils.formatDuration(lessThanDay*1000, "HH:mm:ss:SS");
} else {
formatted = 0 + ":" +
DurationFormatUtils.formatDuration(0, "HH:mm:ss:SS");
}
return formatted;
}
private boolean shouldDefer() {
/* If revocationTimeMs == 0, this is an immediate uncache request.
* No clients were anchored at the time we made the request. */
if (revocationTimeMs == 0) {
return false;
}
/* Let's check if any clients still have this block anchored. */
boolean anchored =
!dataset.datanode.getShortCircuitRegistry().
processBlockMunlockRequest(key);
if (!anchored) {
LOG.debug("Uncaching {} now that it is no longer in use " +
"by any clients.", key);
return false;
}
long delta = revocationTimeMs - Time.monotonicNow();
if (delta < 0) {
LOG.warn("Forcibly uncaching {} after {} " +
"because client(s) {} refused to stop using it.", key,
DurationFormatUtils.formatDurationHMS(revocationTimeMs),
dataset.datanode.getShortCircuitRegistry().getClientNames(key));
return false;
}
LOG.info("Replica {} still can't be uncached because some " +
"clients continue to use it. Will wait for {}", key,
DurationFormatUtils.formatDurationHMS(delta));
return true;
}
@Override
public void onTick(long l) {
if (l > 0) {
mTimeStr = DurationFormatUtils.formatDuration(l, mTimePattern);
//这是apache中的common的lang包中DurationFormatUtils类中的formatDuration,通过传入
//一个时间格式就会自动将倒计时转换成相应的mTimePattern的样式(HH:mm:ss或dd天HH时mm分ss秒)
setBackgroundSpan(mTimeStr);
}
}
private void report() {
long duration = this.endTime - this.startTime;
if (duration == 0) {
return;
}
println("errors found: %s", this.errors);
println("duration: %s", DurationFormatUtils.formatDurationHMS(duration));
println("speed: %d/sec", this.count * 1000 / duration);
}
public static String duration(Duration d) {
String result = null;
if (d != null) {
long ms = d.toMillis();
if (ms >= 0) {
result = DurationFormatUtils.formatDuration(ms, "HH:mm:ss");
}
else {
result = DurationFormatUtils.formatDuration(-ms, "-HH:mm:ss");
}
}
return result;
}
protected void updateTimestamp(long timestamp) {
if (timestamp == currentTime)
return;
currentTime = timestamp;
String formatDurationHMS = DurationFormatUtils.formatDuration(timestamp,
(timestamp == 0 ? "--:--:--.---" : "HH:mm:ss.SSS"), true);
timeLabel.setText(formatDurationHMS);
getParent().layout();
}
protected String getReadableSimulationTime(long timestamp) {
long days = TimeUnit.MILLISECONDS.toDays(timestamp);
long hours = TimeUnit.MILLISECONDS.toHours(timestamp);
long minutes = TimeUnit.MILLISECONDS.toMinutes(timestamp);
long seconds = TimeUnit.MILLISECONDS.toSeconds(timestamp);
return DurationFormatUtils.formatDuration(timestamp,
(days > 0 ? "dd 'days '" : "") + (hours > 0 ? "HH 'hours '" : "") + (minutes > 0 ? "mm 'minutes '" : "")
+ (seconds > 0 ? "ss 'seconds '" : ""),
false);
}
private static void indexSortedFile(Indexer index, String file) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
String old = null;
//long total = 0; has never been used
long size = 0;
long rounds = 0;
Date start = Calendar.getInstance().getTime();
Set<String> sameAsBlock = new HashSet<String>();
while ((line = br.readLine()) != null) {
String[] split = line.split("\\s+");
String node1 = split[0];
String node2 = split[2];
if (node1.equals(old)) {
sameAsBlock.add(node2.toString());
} else if (old != null) {
// Enitity is finished
index.index(old.toString(), sameAsBlock);
// total += sameAsBlock.size();
sameAsBlock.clear();
// Add Uri
sameAsBlock.add(node2.toString());
old = node1;
} else {
// First run
sameAsBlock.add(node2.toString());
old = node1;
}
size++;
if (size % 1000000 == 0) {
Date end = Calendar.getInstance().getTime();
rounds++;
String avgTime = DurationFormatUtils.formatDurationHMS((end.getTime() - start.getTime()) / rounds);
LOGGER.info("Got 1000000 triples...(Sum: {}, AvgTime: {})", size, avgTime);
}
}
}
}
public static void main(String[] args) throws GerbilException, IOException {
Indexer index = Indexer.create(OUTPUT_FOLDER);
SimpleDateFormat format = new SimpleDateFormat();
Date start = Calendar.getInstance().getTime();
LOGGER.info("Start indexing at {}", format.format(start));
indexStream(index, DBPEDIA_DUMP);
index.close();
Date end = Calendar.getInstance().getTime();
LOGGER.info("Indexing finished at {}", format.format(end));
LOGGER.info("Indexing took: " + DurationFormatUtils.formatDurationHMS(end.getTime() - start.getTime()));
}
public String getLastRan() {
long now = new Date().getTime();
long then = getStartDate().getTime();
long distance = now - then;
return DurationFormatUtils.formatDurationWords(distance, true, true)
.replace("hour","h")
.replace("hs", "h")
.replace("minute", "m")
.replace("ms", "m")
.replace("second", "s")
.replace("ss", "s");
}
synchronized void uncacheBlock(String bpid, long blockId) {
ExtendedBlockId key = new ExtendedBlockId(blockId, bpid);
Value prevValue = mappableBlockMap.get(key);
boolean deferred = false;
if (!dataset.datanode.getShortCircuitRegistry().
processBlockMunlockRequest(key)) {
deferred = true;
}
if (prevValue == null) {
LOG.debug("Block with id {}, pool {} does not need to be uncached, "
+ "because it is not currently in the mappableBlockMap.", blockId,
bpid);
numBlocksFailedToUncache.incrementAndGet();
return;
}
switch (prevValue.state) {
case CACHING:
LOG.debug("Cancelling caching for block with id {}, pool {}.", blockId,
bpid);
mappableBlockMap.put(key,
new Value(prevValue.mappableBlock, State.CACHING_CANCELLED));
break;
case CACHED:
mappableBlockMap.put(key,
new Value(prevValue.mappableBlock, State.UNCACHING));
if (deferred) {
LOG.debug("{} is anchored, and can't be uncached now. Scheduling it " +
"for uncaching in {} ",
key, DurationFormatUtils.formatDurationHMS(revocationPollingMs));
deferredUncachingExecutor.schedule(
new UncachingTask(key, revocationMs),
revocationPollingMs, TimeUnit.MILLISECONDS);
} else {
LOG.debug("{} has been scheduled for immediate uncaching.", key);
uncachingExecutor.execute(new UncachingTask(key, 0));
}
break;
default:
LOG.debug("Block with id {}, pool {} does not need to be uncached, "
+ "because it is in state {}.", blockId, bpid, prevValue.state);
numBlocksFailedToUncache.incrementAndGet();
break;
}
}
synchronized void uncacheBlock(String bpid, long blockId) {
ExtendedBlockId key = new ExtendedBlockId(blockId, bpid);
Value prevValue = mappableBlockMap.get(key);
boolean deferred = false;
if (!dataset.datanode.getShortCircuitRegistry().
processBlockMunlockRequest(key)) {
deferred = true;
}
if (prevValue == null) {
LOG.debug("Block with id {}, pool {} does not need to be uncached, "
+ "because it is not currently in the mappableBlockMap.", blockId,
bpid);
numBlocksFailedToUncache.incrementAndGet();
return;
}
switch (prevValue.state) {
case CACHING:
LOG.debug("Cancelling caching for block with id {}, pool {}.", blockId,
bpid);
mappableBlockMap.put(key,
new Value(prevValue.mappableBlock, State.CACHING_CANCELLED));
break;
case CACHED:
mappableBlockMap.put(key,
new Value(prevValue.mappableBlock, State.UNCACHING));
if (deferred) {
LOG.debug("{} is anchored, and can't be uncached now. Scheduling it " +
"for uncaching in {} ",
key, DurationFormatUtils.formatDurationHMS(revocationPollingMs));
deferredUncachingExecutor.schedule(
new UncachingTask(key, revocationMs),
revocationPollingMs, TimeUnit.MILLISECONDS);
} else {
LOG.debug("{} has been scheduled for immediate uncaching.", key);
uncachingExecutor.execute(new UncachingTask(key, 0));
}
break;
default:
LOG.debug("Block with id {}, pool {} does not need to be uncached, "
+ "because it is in state {}.", blockId, bpid, prevValue.state);
numBlocksFailedToUncache.incrementAndGet();
break;
}
}
public static String getDuration(Date dateBegin, Date dateEnd) {
return DurationFormatUtils.formatDuration(dateEnd.getTime()-dateBegin.getTime(), "HH:mm", true);
}
private String convertTimeMs(long timeMs) {
if (timeMs < 1000) {
return Long.toString(timeMs) + " msec";
}
return DurationFormatUtils.formatDuration(timeMs, "HH:mm:ss") + " HH:MM:SS";
}
private String convertTimeMs(long timeMs) {
if (timeMs < 1000) {
return Long.toString(timeMs) + " msec";
}
return DurationFormatUtils.formatDuration(timeMs, "HH:mm:ss") + " HH:MM:SS";
}
private static String format(long miliseconds)
{
return DurationFormatUtils.formatDuration(miliseconds, "mm:ss");
}
String formatDuration() {
return DurationFormatUtils.formatDurationHMS((long) (1000 * Double
.valueOf(duration).doubleValue()));
}
public static void index(Indexer indexer, String file) {
UriEncodingHandlingSameAsRetriever retriever = new UriEncodingHandlingSameAsRetriever();
LineIterator iterator = null;
long size = 0, rounds = 0;
try {
iterator = FileUtils.lineIterator(new File(file), "UTF-8");
String uri = null;
Set<String> uris;
String old = null;
Date start = Calendar.getInstance().getTime();
// iterate over the lines
while (iterator.hasNext()) {
String[] split = iterator.next().split("\\s+");
if (split.length > 2) {
// get the subject of the triple
uri = split[0];
if (uri.startsWith("<")) {
uri = uri.substring(1);
}
if (uri.endsWith(">")) {
uri = uri.substring(0, uri.length() - 1);
}
// if this subject is new
if (!uri.equals(old)) {
// retrieve other writings of this URI
uris = retriever.retrieveSameURIs(uri);
if (uris != null) {
for (String u : uris) {
indexer.index(u);
}
} else {
indexer.index(uri);
}
}
size++;
if (size % 100000 == 0) {
Date end = Calendar.getInstance().getTime();
rounds++;
String avgTime = DurationFormatUtils
.formatDurationHMS((end.getTime() - start.getTime()) / rounds);
LOGGER.info("Got 100000 entities...(Sum: {}, AvgTime: {})", size, avgTime);
}
}
}
} catch (IOException e) {
LOGGER.error("Exception while reading file. It will be ignored.", e);
} finally {
LineIterator.closeQuietly(iterator);
}
LOGGER.info("Successfully indexed {} triples", size);
}
protected void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource) {
Assert.assertNotNull("DataSource could not be located.", dataSource);
try {
StopWatch s = new StopWatch();
s.start();
new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(final TransactionStatus status) {
verifyTestEnvironment(dataSource);
return new JdbcTemplate(dataSource).execute(new StatementCallback() {
public Object doInStatement(Statement statement) throws SQLException {
String schemaName = statement.getConnection().getMetaData().getUserName().toUpperCase();
LOG.info("Clearing tables for schema " + schemaName);
if (StringUtils.isBlank(schemaName)) {
Assert.fail("Empty schema name given");
}
final List<String> reEnableConstraints = new ArrayList<String>();
DatabaseMetaData metaData = statement.getConnection().getMetaData();
Map<String, List<String[]>> exportedKeys = indexExportedKeys(metaData, schemaName);
final ResultSet resultSet = metaData.getTables(null, schemaName, null, new String[] { "TABLE" });
final StringBuilder logStatements = new StringBuilder();
while (resultSet.next()) {
String tableName = resultSet.getString("TABLE_NAME");
if (shouldTableBeCleared(tableName)) {
if (!isUsingDerby(metaData) && isUsingOracle(metaData)) {
List<String[]> exportedKeyNames = exportedKeys.get(tableName);
if (exportedKeyNames != null) {
for (String[] exportedKeyName : exportedKeyNames) {
final String fkName = exportedKeyName[0];
final String fkTableName = exportedKeyName[1];
final String disableConstraint = "ALTER TABLE " + fkTableName + " DISABLE CONSTRAINT " + fkName;
logStatements.append("Disabling constraints using statement ->" + disableConstraint + "<-\n");
statement.addBatch(disableConstraint);
reEnableConstraints.add("ALTER TABLE " + fkTableName + " ENABLE CONSTRAINT " + fkName);
}
}
} else if (isUsingMySQL(metaData)) {
statement.addBatch("SET FOREIGN_KEY_CHECKS = 0");
}
String deleteStatement = "DELETE FROM " + tableName;
logStatements.append("Clearing contents using statement ->" + deleteStatement + "<-\n");
statement.addBatch(deleteStatement);
}
}
for (final String constraint : reEnableConstraints) {
logStatements.append("Enabling constraints using statement ->" + constraint + "<-\n");
statement.addBatch(constraint);
}
if (isUsingMySQL(metaData)) {
statement.addBatch("SET FOREIGN_KEY_CHECKS = 1");
}
LOG.info(logStatements);
int[] results = statement.executeBatch();
for (int index = 0; index < results.length; index++) {
if (results[index] == Statement.EXECUTE_FAILED) {
Assert.fail("Execution of database clear statement failed.");
}
}
resultSet.close();
LOG.info("Tables successfully cleared for schema " + schemaName);
return null;
}
});
}
});
s.stop();
LOG.info("Time to clear tables: " + DurationFormatUtils.formatDurationHMS(s.getTime()));
} catch (Exception e) {
LOG.error(e);
throw new RuntimeException(e);
}
}
public static String formatMsForLog(long ms) {
//return LOG_TIME_FORMAT.format(new Date(ms));
return DurationFormatUtils.formatDuration(ms, "H:mm:ss.S");
}
/**
* This method logs the duration information for a given message.
* @param message
* @param duration
*/
public static void logDuration(String message, long duration) {
LOG.info(message + ": " + DurationFormatUtils.formatDurationHMS(duration) + " (" + duration+ " ms)");
}