Java Code Examples for org.joda.time.format.DateTimeFormat#forPattern()

The following examples show how to use org.joda.time.format.DateTimeFormat#forPattern() . 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: QueryTest.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void dateBetweenSearch() throws IOException, SqlParseException, SQLFeatureNotSupportedException {
	DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_FORMAT);

	DateTime dateLimit1 = new DateTime(2014, 8, 18, 0, 0, 0);
	DateTime dateLimit2 = new DateTime(2014, 8, 21, 0, 0, 0);

	SearchHits response = query(String.format("SELECT insert_time FROM %s/online WHERE insert_time BETWEEN '2014-08-18' AND '2014-08-21' LIMIT 3", TEST_INDEX_ONLINE));
	SearchHit[] hits = response.getHits();
	for(SearchHit hit : hits) {
		Map<String, Object> source = hit.getSourceAsMap();
		DateTime insertTime = formatter.parseDateTime((String) source.get("insert_time"));

		boolean isBetween =
				(insertTime.isAfter(dateLimit1) || insertTime.isEqual(dateLimit1)) &&
				(insertTime.isBefore(dateLimit2) || insertTime.isEqual(dateLimit2));

		Assert.assertTrue("insert_time must be between 2014-08-18 and 2014-08-21", isBetween);
	}
}
 
Example 2
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 3
Source File: CloudStorageHelper.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME environment
 * variable, appending a timestamp to end of the uploaded filename.
 */
public String uploadFile(FileItemStream fileStream, final String bucketName)
    throws IOException, ServletException {
  checkFileExtension(fileStream.getName());

  System.out.println("FileStream name: " + fileStream.getName() + "\nBucket name: " + bucketName);

  DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  String dtString = dt.toString(dtf);
  final String fileName = fileStream.getName() + dtString;

  // the inputstream is closed by default, so we don't need to close it here
  @SuppressWarnings("deprecation")
  BlobInfo blobInfo =
      storage.create(
          BlobInfo.newBuilder(bucketName, fileName)
              // Modify access list to allow all users with link to read file
              .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
              .build(),
          fileStream.openStream());
  logger.log(
      Level.INFO, "Uploaded file {0} as {1}", new Object[] {fileStream.getName(), fileName});
  // return the public download link
  return blobInfo.getMediaLink();
}
 
Example 4
Source File: MessageFile.java    From jeesupport with MIT License 6 votes vote down vote up
private static void _write_( Integer _cmd, Long _usr, String _str, boolean _toc ){
    if( _cmd == null ) return;

    String file = CommonConfig.getString( "jees.jsts.message.jsonPath" );
    if( _usr == null ) _usr = 0L;
    DateTimeFormatter fmt = DateTimeFormat.forPattern(
            CommonConfig.getString( "jees.jsts.message.jsonFormat", "yyyy-MM-dd_HH-mm-ss-SSS" ) );
    file += _usr + "/" + _cmd + "/" + ( _toc? "S_" : "C_" ) + fmt.print( DateTime.now() ) + ".json";

    try{
        if( CommonConfig.getBoolean( "jees.jsts.message.jsonLogs", false ) ){
            log.info( "--生成消息文件:" + file );
        }
        FileUtil.write( _str, file, false );
    }catch( FileNotFoundException e ){
        log.warn( "写入文件失败:" + e.toString() );
    }
}
 
Example 5
Source File: FieldCreatorMapperTest.java    From rocketchat-jira-trigger with MIT License 5 votes vote down vote up
@Test
public void getNoCreator() throws Exception {
	FieldCreatorMapper mapper = new FieldCreatorMapper(false, DateTimeFormat.forPattern("yyyy"));

	List<FieldCreator> creators = mapper.getCreators(emptyList());

	assertThat(creators).isEmpty();
}
 
Example 6
Source File: TestRegexExtractorInterceptor.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 7
Source File: ToDate2ARGS.java    From spork with Apache License 2.0 5 votes vote down vote up
public DateTime exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    String dtStr = DataType.toString(input.get(0));
    //DateTimeZone dtz = extractDateTimeZone(dtStr);
    //The timezone in the customized format is not predictable
    DateTimeFormatter dtf = DateTimeFormat.forPattern(DataType
            .toString(input.get(1)));
    //if (dtz == null) {
        return dtf.parseDateTime(dtStr);
    //} else {
    //    return dtf.withZone(dtz).parseDateTime(dtStr);
    //}
}
 
Example 8
Source File: CDRGen.java    From cdr-gen with MIT License 5 votes vote down vote up
public void saveToFile(String outputFile, List<Person> customers) {
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd/MM/yyyy");
    DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm:ss");
        
    try {
        FileWriter fw = new FileWriter(outputFile);
        String newLine = System.getProperty("line.separator");
        
        for (Person p : customers) {
            for (Call c : p.getCalls()) {
                fw.append(c.getId() + ","
                        + p.getPhoneNumber() + ","
                        + c.getLine() + ","
                        + c.getDestPhoneNumber() + ","
                        + c.getTime().getStart().toString(dateFormatter) + "," 
                        + c.getTime().getEnd().toString(dateFormatter) + "," 
                        + c.getTime().getStart().toString(timeFormatter) + "," 
                        + c.getTime().getEnd().toString(timeFormatter) + ","
                        + c.getType() + ","
                        + c.getCost()
                        + newLine);
            }
        }

        fw.close();
    } catch (IOException ex) {
        LOG.error("Error while writing the output file.", ex);
    } 
}
 
Example 9
Source File: DateTimePerformance.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void checkJISOToString() {
        int COUNT = COUNT_SLOW;
        DateTime dt = new DateTime();
        DateTimeFormatter f = DateTimeFormat.forPattern("dd MMM yyyy");
        for (int i = 0; i < AVERAGE; i++) {
            start("JISO", "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 10
Source File: SegmentGeneratorConfig.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public void setSimpleDateFormat(@Nonnull String simpleDateFormat) {
  _timeColumnType = TimeColumnType.SIMPLE_DATE;
  try {
    DateTimeFormat.forPattern(simpleDateFormat);
  } catch (Exception e) {
    throw new RuntimeException("Illegal simple date format specification", e);
  }
  _simpleDateFormat = simpleDateFormat;
}
 
Example 11
Source File: SeanceAdapter.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
public void setItemList(List<Seances> itemListSeance, List<Event> itemListEvent) {

        listSeances = new ArrayList<>();
        ArrayList<IHoraireRows> listRowItems = new ArrayList<IHoraireRows>();
        String tempDate = "";
        DateTime today = new DateTime();

        listRowItems.addAll(itemListEvent);
        listRowItems.addAll(itemListSeance);

        Collections.sort(listRowItems, new HoraireComparator());

        for(IHoraireRows rows : listRowItems) {

            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
            DateTime seanceDay = formatter.parseDateTime(rows.getDateDebut().substring(0, 10));

//            if(today.isAfter(seanceDay) && !DateUtils.isToday(seanceDay.getMillis()) ) {
//                continue;
//            }

            if(!rows.getDateDebut().substring(0,10).equals(tempDate)) {

                tempDate = rows.getDateDebut().substring(0,10);

                DateTime.Property pDoW = seanceDay.dayOfWeek();
                DateTime.Property pDoM = seanceDay.dayOfMonth();
                DateTime.Property pMoY = seanceDay.monthOfYear();

                this.listSeances.add(new TodayDataRowItem(TodayDataRowItem.viewType.VIEW_TYPE_TITLE_SEANCE, context.getString(R.string.date_text, pDoW.getAsText(Locale.getDefault()), pDoM.get(), pMoY.getAsText(Locale.getDefault()))));
            }

            if(rows.getClass().equals(Event.class)){
                this.listSeances.add(new TodayDataRowItem(TodayDataRowItem.viewType.VIEW_TYPE_ETS_EVENT, rows));
            } else if(rows.getClass().equals(Seances.class)){
                this.listSeances.add(new TodayDataRowItem(TodayDataRowItem.viewType.VIEW_TYPE_SEANCE, rows));
            }
        }

    }
 
Example 12
Source File: ApproveThesisProposal.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected String getMessage(Thesis thesis) {
    Locale locale = I18N.getLocale();
    Person currentPerson = AccessControl.getPerson();
    ExecutionYear executionYear = ExecutionYear.readCurrentExecutionYear();
    String institutionName = Bennu.getInstance().getInstitutionUnit().getPartyName().getContent(locale);

    String title = thesis.getTitle().getContent();
    String year = executionYear.getYear();
    String degreeName = thesis.getDegree().getNameFor(executionYear).getContent();
    String studentName = thesis.getStudent().getPerson().getName();
    String studentNumber = thesis.getStudent().getNumber().toString();
    String presidentName = name(thesis.getPresident());
    String presidentAffiliation = affiliation(thesis.getPresident());
    String vowel1Name = name(thesis.getVowels(), 0);
    String vowel1Affiliation = affiliation(thesis.getVowels(), 0);
    String vowel2Name = name(thesis.getVowels(), 1);
    String vowel2Affiliation = affiliation(thesis.getVowels(), 1);
    String vowel3Name = name(thesis.getVowels(), 2);
    String vowel3Affiliation = affiliation(thesis.getVowels(), 2);
    String vowel4Name = name(thesis.getVowels(), 3);
    String vowel4Affiliation = affiliation(thesis.getVowels(), 3);
    String orientationName =
            thesis.getOrientation().stream().map(p -> p.getName() + ", " + p.getAffiliation())
                    .collect(Collectors.joining("\n"));

    String currentPersonName = currentPerson.getNickname();

    String dateMessage;
    String discussedDate = "";

    if (thesis.getDiscussed() == null) {
        //No date was defined to the thesis
        dateMessage = getMessage(locale, NO_DATE_KEY);
    } else {
        dateMessage = getMessage(locale, WITH_DATE_KEY);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
        discussedDate = thesis.getDiscussed().toString(fmt);
    }

    String sender =
            thesis.isCoordinator() ? getMessage(locale, COORDINATOR_SENDER) : getMessage(locale, COUNCIL_MEMBER_SENDER);
    String role = thesis.isCoordinator() ? "" : getMessage(locale, COUNCIL_MEMBER_ROLE);

    Calendar today = Calendar.getInstance(locale);
    return getMessage(locale, BODY_KEY, year, degreeName, studentName, studentNumber, presidentName, presidentAffiliation,
            includeFlag(vowel1Name), vowel1Name, vowel1Affiliation, includeFlag(vowel2Name), vowel2Name, vowel2Affiliation,
            includeFlag(vowel3Name), vowel3Name, vowel3Affiliation, includeFlag(vowel4Name), vowel4Name, vowel4Affiliation,
            includeFlag(orientationName), orientationName, dateMessage, discussedDate, institutionName,
            "" + today.get(Calendar.DAY_OF_MONTH), today.getDisplayName(Calendar.MONTH, Calendar.LONG, locale),
            "" + today.get(Calendar.YEAR), sender, currentPersonName, role);
}
 
Example 13
Source File: LondonTimes.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
protected boolean sync() throws ExecutionException, InterruptedException {
    try {
        final Trust trust = new Trust();
        final TrustManager[] trustmanagers = new TrustManager[]{trust};
        SSLContext sslContext;


        Ion ion = Ion.getDefault(App.get());
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustmanagers, new SecureRandom());

        ion.configure().createSSLContext("TLS");

        ion.getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
        ion.getHttpClient().getSSLSocketMiddleware().setTrustManagers(trustmanagers);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

    Result r = Ion.with(App.get())
            .load("https://www.londonprayertimes.com/api/times/?formatDate=json&key=1e6f7b94-542d-4ff7-94cc-e9c8e0bd2e64&year=" + LocalDate.now().getYear())
            .setTimeout(3000)
            .userAgent(App.getUserAgent())
            .as(Result.class)
            .get();
    int i = 0;

    DateTimeFormatter pattern = DateTimeFormat.forPattern("yyyy-MM-dd");
    for (Times t : r.times.values()) {
        t.fixTimes();

        LocalDate ld = LocalDate.parse(t.date, pattern);
        setTime(ld, Vakit.FAJR, t.fajr);
        setTime(ld, Vakit.SUN, t.sunrise);
        setTime(ld, Vakit.DHUHR, t.dhuhr);
        setTime(ld, Vakit.ASR, t.asr);
        setTime(ld, Vakit.MAGHRIB, t.magrib);
        setTime(ld, Vakit.ISHAA, t.isha);
        setAsrThani(ld, t.asr_2);
        i++;
    }

    return i > 10;
}
 
Example 14
Source File: SlashEncodedDayPartitionValueExtractor.java    From hudi with Apache License 2.0 4 votes vote down vote up
public SlashEncodedDayPartitionValueExtractor() {
  this.dtfOut = DateTimeFormat.forPattern("yyyy-MM-dd");
}
 
Example 15
Source File: SwiftManager.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void login() throws EndpointNotFoundException, UnauthorizedException, UnexpectedStatusCodeException,
        IOException {

    HttpClient httpClient = new DefaultHttpClient();

    try {
        HttpPost request = new HttpPost(authUrl);

        String body = String
                .format("{\"auth\": {\"passwordCredentials\": {\"username\": \"%s\", \"password\": \"%s\"}, \"tenantName\":\"%s\"}}",
                user, password, tenant);
        StringEntity entity = new StringEntity(body);
        entity.setContentType("application/json");
        request.setEntity(entity);
        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

        String responseBody = swiftResponse.getResponseBodyAsString();

        Gson gson = new Gson();
        LoginResponseObject loginResponse = gson.fromJson(responseBody, LoginResponseObject.class);

        this.authToken = loginResponse.getAccess().getToken().getId();

        Boolean endpointFound = false;

        for (ServiceObject service : loginResponse.getAccess().getServiceCatalog()) {

            if (service.getType().equals("object-store")) {
                this.storageUrl = service.getEndpoints().get(0).getPublicURL();
                endpointFound = true;
                break;
            }
        }

        // get the token issue swift date
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
        DateTime issuedAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getIssuedAt());

        // get the token expiration swift date
        dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        DateTime expiresAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getExpires());

        // calculate the period between these two dates and add it to our
        // current time because datetime can differ from Swift and this
        // device
        Period period = new Period(issuedAt, expiresAt);
        expirationDate = DateTime.now().plus(period);

        if (!endpointFound) {
            throw new EndpointNotFoundException();
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 16
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static int getTime(int temporalResolution, int[] input, int tempPosition) {
    
    String temporal = "";
    String format  = "";
    
    long time = 0L;
    
    try {
        time = ((long)input[tempPosition])*1000;
    } catch (Exception e) {
        return -1;
    }
    
    if (time < 0)
        return -1;
    
    DateTime dt = new DateTime(time, DateTimeZone.UTC);
    
    switch (temporalResolution) {
    
    case HOUR:
        temporal = dt.year().getAsString() + "-" +
                dt.monthOfYear().getAsString() + "-" +
                dt.dayOfMonth().getAsString() + "-" +
                dt.hourOfDay().getAsString();
        format = "yyyy-MM-dd-HH z";
        break;
    case DAY:
        temporal = dt.year().getAsString() + "-" +
                dt.monthOfYear().getAsString() + "-" +
                dt.dayOfMonth().getAsString();
        format = "yyyy-MM-dd z";
        break;
    case WEEK:
        temporal = dt.weekyear().getAsString() + "-" +
                dt.weekOfWeekyear().getAsString();
        format = "xxxx-ww z";
        break;
    case MONTH:
        temporal = dt.year().getAsString() + "-" +
                dt.monthOfYear().getAsString();
        format = "yyyy-MM z";
        break;
    case YEAR:
        temporal = dt.year().getAsString();
        format = "yyyy z";
        break;
    default:
        temporal = null;
        format = "";
        break;
    }
    
    if (temporal == null)
        return -1;
    
    DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
    return (int) (formatter.parseDateTime(temporal + " UTC").getMillis()/1000);
}
 
Example 17
Source File: IndexNameExpressionResolver.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public DateMathExpressionResolver(Settings settings) {
    String defaultTimeZoneId = settings.get("date_math_expression_resolver.default_time_zone", "UTC");
    this.defaultTimeZone = DateTimeZone.forID(defaultTimeZoneId);
    defaultDateFormatterPattern = settings.get("date_math_expression_resolver.default_date_format", "YYYY.MM.dd");
    this.defaultDateFormatter = DateTimeFormat.forPattern(defaultDateFormatterPattern);
}
 
Example 18
Source File: StaticLog4jFormatter.java    From suro with Apache License 2.0 4 votes vote down vote up
@Inject
public StaticLog4jFormatter(ClientConfig config) {
    this.config = config;

    fmt = DateTimeFormat.forPattern(config.getLog4jDateTimeFormat());
}
 
Example 19
Source File: LocalDateConverter.java    From gson-jodatime-serialisers with MIT License 3 votes vote down vote up
/**
 * Gson invokes this call-back method during deserialization 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.JsonDeserializationContext#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws com.google.gson.JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException
{
  // Do not try to deserialize null or empty values
  if (json.getAsString() == null || json.getAsString().isEmpty())
  {
    return null;
  }

  final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
  return fmt.parseLocalDate(json.getAsString());
}
 
Example 20
Source File: Snippets.java    From beam with Apache License 2.0 3 votes vote down vote up
public static Map<String, String> readTestData() {

      Map<String, String> map = new HashMap<>();
      Instant now = Instant.now();

      DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:MM:SS");

      map.put("Key_A", now.minus(Duration.standardSeconds(30)).toString(dtf));
      map.put("Key_B", now.minus(Duration.standardSeconds(30)).toString());

      return map;
    }