下面列出了freemarker.template.Version#org.joda.time.format.DateTimeFormat 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public String exec(Tuple input) throws IOException
{
if (input == null || input.size() < 2) {
return null;
}
if (input.get(0) == null || input.get(1) == null) {
return null;
}
String date = input.get(0).toString();
String format = input.get(1).toString();
// See http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormat.html
DateTimeFormatter parser = DateTimeFormat.forPattern(format);
DateTime result;
try {
result = parser.withOffsetParsed().parseDateTime(date);
} catch(Exception e) {
return null;
}
return result.toString();
}
public CustomDateTimeJsonFieldDecoder(DecoderColumnHandle columnHandle)
{
this.columnHandle = requireNonNull(columnHandle, "columnHandle is null");
if (!SUPPORTED_TYPES.contains(columnHandle.getType())) {
throwUnsupportedColumnType(columnHandle);
}
checkArgument(columnHandle.getFormatHint() != null, "format hint not defined for column '%s'", columnHandle.getName());
try {
formatter = DateTimeFormat.forPattern(columnHandle.getFormatHint()).withLocale(Locale.ENGLISH).withZoneUTC();
}
catch (IllegalArgumentException e) {
throw new PrestoException(
GENERIC_USER_ERROR,
format("invalid joda pattern '%s' passed as format hint for column '%s'", columnHandle.getFormatHint(), columnHandle.getName()));
}
}
public DayPartitioner(State state, int numBranches, int branchId) {
_withColumnNames = state.getPropAsBoolean(GoggleIngestionConfigurationKeys.KEY_INCLUDE_COLUMN_NAMES, false);
_prefix = state.getProp(GoggleIngestionConfigurationKeys.KEY_PARTITIONER_PREFIX);
_withPrefix = StringUtils.isNotBlank(_prefix);
_dateColumn = state.getProp(GoggleIngestionConfigurationKeys.KEY_DATE_COLUMN_NAME, DEFAULT_DATE_COLUMN);
_dateFormatter =
DateTimeFormat.forPattern(state.getProp(GoggleIngestionConfigurationKeys.KEY_DATE_FORMAT, DEFAULT_DATE_FORMAT));
SchemaBuilder.FieldAssembler<Schema> assembler = SchemaBuilder.record(NAME).namespace(NAME_SPACE).fields();
Schema stringType = Schema.create(Schema.Type.STRING);
if (_withPrefix) {
assembler = assembler.name(PARTITION_COLUMN_PREFIX).type(stringType).noDefault();
}
_partitionSchema =
assembler.name(PARTITION_COLUMN_YEAR).type(stringType).noDefault().name(PARTITION_COLUMN_MONTH).type(stringType)
.noDefault().name(PARTITION_COLUMN_DAY).type(stringType).noDefault().endRecord();
}
@Test
@DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/post_custom_expression_function_expression_1.dmn")
public void customExpressionFunctionMissingDefaultFunction() {
DmnEngine dmnEngine = flowableRule2.getDmnEngine();
DmnDecisionService ruleService = dmnEngine.getDmnDecisionService();
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
LocalDate localDate = dateTimeFormatter.parseLocalDate("2015-09-18");
DecisionExecutionAuditContainer result = ruleService.createExecuteDecisionBuilder()
.decisionKey("decision")
.variable("input1", localDate.toDate())
.executeWithAuditTrail();
assertThat(result.getDecisionResult()).isEmpty();
assertThat(result.isFailed()).isTrue();
}
@NotNull private static List<String> handleUrlWithDateFormat(String url) {
List<String> urls = new ArrayList<>();
Pattern dateFormatPattern = Pattern.compile("\\{date\\(([^)]+)\\)\\}");
Matcher matcher = dateFormatPattern.matcher(url);
if (matcher.find()) {
String pattern = matcher.group(1);
for (int j = 0; j < 7; j++) {
LocalDate date = LocalDate.now().plusDays(j);
String dateStr = DateTimeFormat.forPattern(pattern).print(date);
String urlWithDate = matcher.replaceFirst(dateStr);
urls.add(urlWithDate);
}
} else {
urls.add(url);
}
return urls;
}
@Test
public void testHourlyIndexNameFilter() {
DateTimeFormatter formatter = DateTimeFormat.forPattern("'abcd'YYYYMMddHH");
IIndexNameFilter filter = new DatePatternIndexNameFilter(formatter);
assertTrue(filter.filter("abcd2013120300"));
assertTrue(filter.filter("abcd2013120301"));
assertTrue(filter.filter("abcd2013120312"));
assertTrue(filter.filter("abcd2013120323"));
assertFalse(filter.filter("abcd12013120323"));
assertFalse(filter.filter("abcd2013120324"));
assertFalse(filter.filter("abcd2013120345"));
assertFalse(filter.filter("abcd20231248"));
assertFalse(filter.filter("_abc"));
}
@Override
public boolean validate(UserInfo userInfo, String token, String type, int interval) {
OneTimePassword otp = optTokenStore.get(userInfo.getUsername() + "_" + type + "_" + token);
if (otp != null) {
DateTime currentdateTime = new DateTime();
DateTime oneCreateTime = DateTime.parse(otp.getCreateTime(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
Duration duration = new Duration(oneCreateTime, currentdateTime);
int intDuration = Integer.parseInt(duration.getStandardSeconds() + "");
logger.debug("validate duration " + intDuration);
logger.debug("validate result " + (intDuration <= interval));
if (intDuration <= interval) {
return true;
}
}
return false;
}
public static int getMonthsBetween(final String date1, final String date2, String format){
try {
final DateTimeFormatter fmt =
DateTimeFormat
.forPattern(format)
.withChronology(
LenientChronology.getInstance(
GregorianChronology.getInstance()));
return Months.monthsBetween(
fmt.parseDateTime(date1),
fmt.parseDateTime(date2)
).getMonths();
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
public static String x1( Vec v, long row, double d ) {
if( (row >= 0 && v.isNA(row)) || Double.isNaN(d) )
return "-"; // Display of missing elements
if( v.isEnum() ) return row >= 0 ? v.domain(v.at8(row)) : Long.toString((long)d);
if( v.isTime() ) {
String tpat = v.timeParse();
DateTime dt = new DateTime(row >= 0 ? v.at8(row) : (long)d);
DateTimeFormatter fmt = DateTimeFormat.forPattern(tpat);
String str = fmt.print(dt);
return str;
}
if( v.isInt() ) return Long.toString(row >= 0 ? v.at8(row) : (long)d);
Chunk c = v.chunkForChunkIdx(0);
Class Cc = c.getClass();
if( Cc == C1SChunk.class ) return x2(d,((C1SChunk)c)._scale);
if( Cc == C2SChunk.class ) return x2(d,((C2SChunk)c)._scale);
return Double.toString(d);
}
/**
* Add a criteria to get the Risks for the given day
*
* @param query
* @param date yyyy-MM-dd or latest
*/
private void dayCriteria(Query query, String date){
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
if (!date.isEmpty()) {
if (date.equals("latest")){
query.limit(1);
} else {
try {
DateTime startDate = formatter.parseDateTime(date).withZone(DateTimeZone.UTC);
DateTime endDate = startDate.plusDays(1);
query.addCriteria(where("dateTime").gte(startDate).lt(endDate)); // Get the risks for the day given
} catch (Exception e) {
throw new BadRequestException("Not able to parse the date, it has to be in the following format: `yyyy-MM-dd` ");
}
}
}
}
@Override
public String startProcess(String name, String owner, DateTime date, DateTime creationDate,
OnlineWorkflowStartParameters start, OnlineWorkflowParameters params, DateTime[] basecases, int numThreads)
throws Exception {
Objects.requireNonNull(date);
Objects.requireNonNull(creationDate);
Objects.requireNonNull(params);
Objects.requireNonNull(basecases);
config = OnlineConfig.load();
OnlineDb onlineDb = config.getOnlineDbFactoryClass().newInstance().create();
String processId = DateTimeFormat.forPattern("yyyyMMddHHmmSSS").print(new DateTime());
LOGGER.info("Starting process: " + processId);
OnlineProcess proc = new OnlineProcess(processId, name, owner, params.getCaseType().toString(), date, creationDate);
ExecutorService taskExecutor = Executors.newFixedThreadPool(numThreads);
List<Callable<Void>> tasks = new ArrayList<>(numThreads);
for (DateTime basecase : basecases) {
tasks.add(new Callable() {
@Override
public Object call() throws Exception {
OnlineWorkflowParameters pars = new OnlineWorkflowParameters(basecase, params.getStates(), params.getHistoInterval(), params.getOfflineWorkflowId(), params.getTimeHorizon(), params.getFeAnalysisId(), params.getRulesPurityThreshold(), params.storeStates(), params.analyseBasecase(), params.validation(), params.getSecurityIndexes(), params.getCaseType(), params.getCountries(), params.isMergeOptimized(), params.getLimitReduction(), params.isHandleViolationsInN(), params.getConstraintMargin());
String workflowId = startWorkflow(start, pars);
org.joda.time.format.DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String basecaseString = fmt.print(basecase);
proc.addWorkflow(basecaseString, workflowId);
return workflowId;
} });
}
taskExecutor.invokeAll(tasks);
taskExecutor.shutdown();
onlineDb.storeProcess(proc);
LOGGER.info("End of process: " + processId);
return processId;
}
public DerivedColumn(@JsonProperty("columnName") String columnName,
@JsonProperty("columnType") ColumnType columnType, @JsonProperty("format") String format,
@JsonProperty("dateTimeZone") DateTimeZone dateTimeZone,
@JsonProperty("fieldType") DateTimeFieldType fieldType) {
this.columnName = columnName;
this.columnType = columnType;
this.format = format;
this.dateTimeZone = dateTimeZone;
this.fieldType = fieldType;
if (format != null)
dateTimeFormatter = DateTimeFormat.forPattern(this.format).withZone(dateTimeZone);
}
/**
* Convert timestamp in a string format to joda time
* @param input timestamp
* @param format timestamp format
* @param timezone time zone of timestamp
* @return joda time
*/
public static DateTime toDateTime(String input, String format, String timezone) {
String tz = StringUtils.defaultString(timezone, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE);
DateTimeZone dateTimeZone = getTimeZone(tz);
DateTimeFormatter inputDtFormat = DateTimeFormat.forPattern(format).withZone(dateTimeZone);
DateTime outputDateTime = inputDtFormat.parseDateTime(input).withZone(dateTimeZone);
return outputDateTime;
}
private List<IndexApplicationChartResponse> getApplicationChartPerDayRange(String startDate, String endDate, List<Application> applications) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN);
Date calendarEndDate = DateTime.parse(endDate, formatter).toDate();
Date calendarStartDate = DateTime.parse(startDate, formatter).toDate();
int stepSize = DateUtils.getDayDiffBetween(calendarStartDate, calendarEndDate);
return getApplicationChartPerDayRecent(calendarEndDate, -(stepSize + 1), applications);
}
protected StreamsDateTimeDeserializer(Class<DateTime> dateTimeClass, List<String> formats) {
super(dateTimeClass);
for ( String format : formats ) {
try {
formatters.add(DateTimeFormat.forPattern(format));
} catch (Exception ex) {
LOGGER.warn("Exception parsing format " + format);
}
}
}
private LocalDateTime getDateTime(String dateString) {
if (!StringUtils.isBlank(dateString)) {
String pattern;
if (dateString.matches("(19|20)[0-9]{2}[/](0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])")) {
pattern = "yyyy/MM/dd";
} else {
pattern = "yyyy-MM-dd";
}
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern);
return dateTimeFormatter.parseLocalDateTime(dateString);
}
return null;
}
public DateTime effectiveDate() {
if (null == effectiveDate) {
return null;
}
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
return fmt.parseDateTime(effectiveDate);
}
@Test
public void testFormattersFromFormatterWithSpecifiedTZ() {
final DateTimeFormatter yyyyMMdd = JodaTimeHelper.getDateTimeFormatters(DATE_TIME_FORMATTER_SUPPLIER_TZ, TIME_ZONE_SUPPLIER)[0];
final long instant = System.currentTimeMillis();
assertEquals(DateTimeFormat.forPattern("ddMMyyyy").withZone(NY_TZ).print(instant), yyyyMMdd.print(instant));
assertEquals(NY_TZ, yyyyMMdd.getZone());
}
/**
* Constructor.
*
* @param state a {@link SourceState} carrying properties needed to construct an {@link Extract}
* @param namespace dot separated namespace path
* @param type {@link TableType}
* @param table table name
*
* @deprecated Extract does not use any property in {@link SourceState}.
* Use {@link #Extract(TableType, String, String)}
*/
@Deprecated
public Extract(SourceState state, TableType type, String namespace, String table) {
// Values should only be null for deserialization
if (state != null && type != null && !Strings.isNullOrEmpty(namespace) && !Strings.isNullOrEmpty(table)) {
// Constructing DTF
DateTimeZone timeZone = getTimeZoneHelper(state);
DateTimeFormatter DTF = DateTimeFormat.forPattern("yyyyMMddHHmmss").withLocale(Locale.US).withZone(timeZone);
String extractId = DTF.print(new DateTime());
super.addAll(state);
super.setProp(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY, type.toString());
super.setProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, namespace);
super.setProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY, table);
super.setProp(ConfigurationKeys.EXTRACT_EXTRACT_ID_KEY, extractId);
for (WorkUnitState pre : state.getPreviousWorkUnitStates()) {
Extract previousExtract = pre.getWorkunit().getExtract();
if (previousExtract.getNamespace().equals(namespace) && previousExtract.getTable().equals(table)) {
this.previousTableState.addAll(pre);
}
}
// Setting full drop date if not already specified, the value can still be overridden if required.
if (state.getPropAsBoolean(ConfigurationKeys.EXTRACT_IS_FULL_KEY)
&& !state.contains(ConfigurationKeys.EXTRACT_FULL_RUN_TIME_KEY)) {
super.setProp(ConfigurationKeys.EXTRACT_FULL_RUN_TIME_KEY, System.currentTimeMillis());
}
}
}
/**
* Output the date using the specified format pattern.
*
* @param pattern the pattern specification, null means use <code>toString</code>
* @see org.joda.time.format.DateTimeFormat
*/
public String toString(String pattern) {
if (pattern == null) {
return toString();
}
return DateTimeFormat.forPattern(pattern).print(this);
}
/**
* Output the year-month using the specified format pattern.
*
* @param pattern the pattern specification, null means use <code>toString</code>
* @see org.joda.time.format.DateTimeFormat
*/
public String toString(String pattern) {
if (pattern == null) {
return toString();
}
return DateTimeFormat.forPattern(pattern).print(this);
}
@Test
@DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/dates_5.dmn")
public void localDatesEquals() {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
LocalDate localDate = dateTimeFormatter.parseLocalDate("2015-09-18");
Map<String, Object> result = ruleService.createExecuteDecisionBuilder()
.decisionKey("decision")
.variable("input1", localDate)
.executeWithSingleResult();
assertThat(result.get("output1").getClass()).isSameAs(String.class);
assertThat(result.get("output1")).isEqualTo("test2");
}
@Test
@DmnDeploymentAnnotation(resources = "org/activiti/dmn/engine/test/deployment/reservered_word.dmn")
public void executeDecision_reserved_word() {
Map<String, Object> processVariablesInput = new HashMap<String, Object>();
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
LocalDate localDate = dateTimeFormatter.parseLocalDate("2015-09-18");
processVariablesInput.put("date", localDate.toDate());
RuleEngineExecutionResult result = ruleService.executeDecisionByKey("decision", processVariablesInput);
Assert.assertNotNull(result);
Assert.assertSame(result.getResultVariables().get("output1").getClass(), String.class);
Assert.assertEquals(result.getResultVariables().get("output1"), "test2");
}
@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 "";
}
public Resource retrieveLatest(String parentUri, RESULT_CONT resultContent) throws OneM2MException {
String now = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss"));
DBObject c1 = new BasicDBObject(EXPIRETIME_KEY, null);
DBObject c2 = new BasicDBObject(EXPIRETIME_KEY, new BasicDBObject("$gt", now));
BasicDBList or = new BasicDBList();
or.add(c1);
or.add(c2);
BasicDBObject query = new BasicDBObject("$or", or).append(PARENTID_KEY, parentUri);
List<Document>childList = getDocuments(query, RESOURCE_TYPE.CONTENT_INST, CREATETIME_KEY, false, 1);
if (childList.size() == 0) {
return null;
}
Document doc = childList.get(0);
try {
DaoJSONConvertor<ContentInstanceAnnc> cvt = (DaoJSONConvertor<ContentInstanceAnnc>)ConvertorFactory.getDaoJSONConvertor(ContentInstanceAnnc.class, ContentInstanceAnnc.SCHEMA_LOCATION);
//DaoJSONConvertor<ContentInstance> cvt = new DaoJSONConvertor<ContentInstance>(ContentInstance.class);
Resource res = (Resource) cvt.unmarshal(doc.toJson());
res.setUri(doc.getString(URI_KEY));
return res;
} catch (Exception e) {
log.debug("Handled exception", e);
throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR, "Exception during initialization of resource using document.(retrieveOldest)");
}
}
/**
* Update the widget helper date text (useful for those who don't know the other calendar)
*/
protected void updateGregorianDateHelperDisplay() {
DateTime dtLMDGreg = new DateTime(getCurrentMillis());
DateTimeFormatter fmt = DateTimeFormat.forPattern("d MMMM yyyy");
String str = fmt.print(dtLMDGreg);
txtGregorian.setText("(" + str + ")");
}
/**
* getFormattedDate takes a string input and return the formatted date.
* @param inputDate is an input a string like ${TODAY} or ${TODAY+1}
* @return formatted date as String
*/
public String getFormattedDate(String inputDate) {
String outputDate = "";
DateTime dateToParse = getDateTime(inputDate);
String patternForFormat = "\\$\\{" + DateHeatPlaceholderModule.TODAY_PLACEHOLDER_KEYWORD + ".*_(.*?)\\}";
Pattern formatPattern = Pattern.compile(patternForFormat);
Matcher formatMatcher = formatPattern.matcher(inputDate);
String format = DateHeatPlaceholderModule.TODAY_PLACEHOLDER_DEFAULT_PATTERN;
if (formatMatcher.find()) {
format = formatMatcher.group(1);
}
dtfOut = DateTimeFormat.forPattern(format);
outputDate = dtfOut.print(dateToParse);
return outputDate;
}
@Override
public String convertParameterValueToFixWireValue(Object aParameterValue)
{
DateTime date = convertParameterValueToParameterComparable( aParameterValue );
if ( date != null )
{
DateTimeFormatter fmt = DateTimeFormat.forPattern( getFormatString() );
return fmt.withZone( DateTimeZone.UTC ).print( date );
}
else
{
return null;
}
}
Date expiresOn() {
if (expiresOnDate == null) {
try {
expiresOnDate = DateTime.parse(expiresOn, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")).toDate();
} catch (IllegalArgumentException e) {
expiresOnDate = DateTime.parse(expiresOn).toDate();
}
}
return expiresOnDate;
}
@Override
protected String getSingleItemDescription(String expression) {
String exp = expression;
if (expression.contains("#")) {
exp = expression.substring(0, expression.indexOf("#"));
} else if (expression.contains("L")) {
exp = exp.replace("L", "");
}
if (StringUtils.isNumeric(exp)) {
return DateAndTimeUtils.getDayOfWeekName(Integer.parseInt(exp));
} else {
return DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH)
.parseDateTime(WordUtils.capitalizeFully(exp)).dayOfWeek().getAsText(Locale.ENGLISH);
}
}