org.joda.time.format.DateTimeFormat Java Examples

The following examples show how to use org.joda.time.format.DateTimeFormat. 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: InMemoryOptTokenStore.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: Interval.java    From program-ab with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example #3
Source File: RiskService.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
/**
 * 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` ");
            }
        }
    }
}
 
Example #4
Source File: CustomFormatToISO.java    From spork with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: DayPartitioner.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: CustomConfigRuntimeTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: TestIndexNameFilter.java    From Raigad with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #8
Source File: ParserUtils.java    From substitution-schedule-parser with Mozilla Public License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: CustomDateTimeJsonFieldDecoder.java    From presto with Apache License 2.0 6 votes vote down vote up
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()));
    }
}
 
Example #10
Source File: Inspect2.java    From h2o-2 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #11
Source File: ContentInstanceAnncDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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)");
	}
	
}
 
Example #12
Source File: DateTimePerformance.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void checkJodaToString() {
        int COUNT = COUNT_SLOW;
        DateTime dt = new DateTime(GJChronology.getInstance());
        DateTimeFormatter f = DateTimeFormat.forPattern("dd MMM yyyy");
        for (int i = 0; i < AVERAGE; i++) {
            start("Joda", "toString");
            for (int j = 0; j < COUNT; j++) {
                String str = dt.toString("dd MMM yyyy");
//                String str = dt.toString(f);
                if (str == null) {System.out.println("Anti optimise");}
            }
            end(COUNT);
        }
    }
 
Example #13
Source File: CMSExtensions.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 "";
}
 
Example #14
Source File: RuntimeTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #15
Source File: RuntimeTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #16
Source File: DateTimePlaceholderResolver.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object getChild(String name) {
    switch (name) {
        case "shortTime":
            return format(DateTimeFormat.shortTime());
        case "mediumTime":
            return format(DateTimeFormat.mediumTime());
        case "longTime":
            return format(DateTimeFormat.longTime());
        case "fullTime":
            return format(DateTimeFormat.fullTime());
        case "shortDate":
            return format(DateTimeFormat.shortDate());
        case "mediumDate":
            return format(DateTimeFormat.mediumDate());
        case "longDate":
            return format(DateTimeFormat.longDate()); // The same as medium
        case "fullDate":
            return format(DateTimeFormat.fullDate());
        case "shortDateTime":
            return format(DateTimeFormat.shortDateTime());
        case "mediumDateTime":
            return format(DateTimeFormat.mediumDateTime());
        case "longDateTime":
            return format(DateTimeFormat.longDateTime());
        case "fullDateTime":
            return format(DateTimeFormat.fullDateTime());
    }
    return null;
}
 
Example #17
Source File: YearMonth.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #18
Source File: StreamsDateTimeDeserializer.java    From streams with Apache License 2.0 5 votes vote down vote up
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);
    }
  }
}
 
Example #19
Source File: Extract.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
  }
}
 
Example #20
Source File: AbstractUniversalDateWidget.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
/**
 * 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 + ")");
}
 
Example #21
Source File: DateHandler.java    From heat with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #22
Source File: DateTimeConverter.java    From atdl4j with MIT License 5 votes vote down vote up
@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;
	}
}
 
Example #23
Source File: AzureCliToken.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
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;
}
 
Example #24
Source File: LocalOnlineApplication.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@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;
}
 
Example #25
Source File: DayOfWeekDescriptionBuilder.java    From quartz-glass with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #26
Source File: JodaTimeHelperTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testFormattersFromFormatterWithOwnTZ() {
    final DateTimeFormatter yyyyMMdd = JodaTimeHelper.getDateTimeFormatters(DATE_TIME_FORMATTER_SUPPLIER_TZ)[0];
    final long instant = System.currentTimeMillis();
    assertEquals(DateTimeFormat.forPattern("ddMMyyyy").withZone(CHICAGO_TZ).print(instant), yyyyMMdd.print(instant));
    assertEquals(CHICAGO_TZ, yyyyMMdd.getZone());
}
 
Example #27
Source File: DateUtilTests.java    From flink-learning with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTimeAtStartOfDay() {
    DateTimeFormatter dtf =
            DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    Date date = new Date(1557874800000L);
    DateTime dt = new DateTime(1557874800000L);

    Assert.assertEquals("2019-05-15 00:00:00",
            DateUtil.withTimeAtStartOfDay(date, dtf));
    Assert.assertEquals("2019-05-15 00:00:00",
            DateUtil.withTimeAtStartOfDay(dt, dtf));
}
 
Example #28
Source File: DatePartitionedAvroFileExtractorTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadPartitionsByMinuteWithLeadtime() throws IOException, DataRecordException {

  DatePartitionedAvroFileSource source = new DatePartitionedAvroFileSource();

  SourceState state = new SourceState();
  state.setProp(ConfigurationKeys.SOURCE_FILEBASED_FS_URI, ConfigurationKeys.LOCAL_FS_URI);
  state.setProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, SOURCE_ENTITY);
  state.setProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY, OUTPUT_DIR + Path.SEPARATOR + SOURCE_ENTITY);
  state.setProp(ConfigurationKeys.SOURCE_ENTITY, SOURCE_ENTITY);
  state.setProp(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, 2);

  state.setProp("date.partitioned.source.partition.pattern", DATE_PATTERN);
  state.setProp("date.partitioned.source.min.watermark.value", DateTimeFormat.forPattern(DATE_PATTERN).print(
      this.startDateTime.minusMinutes(1)));
  state.setProp(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY, TableType.SNAPSHOT_ONLY);
  state.setProp("date.partitioned.source.partition.prefix", PREFIX);
  state.setProp("date.partitioned.source.partition.suffix", SUFFIX);
  state.setProp("date.partitioned.source.partition.lead_time.size", "3");
  state.setProp("date.partitioned.source.partition.lead_time.granularity", "HOUR");

  /*
   * Since lead time is 3 hours, only the first WorkUnit (which is 6 hours old, rest are 2hrs) should get
   * picked up
   */
  List<WorkUnit> workunits = source.getWorkunits(state);

  Assert.assertEquals(workunits.size(), 1);
  verifyWorkUnits(workunits, workunits.size());
}
 
Example #29
Source File: AbsoluteDateFormat.java    From NaturalDateFormat with Apache License 2.0 5 votes vote down vote up
private void buildTimeFormat() {
    if (!hasFormat(TIME))
        return;
    StringBuilder pattern = new StringBuilder();
    if ((format & HOURS) != 0)
        pattern.append(twelveHour ? "h" : "H");
    if ((format & MINUTES) != 0)
        pattern.append(pattern.length() == 0 ? "mm" : ":mm");
    if ((format & SECONDS) != 0)
        pattern.append(pattern.length() == 0 ? "ss" : ":ss");
    if (hasFormat(HOURS) && twelveHour)
        pattern.append(" a");
    timeFormat = DateTimeFormat.forPattern(pattern.toString());
}
 
Example #30
Source File: PreparedInput.java    From ambiverse-nlu with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}