下面列出了org.joda.time.format.DateTimeFormatter#print ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Output the date in an appropriate ISO8601 format.
* <p>
* This method will output the partial in one of two ways.
* If {@link #getFormatter()}
* <p>
* If there is no appropriate ISO format a dump of the fields is output
* via {@link #toStringList()}.
*
* @return ISO8601 formatted string
*/
public String toString() {
DateTimeFormatter[] f = iFormatter;
if (f == null) {
getFormatter();
f = iFormatter;
if (f == null) {
return toStringList();
}
}
DateTimeFormatter f1 = f[1];
if (f1 == null) {
return toStringList();
}
return f1.print(this);
}
/**
* Generate parameters for JVM Heap dump
*
* @param scriptName
* @param jvm
* @return
*/
private ExecCommand getExecCommandForHeapDump(String scriptName, Jvm jvm) {
final String trimmedJvmName = StringUtils.deleteWhitespace(jvm.getJvmName());
final String jvmRootDir = Paths.get(jvm.getTomcatMedia().getRemoteDir().toString() + '/' + trimmedJvmName + '/' +
jvm.getTomcatMedia().getRootDir()).normalize().toString();
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd.HHmmss");
final String dumpFile = "heapDump." + trimmedJvmName + "." + formatter.print(DateTime.now());
final String dumpLiveStr = ApplicationProperties.getAsBoolean(PropertyKeys.JMAP_DUMP_LIVE_ENABLED.name()) ? "live," : "\"\"";
final String heapDumpDir = jvm.getTomcatMedia().getRemoteDir().normalize().toString() + "/" + jvm.getJvmName();
return new ExecCommand(getFullPathScript(jvm, scriptName), jvm.getJavaHome(), heapDumpDir, dumpFile,
dumpLiveStr , jvmRootDir, jvm.getJvmName());
}
/**
* Output the date in an appropriate ISO8601 format.
* <p>
* This method will output the partial in one of two ways.
* If {@link #getFormatter()}
* <p>
* If there is no appropriate ISO format a dump of the fields is output
* via {@link #toStringList()}.
*
* @return ISO8601 formatted string
*/
public String toString() {
DateTimeFormatter[] f = iFormatter;
if (f == null) {
getFormatter();
f = iFormatter;
if (f == null) {
return toStringList();
}
}
DateTimeFormatter f1 = f[1];
if (f1 == null) {
return toStringList();
}
return f1.print(this);
}
/**
* Assumes a PreparedInput with only a single chunk. Multi-Chunk documents
* should never be stored.
*
* Mentions will be aligned to the tokens present in the document according
* to their character offset and length.
*
* @param writer
* @throws IOException
*/
public void writeTo(BufferedWriter writer) throws IOException {
writer.write("-DOCSTART- (");
writer.write(docId_.replace('/', '_'));
writer.write(")");
if (timestamp_ != 0) {
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC();
String timeString = fmt.print(timestamp_);
writer.write("\t" + timeString);
}
writer.newLine();
int currentToken = 0;
if (chunks_.size() > 1 || chunks_.size() == 0) {
throw new IllegalStateException("AIDA disk formats do not support " + "chunked documents. This document contains " + chunks_.size() + "cunks.");
}
PreparedInputChunk chunk = chunks_.get(0);
// Align mentions to underlying tokens.
setTokensPositions(chunk.getConceptMentions(), chunk.getTokens());
setTokensPositions(chunk.getNamedEntityMentions(), chunk.getTokens());
for (Map<Integer, Mention> innerMap : getMentions().getMentions().values()) {
for (Mention mention : innerMap.values()) {
// Write up to mention.
writeTokens(chunk.getTokens(), currentToken, mention.getStartToken(), writer);
currentToken = mention.getEndToken() + 1;
// Add mention.
writeTokensMention(chunk.getTokens(), mention, writer);
}
}
writeTokens(chunk.getTokens(), currentToken, chunk.getTokens().size(), writer);
}
@Override
public Object apply(Object input, Map<String, Object> args) {
if (input instanceof DateTime) {
String pattern = (String) args.get("format");
if (pattern == null) {
pattern = "MMMM d, Y, H:m";
}
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
return fmt.print((DateTime) input);
}
return "";
}
private static String changeFormatForDateTime(final DateTime inputDateTime, final String outFormat, final String outLocaleLang,
final String outLocaleCountry) {
if (DateTimeUtils.isUnix(outFormat)) {
Long timestamp = (long) Math.round(inputDateTime.getMillis() / Constants.Miscellaneous.THOUSAND_MULTIPLIER);
return timestamp.toString();
}
DateTimeFormatter outFormatter = DateTimeUtils.getDateFormatter(outFormat, outLocaleLang, outLocaleCountry);
return outFormatter.print(inputDateTime);
}
/**
* Test suspending a process definition on a certain date. POST repository/process-definitions/{processDefinitionId}
*/
@Deployment(resources = { "org/activiti/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testSuspendProcessDefinitionDelayed() throws Exception {
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
assertFalse(processDefinition.isSuspended());
ObjectNode requestNode = objectMapper.createObjectNode();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 2);
// Format the date using ISO date format
DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
String dateString = formatter.print(cal.getTimeInMillis());
requestNode.put("action", "suspend");
requestNode.put("date", dateString);
HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_DEFINITION, processDefinition.getId()));
httpPut.setEntity(new StringEntity(requestNode.toString()));
CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
// Check "OK" status
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertTrue(responseNode.get("suspended").booleanValue());
// Check if process-definition is not yet suspended
processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
assertFalse(processDefinition.isSuspended());
// Force suspension by altering time
cal.add(Calendar.HOUR, 1);
processEngineConfiguration.getClock().setCurrentTime(cal.getTime());
waitForJobExecutorToProcessAllJobs(5000, 100);
// Check if process-definition is suspended
processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
assertTrue(processDefinition.isSuspended());
}
@Test
public void shouldExtractAddHeadersUsingSpecifiedSerializer()
throws Exception {
long now = (System.currentTimeMillis() / 60000L) * 60000L;
String pattern = "yyyy-MM-dd HH:mm:ss,SSS";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String body = formatter.print(now);
System.out.println(body);
Context context = new Context();
// Skip the second group
context.put(RegexExtractorInterceptor.REGEX,
"^(\\d\\d\\d\\d-\\d\\d-\\d\\d\\s\\d\\d:\\d\\d)(:\\d\\d,\\d\\d\\d)");
context.put(RegexExtractorInterceptor.SERIALIZERS, "s1 s2");
String millisSerializers = RegexExtractorInterceptorMillisSerializer.class.getName();
context.put(RegexExtractorInterceptor.SERIALIZERS + ".s1.type", millisSerializers);
context.put(RegexExtractorInterceptor.SERIALIZERS + ".s1.name", "timestamp");
context.put(RegexExtractorInterceptor.SERIALIZERS + ".s1.pattern", "yyyy-MM-dd HH:mm");
// Default type
context.put(RegexExtractorInterceptor.SERIALIZERS + ".s2.name", "data");
fixtureBuilder.configure(context);
Interceptor fixture = fixtureBuilder.build();
Event event = EventBuilder.withBody(body, Charsets.UTF_8);
Event expected = EventBuilder.withBody(body, Charsets.UTF_8);
expected.getHeaders().put("timestamp", String.valueOf(now));
expected.getHeaders().put("data", ":00,000");
Event actual = fixture.intercept(event);
Assert.assertArrayEquals(expected.getBody(), actual.getBody());
Assert.assertEquals(expected.getHeaders(), actual.getHeaders());
}
public static String getFromIsoDate(String aDate, String outputPattern, String language)
{
DateTime date;
try
{
date = getDateFromString(aDate, ISO_PATTERN_MIN, language);
}
catch ( Exception e )
{
date = getDateFromString(aDate, ISO_PATTERN, language);
}
DateTimeFormatter outputFormatter = getDateTimeFormatter(outputPattern, language);
return outputFormatter.print(date);
}
/**
* @param isNullable isNullable
* @param earliest lower boundary date
* @param latest upper boundary date
* @param onlyBusinessDays only business days
* @return a list of boundary dates
*/
public List<String> positiveCase(boolean isNullable, String earliest, String latest, boolean onlyBusinessDays) {
List<String> values = new LinkedList<>();
if (earliest.equalsIgnoreCase(latest)) {
values.add(earliest);
if (isNullable) {
values.add("");
}
return values;
}
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime earlyDate = parser.parseDateTime(earliest);
DateTime lateDate = parser.parseDateTime(latest);
String earlyDay = parser.print(earlyDate);
String nextDay = getNextDay(earlyDate.toString().substring(0, 10), onlyBusinessDays);
String prevDay = getPreviousDay(lateDate.toString().substring(0, 10), onlyBusinessDays);
String lateDay = parser.print(lateDate);
values.add(earlyDay);
values.add(nextDay);
values.add(prevDay);
values.add(lateDay);
if (isNullable) {
values.add("");
}
return values;
}
@JsonCreator
public IndexSuffixFormatter(
@JsonProperty("type") String type,
@JsonProperty("properties") Properties props) {
if (type == null) {
formatter = new Function<IndexInfo, String>() {
@Nullable
@Override
public String apply(@Nullable IndexInfo input) {
return "";
}
};
} else if (type.equals("date")) {
final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(props.getProperty("dateFormat"));
formatter = new Function<IndexInfo, String>() {
@Nullable
@Override
public String apply(@Nullable IndexInfo input) {
return dateTimeFormatter.print(input.getTimestamp());
}
};
} else {
throw new RuntimeException("unsupported type: " + type);
}
}
String toString(final Object source) {
final DateMidnight data = (DateMidnight) source;
final DateTimeFormatter printFormat = DateTimeFormat.forPattern(ISO_FORMAT);
final String date = printFormat.print(data);
return date;
}
@Test
@Deployment
public void testRepeatWithoutEnd() throws Throwable {
// We need to make sure the time ends on .000, .003 or .007 due to SQL Server rounding to that
Instant baseInstant = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusMillis(337);
// expect to stop boundary jobs after 20 minutes
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dt = new DateTime(new DateTime(baseInstant.plus(20, ChronoUnit.MINUTES).getEpochSecond()));
String dateStr = fmt.print(dt);
// reset the timer
Instant nextTimeInstant = baseInstant;
processEngineConfiguration.getClock().setCurrentTime(Date.from(nextTimeInstant));
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("repeatWithEnd");
runtimeService.setVariable(processInstance.getId(), "EndDateForBoundary", dateStr);
List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list();
assertThat(tasks)
.extracting(Task::getName)
.containsOnly("Task A");
// Test Boundary Events
// complete will cause timer to be created
taskService.complete(tasks.get(0).getId());
List<Job> jobs = managementService.createTimerJobQuery().list();
assertThat(jobs).hasSize(1);
// change the job in old mode (the configuration should not be json in
// "old mode" but a simple string).
TimerJobEntity job = (TimerJobEntity) jobs.get(0);
changeConfigurationToPlainText(job);
// boundary events
waitForJobExecutorToProcessAllJobs(7000, 100);
// a new job must be prepared because there are 10 repeats 2 seconds interval
jobs = managementService.createTimerJobQuery().list();
assertThat(jobs).hasSize(1);
for (int i = 0; i < 9; i++) {
nextTimeInstant = nextTimeInstant.plus(2, ChronoUnit.SECONDS);
processEngineConfiguration.getClock().setCurrentTime(Date.from(nextTimeInstant));
waitForJobExecutorToProcessAllJobs(7000, 100);
// a new job must be prepared because there are 10 repeats 2 seconds interval
jobs = managementService.createTimerJobQuery().list();
assertThat(jobs).hasSize(1);
}
nextTimeInstant = nextTimeInstant.plus(2, ChronoUnit.SECONDS);
processEngineConfiguration.getClock().setCurrentTime(Date.from(nextTimeInstant));
assertThatCode(() -> { waitForJobExecutorToProcessAllJobs(7000, 100); })
.as("Should not have any other jobs because the endDate is reached")
.doesNotThrowAnyException();
tasks = taskService.createTaskQuery().list();
assertThat(tasks)
.extracting(Task::getName)
.containsOnly("Task B");
taskService.complete(tasks.get(0).getId());
assertThatCode(() -> { waitForJobExecutorToProcessAllJobs(7000, 500); })
.as("No jobs should be active here.")
.doesNotThrowAnyException();
// now All the process instances should be completed
List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list();
assertThat(processInstances).isEmpty();
// no jobs
jobs = managementService.createJobQuery().list();
assertThat(jobs).isEmpty();
jobs = managementService.createTimerJobQuery().list();
assertThat(jobs).isEmpty();
// no tasks
tasks = taskService.createTaskQuery().list();
assertThat(tasks).isEmpty();
}
@Deployment
public void testRepeatWithoutEnd() throws Throwable {
Clock clock = processEngineConfiguration.getClock();
Calendar calendar = Calendar.getInstance();
Date baseTime = calendar.getTime();
calendar.add(Calendar.MINUTE, 20);
//expect to stop boundary jobs after 20 minutes
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dt = new DateTime(calendar.getTime());
String dateStr = fmt.print(dt);
//reset the timer
Calendar nextTimeCal = Calendar.getInstance();
nextTimeCal.setTime(baseTime);
clock.setCurrentCalendar(nextTimeCal);
processEngineConfiguration.setClock(clock);
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("repeatWithEnd");
runtimeService.setVariable(processInstance.getId(), "EndDateForBoundary", dateStr);
List<Task> tasks = taskService.createTaskQuery().list();
assertEquals(1, tasks.size());
Task task = tasks.get(0);
assertEquals("Task A", task.getName());
// Test Boundary Events
// complete will cause timer to be created
taskService.complete(task.getId());
List<Job> jobs = managementService.createTimerJobQuery().list();
assertEquals(1, jobs.size());
//boundary events
waitForJobExecutorToProcessAllJobs(2000, 200);
// a new job must be prepared because there are 10 repeats 2 seconds interval
for (int i = 0; i < 9; i++) {
nextTimeCal.add(Calendar.SECOND, 2);
clock.setCurrentCalendar(nextTimeCal);
processEngineConfiguration.setClock(clock);
waitForJobExecutorToProcessAllJobsAndExecutableTimerJobs(2000, 200);
}
nextTimeCal.add(Calendar.SECOND, 2);
clock.setCurrentCalendar(nextTimeCal);
processEngineConfiguration.setClock(clock);
waitForJobExecutorToProcessAllJobs(2000, 200);
// Should not have any other jobs because the endDate is reached
jobs = managementService.createTimerJobQuery().list();
assertEquals(0, jobs.size());
tasks = taskService.createTaskQuery().list();
task = tasks.get(0);
assertEquals("Task B", task.getName());
assertEquals(1, tasks.size());
taskService.complete(task.getId());
waitForJobExecutorToProcessAllJobs(2000, 200);
// now All the process instances should be completed
List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list();
assertEquals(0, processInstances.size());
// no jobs
jobs = managementService.createJobQuery().list();
assertEquals(0, jobs.size());
jobs = managementService.createTimerJobQuery().list();
assertEquals(0, jobs.size());
// no tasks
tasks = taskService.createTaskQuery().list();
assertEquals(0, tasks.size());
processEngineConfiguration.resetClock();
}
public void paymentAfter(DateTime date){
DateTimeFormatter format = DateTimeFormat.forPattern(CommonFormats.DATE_TIME);
super.setGreatedThan(PAYMENT_DATE, format.print(date));
}
/**
* Uses the specified formatter to convert this partial to a String.
*
* @param formatter the formatter to use, null means use <code>toString()</code>.
* @return the formatted string
* @since 1.1
*/
public String toString(DateTimeFormatter formatter) {
if (formatter == null) {
return toString();
}
return formatter.print(this);
}
/**
* Uses the specified formatter to convert this partial to a String.
*
* @param formatter the formatter to use, null means use <code>toString()</code>.
* @return the formatted string
* @since 1.1
*/
public String toString(DateTimeFormatter formatter) {
if (formatter == null) {
return toString();
}
return formatter.print(this);
}
/**
* Gson invokes this call-back method during serialization when it encounters a field of the
* specified type. <p>
*
* In the implementation of this call-back method, you should consider invoking
* {@link com.google.gson.JsonSerializationContext#serialize(Object, java.lang.reflect.Type)} method to create JsonElements for any
* non-trivial field of the {@code src} object. However, you should never invoke it on the
* {@code src} object itself since that will cause an infinite loop (Gson will call your
* call-back method again).
* @param src the object that needs to be converted to Json.
* @param typeOfSrc the actual type (fully genericized version) of the source object.
* @return a JsonElement corresponding to the specified object.
*/
@Override
public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context)
{
final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
return new JsonPrimitive(fmt.print(src));
}
/**
* Gson invokes this call-back method during serialization when it encounters a field of the
* specified type. <p>
*
* In the implementation of this call-back method, you should consider invoking
* {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
* non-trivial field of the {@code src} object. However, you should never invoke it on the
* {@code src} object itself since that will cause an infinite loop (Gson will call your
* call-back method again).
* @param src the object that needs to be converted to Json.
* @param typeOfSrc the actual type (fully genericized version) of the source object.
* @return a JsonElement corresponding to the specified object.
*/
@Override
public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context)
{
final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
return new JsonPrimitive(fmt.print(src));
}
/**
* Change the timestamp into our own format.
* @param date
* Timestamp
* @return
* returns the formatted timestamp
*/
public static String getTimeStamp(DateTime date) {
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String timeStamp = fmt.print(date);
return timeStamp;
}