Java 类org.joda.time.Period 实例源码

项目:Equella    文件:EchoUtils.java   
public static String formatDuration(long duration)
{
    // Using Joda Time
    DateTime now = new DateTime(); // Now
    DateTime plus = now.plus(new Duration(duration * 1000));

    // Define and calculate the interval of time
    Interval interval = new Interval(now.getMillis(), plus.getMillis());
    Period period = interval.toPeriod(PeriodType.time());

    // Define the period formatter for pretty printing
    String ampersand = " & ";
    PeriodFormatter pf = new PeriodFormatterBuilder().appendHours().appendSuffix(ds("hour"), ds("hours"))
        .appendSeparator(" ", ampersand).appendMinutes().appendSuffix(ds("minute"), ds("minutes"))
        .appendSeparator(ampersand).appendSeconds().appendSuffix(ds("second"), ds("seconds")).toFormatter();

    return pf.print(period).trim();
}
项目:azure-libraries-for-java    文件:TimeSpanTests.java   
@Test
public void testTimeSpanFromPeriod() {
    Period period = new Period()
            .withDays(366)
            .withHours(25)
            .withMinutes(10)
            .withSeconds(70)
            .withMillis(1001);
    TimeSpan timeSpan = new TimeSpan()
            .withDays(366)
            .withHours(25)
            .withMinutes(10)
            .withSeconds(70)
            .withMilliseconds(1001);
    Assert.assertEquals(TimeSpan.fromPeriod(period).toString(), timeSpan.toString());

    period = new Period()
            .withWeeks(12)
            .withDays(366)
            .withHours(25)
            .withMinutes(10)
            .withSeconds(70)
            .withMillis(1001);
    // Days -> 12 * 7 + 366 + 1
    Assert.assertEquals("451.01:11:11.0010000", TimeSpan.fromPeriod(period).toString());
}
项目:kubernetes-elastic-agents    文件:KubernetesAgentInstances.java   
private KubernetesAgentInstances unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception {
    Period period = settings.getAutoRegisterPeriod();
    KubernetesAgentInstances unregisteredInstances = new KubernetesAgentInstances();
    KubernetesClient client = factory.kubernetes(settings);

    for (String instanceName : instances.keySet()) {
        if (knownAgents.containsAgentWithId(instanceName)) {
            continue;
        }
        Pod pod = client.pods().inNamespace(Constants.KUBERNETES_NAMESPACE_KEY).withName(instanceName).get();
        Date createdAt = getSimpleDateFormat().parse(pod.getMetadata().getCreationTimestamp());
        DateTime dateTimeCreated = new DateTime(createdAt);

        if (clock.now().isAfter(dateTimeCreated.plus(period))) {
            unregisteredInstances.register(kubernetesInstanceFactory.fromKubernetesPod(pod));
        }
    }
    return unregisteredInstances;
}
项目:kubernetes-elastic-agents    文件:ServerPingRequestExecutorTest.java   
@Test
public void testShouldTerminateInstancesThatNeverAutoRegistered() throws Exception {
    KubernetesAgentInstances agentInstances = new KubernetesAgentInstances(factory);
    HashMap<String, String> properties = new HashMap<>();
    properties.put("Image", "foo");
    KubernetesInstance container = agentInstances.create(new CreateAgentRequest(null, properties, null, new JobIdentifier(1L)), createSettings(), null);

    agentInstances.clock = new Clock.TestClock().forward(Period.minutes(11));
    PluginRequest pluginRequest = mock(PluginRequest.class);

    objectMetadata.setName(container.name());
    HashMap<String, String> labels = new HashMap<>();
    labels.put(Constants.JOB_ID_LABEL_KEY, "1");
    objectMetadata.setLabels(labels);
    when(pluginRequest.getPluginSettings()).thenReturn(createSettings());
    when(pluginRequest.listAgents()).thenReturn(new Agents());
    verifyNoMoreInteractions(pluginRequest);

    new ServerPingRequestExecutor(agentInstances, pluginRequest).execute();
    assertFalse(agentInstances.instanceExists(container));
}
项目:dremio-oss    文件:TestParquetWriter.java   
private void testParquetReaderHelper(String tableName, Period row1Col1, Period row1Col2,
                                     Period row2Col1, Period row2Col2) throws Exception {

  final String switchReader = "alter session set `store.parquet.use_new_reader` = %s; ";
  final String enableVectorizedReader = String.format(switchReader, true);
  final String disableVectorizedReader = String.format(switchReader, false);
  String query = String.format("select * from %s", tableName);

  testBuilder()
      .sqlQuery(query)
      .unOrdered()
      .optionSettingQueriesForTestQuery(enableVectorizedReader)
      .baselineColumns("col1", "col2")
      .baselineValues(row1Col1, row1Col2)
      .baselineValues(row2Col1, row2Col2)
      .go();

  testBuilder()
      .sqlQuery(query)
      .unOrdered()
      .optionSettingQueriesForTestQuery(disableVectorizedReader)
      .baselineColumns("col1", "col2")
      .baselineValues(row1Col1, row1Col2)
      .baselineValues(row2Col1, row2Col2)
      .go();
}
项目:autorest.java    文件:DictionarysImpl.java   
/**
 * Set dictionary value  {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}.
 *
 * @param arrayBody the Map&lt;String, Period&gt; value
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> putDurationValidWithServiceResponseAsync(Map<String, Period> arrayBody) {
    if (arrayBody == null) {
        throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null.");
    }
    Validator.validate(arrayBody);
    return service.putDurationValid(arrayBody)
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = putDurationValidDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
项目:gocd-elastic-agent-marathon    文件:MarathonAgentInstances.java   
private MarathonAgentInstances unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception {
    MarathonAgentInstances unregisteredContainers = new MarathonAgentInstances();
    if (settings == null) {
        return unregisteredContainers;
    }
    Period period = settings.getAutoRegisterPeriod();

    for (MarathonInstance instance: instances.values()) {
        if (knownAgents.containsAgentWithId(instance.name())) {
            continue;
        }

        DateTime dateTimeCreated = new DateTime(instance.createdAt());

        if (clock.now().isAfter(dateTimeCreated.plus(period))) {
            unregisteredContainers.register(instance);
        }
    }
    return unregisteredContainers;
}
项目:dremio-oss    文件:DremioStringUtils.java   
/**
 * Formats a period similar to Oracle INTERVAL DAY TO SECOND data type.<br>
 * For example, the string "-001 18:25:16.766" defines an interval of - 1 day 18 hours 25 minutes 16 seconds and 766 milliseconds
 */
public static String formatIntervalDay(final Period p) {
  long millis = p.getDays() * (long) DateUtility.daysToStandardMillis + DateUtility.millisFromPeriod(p);

  boolean neg = false;
  if (millis < 0) {
    millis = -millis;
    neg = true;
  }

  final int days = (int) (millis / DateUtility.daysToStandardMillis);
  millis = millis % DateUtility.daysToStandardMillis;

  final int hours  = (int) (millis / DateUtility.hoursToMillis);
  millis     = millis % DateUtility.hoursToMillis;

  final int minutes = (int) (millis / DateUtility.minutesToMillis);
  millis      = millis % DateUtility.minutesToMillis;

  final int seconds = (int) (millis / DateUtility.secondsToMillis);
  millis      = millis % DateUtility.secondsToMillis;

  return String.format("%c%03d %02d:%02d:%02d.%03d", neg ? '-':'+', days, hours, minutes, seconds, millis);
}
项目:autorest.java    文件:ArraysImpl.java   
/**
 * Set array value  ['P123DT22H14M12.011S', 'P5DT1H0M0S'].
 *
 * @param arrayBody the List&lt;Period&gt; value
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> putDurationValidWithServiceResponseAsync(List<Period> arrayBody) {
    if (arrayBody == null) {
        throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null.");
    }
    Validator.validate(arrayBody);
    return service.putDurationValid(arrayBody)
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = putDurationValidDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
项目:gocd-elastic-agent-marathon    文件:MarathonAgentInstances.java   
@Override
public void refreshAll(PluginRequest pluginRequest) throws Exception {
    if (refreshed) {
        if (refreshedTime == null) {
            setRefreshed(false);
        } else {
            if (refreshedTime.isBefore(new DateTime().minus(new Period("PT10M")))) {
                setRefreshed(false);
            }
        }
    }
    if (!refreshed) {
        PluginSettings settings = pluginRequest.getPluginSettings();
        List<MarathonInstance> marathonInstanceList = marathon(settings).getGoAgents(settings);
        for (MarathonInstance instance: marathonInstanceList) {
             register(instance);
        }
        LOG.debug("Instances found: " + marathonInstanceList.toString());
        setRefreshedTime(new DateTime());
        setRefreshed(true);
    }
}
项目:soundwave    文件:ExclusiveRecurringJobExecutor.java   
/**
 * Decide when the job should start run in first time
 * @return Seconds for the Job to start
 */
public int getDelay() {
  try {
    JobRunInfo lastRun = jobInfoStore.getLatestRun(this.identifier);

    if (lastRun != null && lastRun.isSucceed()) {
      Period
          period =
          new Period(new DateTime(lastRun.getStartTime()), DateTime.now(DateTimeZone.UTC));
      if (period.toStandardSeconds().getSeconds() < this.interval) {
        return (int) (this.interval - period.toStandardSeconds().getSeconds());
      }
    }
  } catch (Exception ex) {
    logger.error(ExceptionUtils.getRootCauseMessage(ex));
    logger.error(ExceptionUtils.getFullStackTrace(ex));
  }

  return random.nextInt(Configuration.getProperties().getInt("job_random_delay", 60));
}
项目:autorest.java    文件:DurationsImpl.java   
/**
 * Get a positive duration value.
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the observable to the Period object
 */
public Observable<ServiceResponse<Period>> getPositiveDurationWithServiceResponseAsync() {
    return service.getPositiveDuration()
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Period>>>() {
            @Override
            public Observable<ServiceResponse<Period>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Period> clientResponse = getPositiveDurationDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
项目:azure-libraries-for-java    文件:ServiceBusSubscriptionImpl.java   
@Override
public Period defaultMessageTtlDuration() {
    if (this.inner().defaultMessageTimeToLive() == null) {
        return null;
    }
    TimeSpan timeSpan = TimeSpan.parse(this.inner().defaultMessageTimeToLive());
    return new Period()
            .withDays(timeSpan.days())
            .withHours(timeSpan.hours())
            .withMinutes(timeSpan.minutes())
            .withSeconds(timeSpan.seconds())
            .withMillis(timeSpan.milliseconds());
}
项目:vertx-sfdc-platformevents    文件:ApplicationStarter.java   
/**
 * Executes the actual shutdown once one of the shutdown handlers has
 * accepted the shutdown request
 * 
 * @param response
 *            Tells the caller some metrics
 */
private void shutdownExecution(final HttpServerResponse response) {
    final JsonObject goodby = new JsonObject();
    goodby.put("Goodby", "It was a pleasure doing business with you");
    goodby.put("StartDate", Utils.getDateString(this.startDate));
    goodby.put("EndDate", Utils.getDateString(new Date()));
    final Duration dur = new Duration(new DateTime(this.startDate), new DateTime());
    goodby.put("Duration", PeriodFormat.getDefault().print(new Period(dur)));
    response.putHeader(Constants.CONTENT_HEADER, Constants.CONTENT_TYPE_JSON).setStatusCode(202)
            .end(goodby.encodePrettily());
    try {
        Future<Void> shutdownFuture = Future.future();
        shutdownFuture.setHandler(fResult -> {
            if (fResult.failed()) {
                this.logger.fatal(fResult.cause());
                System.exit(-1);
            }
            this.logger.info("Good by!");
            this.getVertx().close(handler -> {
                if (handler.failed()) {
                    this.logger.fatal(handler.cause());
                }
                System.exit(0);
            });
        });
        this.shutDownVerticles(shutdownFuture);
    } catch (Exception e) {
        this.logger.fatal(e.getMessage(), e);
    }
}
项目:autorest.java    文件:ArraysImpl.java   
/**
 * Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S'].
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the observable to the List&lt;Period&gt; object
 */
public Observable<List<Period>> getDurationValidAsync() {
    return getDurationValidWithServiceResponseAsync().map(new Func1<ServiceResponse<List<Period>>, List<Period>>() {
        @Override
        public List<Period> call(ServiceResponse<List<Period>> response) {
            return response.body();
        }
    });
}
项目:dremio-oss    文件:TestDateTruncFunctions.java   
@Test
public void dateTruncOnIntervalDay() throws Exception {
  final String query = "SELECT " +
      "date_trunc('SECOND', interval '200 10:20:30.123' day(3) to second) as `second`, " +
      "date_trunc('MINUTE', interval '200 10:20:30.123' day(3) to second) as `minute`, " +
      "date_trunc('HOUR', interval '200 10:20:30.123' day(3) to second) as `hour`, " +
      "date_trunc('DAY', interval '200 10:20:30.123' day(3) to second) as `day`, " +
      "date_trunc('MONTH', interval '200 10:20:30.123' day(3) to second) as `month`, " +
      "date_trunc('YEAR', interval '200 10:20:30.123' day(3) to second) as `year`, " +
      "date_trunc('QUARTER', interval '200 10:20:30.123' day(3) to second) as `quarter`, " +
      "date_trunc('DECADE', interval '200 10:20:30.123' day(3) to second) as `decade`, " +
      "date_trunc('CENTURY', interval '200 10:20:30.123' day(3) to second) as `century`, " +
      "date_trunc('MILLENNIUM', interval '200 10:20:30.123' day(3) to second) as `millennium` " +
      "FROM sys.version";

  testBuilder()
      .sqlQuery(query)
      .unOrdered()
      .baselineColumns("second", "minute", "hour", "day", "month", "year", "quarter", "decade", "century", "millennium")
      .baselineValues(
          new Period().plusDays(200).plusMillis(37230000), // seconds
          new Period().plusDays(200).plusMillis(37200000), // minute
          new Period().plusDays(200).plusMillis(36000000), // hour
          new Period().plusDays(200), // day
          new Period("PT0S"), // month
          new Period("PT0S"), // year
          new Period("PT0S"), // quarter
          new Period("PT0S"), // decade
          new Period("PT0S"), // century
          new Period("PT0S")) // millennium
      .go();
}
项目:autorest.java    文件:DictionaryTests.java   
@Test
public void putDurationValid() throws Exception {
    Map<String, Period> testdata = new HashMap<String, Period>();
    testdata.put("0", new Period(0, 0, 0, 123, 22, 14, 12, 11));
    testdata.put("1", new Period(0, 0, 0, 5, 1, 0, 0, 0));
    client.dictionarys().putDurationValid(testdata);
}
项目:autorest.java    文件:DictionarysImpl.java   
/**
 * Set dictionary value  {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}.
 *
 * @param arrayBody the Map&lt;String, Period&gt; value
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<Void> putDurationValidAsync(Map<String, Period> arrayBody) {
    return putDurationValidWithServiceResponseAsync(arrayBody).map(new Func1<ServiceResponse<Void>, Void>() {
        @Override
        public Void call(ServiceResponse<Void> response) {
            return response.body();
        }
    });
}
项目:autorest.java    文件:DurationsImpl.java   
/**
 * Get an invalid duration value.
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the observable to the Period object
 */
public Observable<ServiceResponse<Period>> getInvalidWithServiceResponseAsync() {
    return service.getInvalid()
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Period>>>() {
            @Override
            public Observable<ServiceResponse<Period>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Period> clientResponse = getInvalidDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
项目:autorest.java    文件:HeadersImpl.java   
/**
 * Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S".
 *
 * @param scenario Send a post request with header values "scenario": "valid"
 * @param value Send a post request with header values "P123DT22H14M12.011S"
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<Void> paramDurationAsync(String scenario, Period value) {
    return paramDurationWithServiceResponseAsync(scenario, value).map(new Func1<ServiceResponse<Void>, Void>() {
        @Override
        public Void call(ServiceResponse<Void> response) {
            return response.body();
        }
    });
}
项目:autorest.java    文件:DurationsImpl.java   
/**
 * Get an invalid duration value.
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the observable to the Period object
 */
public Observable<Period> getInvalidAsync() {
    return getInvalidWithServiceResponseAsync().map(new Func1<ServiceResponse<Period>, Period>() {
        @Override
        public Period call(ServiceResponse<Period> response) {
            return response.body();
        }
    });
}
项目:dremio-oss    文件:TestDateTruncFunctions.java   
@Test
public void dateTruncOnIntervalYear() throws Exception {
  final String query = "SELECT " +
      "date_trunc('SECOND', interval '217-7' year(3) to month) as `second`, " +
      "date_trunc('MINUTE', interval '217-7' year(3) to month) as `minute`, " +
      "date_trunc('HOUR', interval '217-7' year(3) to month) as `hour`, " +
      "date_trunc('DAY', interval '217-7' year(3) to month) as `day`, " +
      "date_trunc('MONTH', interval '217-7' year(3) to month) as `month`, " +
      "date_trunc('YEAR', interval '217-7' year(3) to month) as `year`, " +
      "date_trunc('QUARTER', interval '217-7' year(3) to month) as `quarter`, " +
      "date_trunc('DECADE', interval '217-7' year(3) to month) as `decade`, " +
      "date_trunc('CENTURY', interval '217-7' year(3) to month) as `century`, " +
      "date_trunc('MILLENNIUM', interval '217-7' year(3) to month) as `millennium` " +
      "FROM sys.version";

  testBuilder()
      .sqlQuery(query)
      .unOrdered()
      .baselineColumns("second", "minute", "hour", "day", "month", "year", "quarter", "decade", "century", "millennium")
      .baselineValues(
          new Period("P217Y7M").normalizedStandard(), // seconds
          new Period("P217Y7M").normalizedStandard(), // minute
          new Period("P217Y7M").normalizedStandard(), // hour
          new Period("P217Y7M").normalizedStandard(), // day
          new Period("P217Y7M").normalizedStandard(), // month
          new Period("P217Y").normalizedStandard(), // year
          new Period("P217Y6M").normalizedStandard(), // quarter
          new Period("P210Y").normalizedStandard(), // decade
          new Period("P200Y").normalizedStandard(), // century
          new Period("PT0S").normalizedStandard()) // millennium
      .go();
}
项目:cloud-s4-sdk-examples    文件:CostCenterServiceIntegrationTest.java   
private static String generateId() {
    return "T"
            + StringUtils.leftPad(
            Long.toString(new DateTime().minus(Period.years(45)).getMillis(), 36).toUpperCase(),
            9,
            '0');
}
项目:Sound.je    文件:JodaPeriodSplitBridge.java   
@Override
public void save(final String name,
                 final Object value,
                 final BridgeController.Presets presets) {
    if (value != null) {
        final Period period = (Period) value;
        presets.recordPeriod(period);
    } else {
        presets.recordPeriod(new Period(0));
    }
}
项目:dremio-oss    文件:ExpressionStringBuilder.java   
@Override
public Void visitIntervalYearConstant(IntervalYearExpression lExpr, StringBuilder sb) throws RuntimeException {
  sb.append("cast( '");
  sb.append(Period.months(lExpr.getIntervalYear()).toString());
  sb.append("' as INTERVALYEAR)");
  return null;
}
项目:autorest.java    文件:ArraysImpl.java   
/**
 * Set array value  ['P123DT22H14M12.011S', 'P5DT1H0M0S'].
 *
 * @param arrayBody the List&lt;Period&gt; value
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<Void> putDurationValidAsync(List<Period> arrayBody) {
    return putDurationValidWithServiceResponseAsync(arrayBody).map(new Func1<ServiceResponse<Void>, Void>() {
        @Override
        public Void call(ServiceResponse<Void> response) {
            return response.body();
        }
    });
}
项目:azure-libraries-for-java    文件:TopicImpl.java   
@Override
public TopicImpl withDuplicateMessageDetectionHistoryDuration(Period duration) {
    this.inner().withDuplicateDetectionHistoryTimeWindow(TimeSpan
            .fromPeriod(duration)
            .toString());
    // Below shortcut cannot be used as 'withRequiresDuplicateDetection' cannot be changed
    // once the topic is created.
    // return withDuplicateMessageDetection(duration);
    return this;
}
项目:Sound.je    文件:JodaPeriodSplitBridge.java   
@Override
public Object get(final String name, final Document document) {
    final IndexableField stringPeriod = document.getField(name);
    if (stringPeriod != null) {
        return Period.seconds((Integer) stringPeriod.numericValue());
    } else {
        return null;
    }
}
项目:ThunderMusic    文件:OnlineTotalSearchTask.java   
private int convertTime(String time) {
    PeriodFormatter formatter = ISOPeriodFormat.standard();
    Period p = formatter.parsePeriod(time);
    Seconds s = p.toStandardSeconds();

    return s.getSeconds();
}
项目:hyperrail-for-android    文件:Route.java   
public Duration getDuration() {
    return new Period(getDepartureTime(), getArrivalTime()).toStandardDuration();
}
项目:elasticsearch_my    文件:TimeValue.java   
public String format() {
    Period period = new Period(millis());
    return defaultFormatter.print(period);
}
项目:autorest.java    文件:HeaderOperationsTests.java   
@Test
public void paramDuration() throws Exception {
    client.headers().paramDuration("valid", new Period(0, 0, 0, 123, 22, 14, 12, 11));
}
项目:mod-circulation-storage    文件:LoansApiTest.java   
@Test
public void canCompleteALoanByReturningTheItem()
  throws InterruptedException,
  MalformedURLException,
  TimeoutException,
  ExecutionException,
  UnsupportedEncodingException {

  DateTime loanDate = new DateTime(2017, 3, 1, 13, 25, 46, 232, DateTimeZone.UTC);

  IndividualResource loan = createLoan(new LoanRequestBuilder()
    .withLoanDate(loanDate)
    .withdueDate(loanDate.plus(Period.days(14)))
    .create());

  JsonObject returnedLoan = loan.copyJson();

  returnedLoan
    .put("status", new JsonObject().put("name", "Closed"))
    .put("action", "checkedin")
    .put("itemStatus", "Available")
    .put("returnDate", new DateTime(2017, 3, 5, 14, 23, 41, DateTimeZone.UTC)
    .toString(ISODateTimeFormat.dateTime()));

  CompletableFuture<JsonResponse> putCompleted = new CompletableFuture();

  client.put(loanStorageUrl(String.format("/%s", loan.getId())), returnedLoan,
    StorageTestSuite.TENANT_ID, ResponseHandler.json(putCompleted));

  JsonResponse putResponse = putCompleted.get(5, TimeUnit.SECONDS);

  assertThat(String.format("Failed to update loan: %s", putResponse.getBody()),
    putResponse.getStatusCode(), is(HttpURLConnection.HTTP_NO_CONTENT));

  JsonResponse updatedLoanResponse = getById(UUID.fromString(loan.getId()));

  JsonObject updatedLoan = updatedLoanResponse.getJson();

  assertThat(updatedLoan.getString("returnDate"),
    is("2017-03-05T14:23:41.000Z"));

  assertThat("status is not closed",
    updatedLoan.getJsonObject("status").getString("name"), is("Closed"));

  assertThat("item status is not available",
    updatedLoan.getString("itemStatus"), is("Available"));

  assertThat("action is not checkedin",
    updatedLoan.getString("action"), is("checkedin"));
}
项目:azure-libraries-for-java    文件:ServiceBusOperationsTests.java   
@Test
public void canCreateNamespaceThenCRUDOnQueue() {
    Region region = Region.US_EAST;
    Creatable<ResourceGroup> rgCreatable = resourceManager.resourceGroups()
            .define(RG_NAME)
            .withRegion(region);

    String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15);
    ServiceBusNamespace namespace = serviceBusManager.namespaces()
            .define(namespaceDNSLabel)
            .withRegion(region)
            .withNewResourceGroup(rgCreatable)
            .withSku(NamespaceSku.PREMIUM_CAPACITY1)
            .create();
    Assert.assertNotNull(namespace);
    Assert.assertNotNull(namespace.inner());

    String queueName = generateRandomResourceName("queue1-", 15);
    Queue queue = namespace.queues()
            .define(queueName)
            .create();

    Assert.assertNotNull(queue);
    Assert.assertNotNull(queue.inner());
    Assert.assertNotNull(queue.name());
    Assert.assertTrue(queue.name().equalsIgnoreCase(queueName));
    // Default lock duration is 1 minute, assert TimeSpan("00:01:00") parsing
    //
    Assert.assertEquals("00:01:00", queue.inner().lockDuration());
    Assert.assertEquals(60, queue.lockDurationInSeconds());

    Period dupDetectionDuration = queue.duplicateMessageDetectionHistoryDuration();
    Assert.assertNotNull(dupDetectionDuration);
    Assert.assertEquals(10, dupDetectionDuration.getMinutes());
    // Default message TTL is TimeSpan.Max, assert parsing
    //
    Assert.assertEquals("10675199.02:48:05.4775807", queue.inner().defaultMessageTimeToLive());
    Period msgTtlDuration = queue.defaultMessageTtlDuration();
    Assert.assertNotNull(msgTtlDuration);
    // Assert the default ttl TimeSpan("10675199.02:48:05.4775807") parsing
    //
    Assert.assertEquals(10675199, msgTtlDuration.getDays());
    Assert.assertEquals(2, msgTtlDuration.getHours());
    Assert.assertEquals(48, msgTtlDuration.getMinutes());
    // Assert the default max size In MB
    //
    Assert.assertEquals(1024, queue.maxSizeInMB());

    PagedList<Queue> queuesInNamespace = namespace.queues().list();
    Assert.assertNotNull(queuesInNamespace);
    Assert.assertTrue(queuesInNamespace.size() > 0);
    Queue foundQueue = null;
    for (Queue q : queuesInNamespace) {
        if (q.name().equalsIgnoreCase(queueName)) {
            foundQueue = q;
            break;
        }
    }
    Assert.assertNotNull(foundQueue);
    // Dead lettering disabled by default
    //
    Assert.assertFalse(foundQueue.isDeadLetteringEnabledForExpiredMessages());
    foundQueue = foundQueue.update()
            .withMessageLockDurationInSeconds(120)
            .withDefaultMessageTTL(new Period().withMinutes(20))
            .withExpiredMessageMovedToDeadLetterQueue()
            .withMessageMovedToDeadLetterQueueOnMaxDeliveryCount(25)
            .apply();
    Assert.assertEquals(120, foundQueue.lockDurationInSeconds());
    Assert.assertTrue(foundQueue.isDeadLetteringEnabledForExpiredMessages());
    Assert.assertEquals(25, foundQueue.maxDeliveryCountBeforeDeadLetteringMessage());
    namespace.queues().deleteByName(foundQueue.name());
}
项目:azure-libraries-for-java    文件:ServiceBusOperationsTests.java   
@Test
public void canCreateNamespaceThenCRUDOnTopic() {
    Region region = Region.US_EAST;
    Creatable<ResourceGroup> rgCreatable = resourceManager.resourceGroups()
            .define(RG_NAME)
            .withRegion(region);

    String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15);
    ServiceBusNamespace namespace = serviceBusManager.namespaces()
            .define(namespaceDNSLabel)
            .withRegion(region)
            .withNewResourceGroup(rgCreatable)
            .withSku(NamespaceSku.STANDARD)
            .create();
    Assert.assertNotNull(namespace);
    Assert.assertNotNull(namespace.inner());

    String topicName = generateRandomResourceName("topic1-", 15);
    Topic topic = namespace.topics()
            .define(topicName)
            .create();

    Assert.assertNotNull(topic);
    Assert.assertNotNull(topic.inner());
    Assert.assertNotNull(topic.name());
    Assert.assertTrue(topic.name().equalsIgnoreCase(topicName));

    Period dupDetectionDuration = topic.duplicateMessageDetectionHistoryDuration();
    Assert.assertNotNull(dupDetectionDuration);
    Assert.assertEquals(10, dupDetectionDuration.getMinutes());
    // Default message TTL is TimeSpan.Max, assert parsing
    //
    Assert.assertEquals("10675199.02:48:05.4775807", topic.inner().defaultMessageTimeToLive());
    Period msgTtlDuration = topic.defaultMessageTtlDuration();
    Assert.assertNotNull(msgTtlDuration);
    // Assert the default ttl TimeSpan("10675199.02:48:05.4775807") parsing
    //
    Assert.assertEquals(10675199, msgTtlDuration.getDays());
    Assert.assertEquals(2, msgTtlDuration.getHours());
    Assert.assertEquals(48, msgTtlDuration.getMinutes());
    // Assert the default max size In MB
    //
    Assert.assertEquals(1024, topic.maxSizeInMB());

    PagedList<Topic> topicsInNamespace = namespace.topics().list();
    Assert.assertNotNull(topicsInNamespace);
    Assert.assertTrue(topicsInNamespace.size() > 0);
    Topic foundTopic = null;
    for (Topic t : topicsInNamespace) {
        if (t.name().equalsIgnoreCase(topic.name())) {
            foundTopic = t;
            break;
        }
    }
    Assert.assertNotNull(foundTopic);
    foundTopic = foundTopic.update()
            .withDefaultMessageTTL(new Period().withMinutes(20))
            .withDuplicateMessageDetectionHistoryDuration(new Period().withMinutes(15))
            .withDeleteOnIdleDurationInMinutes(25)
            .apply();
    Period ttlDuration = foundTopic.defaultMessageTtlDuration();
    Assert.assertNotNull(ttlDuration);
    Assert.assertEquals(20, ttlDuration.getMinutes());
    Period duplicateDetectDuration = foundTopic.duplicateMessageDetectionHistoryDuration();
    Assert.assertNotNull(duplicateDetectDuration);
    Assert.assertEquals(15, duplicateDetectDuration.getMinutes());
    Assert.assertEquals(25, foundTopic.deleteOnIdleDurationInMinutes());
    // Delete
    namespace.topics().deleteByName(foundTopic.name());
}
项目:QDrill    文件:DateUtility.java   
public static int millisFromPeriod(final Period period){
  return (period.getHours() * hoursToMillis) +
  (period.getMinutes() * minutesToMillis) +
  (period.getSeconds() * secondsToMillis) +
  (period.getMillis());
}
项目:autorest.java    文件:DictionarysImpl.java   
private ServiceResponse<Map<String, Period>> getDurationValidDelegate(Response<ResponseBody> response) throws ErrorException, IOException {
    return this.client.restClient().responseBuilderFactory().<Map<String, Period>, ErrorException>newInstance(this.client.serializerAdapter())
            .register(200, new TypeToken<Map<String, Period>>() { }.getType())
            .registerError(ErrorException.class)
            .build(response);
}
项目:dremio-oss    文件:BasicJsonOutput.java   
@Override
public void writeInterval(Period value) throws IOException {
  gen.writeString(value.toString(ISOPeriodFormat.standard()));
}
项目:gocd-elastic-agent-marathon    文件:CreateAgentRequestExecutor.java   
@Override
public GoPluginApiResponse execute() throws Exception {
    /*
    The logic here is that the go server has a list of agents, but
    not a definitive view of which of those agents is actually
    running.  This means that this plugin is sent a createAgentRequest
    for every matching job being scheduled.

    The housekeeping we do to prevent over-creating new instances is to
    get a list of agents from the go server, find idle ones in the list,
    and match to the corresponding instance running on marathon.  If the
    instance running on marathon would satisfy the request, we do not create
    a new instance.

    In the case where we might get multiple createAgentRequests in a short
    period of time, we mark the instance as recently matched so it is not
    eligible to match for subsequent requests.

    This isn't perfect - we might mark one and then the job actually gets
    scheduled to another agent.  In the long term, the go agents will use
    web sockets, the go server will know which ones are still running, and
    we can drop this logic here.
     */

    boolean agentMatch = false;
    for (Agent agent: pluginRequest.listAgents().agents()) {
        if (!agentIdle(agent)) {
            continue;
        }
        MarathonInstance instance = (MarathonInstance)agentInstances.find(agent.elasticAgentId());
        if (instance == null) {
            continue;
        }
        if (!propertiesMatch(instance.properties(), request.properties())) {
            continue;
        }
        // Recently matched to an outstanding task
        if (instance.getLastMatched().isAfter(new DateTime().minus(new Period("PT30S")))) {
            continue;
        }
        agentMatch = true;
        instance.setLastMatched(new DateTime());
        break;
    }
    if (!agentMatch) {
        agentInstances.create(request, pluginRequest.getPluginSettings());
    }
    return new DefaultGoPluginApiResponse(200);
}
项目:autorest.java    文件:DictionarysImpl.java   
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydictionary.Dictionarys putDurationValid" })
@PUT("dictionary/prim/duration/valid")
Observable<Response<ResponseBody>> putDurationValid(@Body Map<String, Period> arrayBody);