List of usage examples for org.joda.time Duration getMillis
public long getMillis()
From source file:org.thiesen.jiffs.jobs.fetcher.SubscriptionFetcher.java
License:Open Source License
private DateTime increase(Duration duration) { if (duration.getMillis() >= MAX_CHECK_TIME_MILLIS) { return new DateTime().plus(MAX_CHECK_TIME_MILLIS); }/*from www. j a v a 2 s. c o m*/ return new DateTime().plus(duration.plus(CHECK_TIME_STEPPING_MILLIS)); }
From source file:org.vaadin.testbenchsauce.BaseTestBenchTestCase.java
private void updateRallyTestCase(String testCaseId, ITestResult testResult) throws URISyntaxException, IOException { //Rally API Setup RallyRestApi restApi = new RallyRestApi(new URI(RALLY_SERVER_URL), RALLY_USERNAME, RALLY_PASSWORD); restApi.setApplicationName("VaadinTestBench"); int status = testResult.getStatus(); String verdict = null;//ww w . jav a2 s .c o m if (status == ITestResult.FAILURE) { verdict = "Fail"; } else if (status == ITestResult.SUCCESS) { verdict = "Pass"; } else { //For now if it's not a failure or success, don't update rally return; } Duration duration = new Duration(testResult.getStartMillis(), testResult.getEndMillis()); try { //Get a reference to the test case QueryRequest testCaseRequest = new QueryRequest("TestCase"); testCaseRequest.setFetch(new Fetch("FormattedID", "Name")); testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testCaseId)); QueryResponse testCaseResponse = restApi.query(testCaseRequest); if (testCaseResponse.getTotalResultCount() <= 0) { System.out.println("WARNING: Could not add test result to Rally test case '" + testCaseId + "' because it was not found."); return; } JsonObject testCaseJsonObject = testCaseResponse.getResults().get(0).getAsJsonObject(); String testCaseRef = testCaseJsonObject.get("_ref").getAsString(); //Add a test result to that test case JsonObject testCaseResult = new JsonObject(); testCaseResult.addProperty("Verdict", verdict); testCaseResult.addProperty("Build", JENKINS_BUILD_NUMBER); testCaseResult.addProperty("TestCase", testCaseRef); testCaseResult.addProperty("Date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(new Date())); testCaseResult.addProperty("Duration", duration.getMillis()); //rallyTestCaseIntegration(SolutionsTabUiTest) String methodName = testResult.getName(); Class realClass = testResult.getTestClass().getRealClass(); String jobHref = "<b><a target='_blank' href=\"" + JENKINS_BUILD_URL + "\">Jenkins Job</a></b>"; //testngreports/<package>/<package>.<Class>/<methodName>/ String testUrl = JENKINS_BUILD_URL + "testngreports/" + realClass.getPackage().getName() + "/" + realClass.getName() + "/" + methodName + "/"; String testHref = "<a target='_blank' href=\"" + testUrl + "\">" + "Test Method: " + methodName + "(" + realClass.getSimpleName() + ")" + "</a>"; String notes = jobHref + " " + testHref; notes += "<div><b>Release Build Test Output:</b></div>"; notes += getHtmlTestOutput(testResult); if (!testResult.isSuccess()) { notes += "<div style='color:red;'><b>Failure Details:</b></div>"; notes += ExceptionUtils.getStackTrace(testResult.getThrowable()); } testCaseResult.addProperty("Notes", notes); CreateRequest createTestResultRequest = new CreateRequest("testcaseresult", testCaseResult); CreateResponse createTestResultResponse = restApi.create(createTestResultRequest); //Output response if (createTestResultResponse.wasSuccessful()) { System.out.println("Created test result for Rally test case '" + testCaseId + "' - " + testCaseRef); } else { String[] createErrors; createErrors = createTestResultResponse.getErrors(); System.out.println( "WARNING: Error occurred creating Rally test case result for '" + testCaseId + "'"); for (int i = 0; i < createErrors.length; i++) { System.out.println(createErrors[i]); } } } finally { restApi.close(); } }
From source file:org.waarp.gateway.kernel.rest.RestArgument.java
License:Open Source License
/** * Check Time only (no signature)// w w w .ja v a 2 s. c o m * * @param maxInterval * @throws HttpInvalidAuthenticationException */ public void checkTime(long maxInterval) throws HttpInvalidAuthenticationException { DateTime dateTime = new DateTime(); String date = getXAuthTimestamp(); if (date != null && !date.isEmpty()) { DateTime received = DateTime.parse(date); if (maxInterval > 0) { Duration duration = new Duration(received, dateTime); if (Math.abs(duration.getMillis()) >= maxInterval) { throw new HttpInvalidAuthenticationException( "timestamp is not compatible with the maximum delay allowed"); } } } else if (maxInterval > 0) { throw new HttpInvalidAuthenticationException("timestamp absent while required"); } }
From source file:org.waarp.gateway.kernel.rest.RestArgument.java
License:Open Source License
/** * This implementation of authentication is as follow: if X_AUTH is included in the URI or Header<br> * 0) Check that timestamp is correct (|curtime - timestamp| < maxinterval) from ARG_X_AUTH_TIMESTAMP, if maxInterval is 0, * not mandatory<br>// ww w .ja v a 2s.c om * 1) Get all URI args (except ARG_X_AUTH_KEY itself, but including timestamp), lowered case, in alphabetic order<br> * 2) Add an extra Key if not null (from ARG_X_AUTH_INTERNALKEY)<br> * 3) Compute an hash (SHA-1 or SHA-256)<br> * 4) Compare this hash with ARG_X_AUTH_KEY<br> * * @param hmacSha256 * SHA-256 key to create the signature * @param extraKey * will be added as ARG_X_AUTH_INTERNALKEY might be null * @param maxInterval * ARG_X_AUTH_TIMESTAMP will be tested if value > 0 * @throws HttpInvalidAuthenticationException * if the authentication failed */ public void checkBaseAuthent(HmacSha256 hmacSha256, String extraKey, long maxInterval) throws HttpInvalidAuthenticationException { TreeMap<String, String> treeMap = new TreeMap<String, String>(); String argPath = getUri(); ObjectNode arguri = getUriArgs(); if (arguri == null) { throw new HttpInvalidAuthenticationException("Not enough argument"); } Iterator<Entry<String, JsonNode>> iterator = arguri.fields(); DateTime dateTime = new DateTime(); DateTime received = null; while (iterator.hasNext()) { Entry<String, JsonNode> entry = iterator.next(); String key = entry.getKey(); if (key.equalsIgnoreCase(REST_ROOT_FIELD.ARG_X_AUTH_KEY.field)) { continue; } JsonNode values = entry.getValue(); if (key.equalsIgnoreCase(REST_ROOT_FIELD.ARG_X_AUTH_TIMESTAMP.field)) { received = DateTime.parse(values.asText()); } String keylower = key.toLowerCase(); if (values != null) { String val = null; if (values.isArray()) { JsonNode jsonNode = values.get(values.size() - 1); val = jsonNode.asText(); } else { val = values.asText(); } treeMap.put(keylower, val); } } if (received == null) { String date = getXAuthTimestamp(); received = DateTime.parse(date); treeMap.put(REST_ROOT_FIELD.ARG_X_AUTH_TIMESTAMP.field.toLowerCase(), date); } String user = getXAuthUser(); if (user != null && !user.isEmpty()) { treeMap.put(REST_ROOT_FIELD.ARG_X_AUTH_USER.field.toLowerCase(), user); } if (maxInterval > 0 && received != null) { Duration duration = new Duration(received, dateTime); if (Math.abs(duration.getMillis()) >= maxInterval) { throw new HttpInvalidAuthenticationException( "timestamp is not compatible with the maximum delay allowed"); } } else if (maxInterval > 0) { throw new HttpInvalidAuthenticationException("timestamp absent while required"); } String key = computeKey(hmacSha256, extraKey, treeMap, argPath); if (!key.equalsIgnoreCase(getXAuthKey())) { throw new HttpInvalidAuthenticationException("Invalid Authentication Key"); } }
From source file:org.zkoss.ganttz.util.Interval.java
License:Open Source License
private Fraction inTheDayIncrement(DateTime date) { DateTime atStartOfDay = date.toLocalDate().toDateTimeAtStartOfDay(); Duration duration = new Duration(atStartOfDay, date); double result = ((double) duration.getMillis()) / lengthBetween.getMillis(); return Fraction.getFraction(result); }
From source file:petascope.util.TimeUtil.java
License:Open Source License
/** * Verifies that the two input timestamps define a valid interval. * * @param timestampLo timestamp//from w ww .java2 s. c om * @param timestampHi timestamp * @return True if Lo is lower or equal than Hi * @throws PetascopeException */ public static boolean isOrderedTimeSubset(String timestampLo, String timestampHi) throws PetascopeException { DateTime dtLo = isoFmt.parseDateTime(fix(timestampLo)); DateTime dtHi = isoFmt.parseDateTime(fix(timestampHi)); Duration millis; try { millis = new Duration(dtLo, dtHi); } catch (ArithmeticException ex) { log.error("Error while computing milliseconds between " + dtLo + " and " + dtHi + "."); throw new PetascopeException(ExceptionCode.InternalComponentError, "Cannot convert input datetimes to numeric time coordinates: duration exceeds a 64 bit long.", ex); } return (millis.getMillis() >= 0); }
From source file:petascope.util.TimeUtil.java
License:Open Source License
/** * Count how many temporal units (i.e. offset vectors) fit inside a time interval. * * @param timestampLo Lower ISO timestamp * @param timestampHi Upper ISO timestamp * @param timeResolution Temporal UoM of the CRS * @param timeVector Length of the offset vector along time [TIME(n) := timeEpoch + n*(timeResolution*timeVector)] * @return How many time units (with fractional resolution) fit into the time interval [timestampHi-timestampLo] * @throws PetascopeException/*from w ww. j a v a 2 s . co m*/ */ public static Double countOffsets(String timestampLo, String timestampHi, String timeResolution, Double timeVector) throws PetascopeException { // local variables Double fractionalTimeSteps; DateTime dtLo = isoFmt.parseDateTime(fix(timestampLo)); DateTime dtHi = isoFmt.parseDateTime(fix(timestampHi)); // Determine milliseconds between these two datetimes Duration millis; try { millis = new Duration(dtLo, dtHi); } catch (ArithmeticException ex) { log.error("Error while computing milliseconds between " + dtLo + " and " + dtHi + "."); throw new PetascopeException(ExceptionCode.InternalComponentError, "Cannot convert input datetimes to numeric time coordinates: duration exceeds a 64 bit long.", ex); } // Compute how many vectors of distance are there between dtLo and dtHi along this time CRS // NOTE: not necessarily an integer number of vectors will fit in the interval, clearly. // Formula: // fractionalTimeSteps := milliseconds(lo,hi) / [milliseconds(offset_vector)] // WHERE milliseconds(offset_vector) := milliseconds(timeResolution) * vector_length Long vectorMillis = (long) (getMillis(timeResolution) * timeVector); fractionalTimeSteps = 1D * millis.getMillis() / vectorMillis; log.debug("Computed " + fractionalTimeSteps + " offset-vectors between " + dtLo + " and " + dtHi + "."); return fractionalTimeSteps; }
From source file:propel.core.utils.ConversionUtils.java
License:Open Source License
/** * Converts a Joda Duration object to an XML Duration data type *//*from w ww. j a v a 2 s . c om*/ @Validate public static javax.xml.datatype.Duration toXMLDuration(@NotNull final Duration value) throws DatatypeConfigurationException { return DatatypeFactory.newInstance().newDuration(value.getMillis()); }
From source file:propel.core.utils.ConversionUtils.java
License:Open Source License
/** * Returns the value of the given timespan in a human-readable form, appending the suffix. * /*from w w w . j a va2s . c om*/ * <pre> * Example: 10 seconds become "less than a minute". * Example: 1.1 minutes become "about a minute from now". * Example: 50 minutes become "50 minutes". * Example: 13 hours, 10 minutes become "about 13 hours". * The suffix " ago" or " from now" is appended depending on the sign of the timespan. * </pre> */ @Validate public static String toHumanReadable(@NotNull Duration ts) { String suffix = " ago"; if (ts.getMillis() < 0.0) { // negate ts = new Duration(-ts.getMillis()); // indicate this is suffix = " from now"; } return toHumanReadable(ts, suffix); }
From source file:pt.ist.expenditureTrackingSystem.domain.organization.UserAcquisitionProcessStatistics.java
License:Open Source License
public void setPaymentProcessYear(PaymentProcessYear paymentProcessYear) { this.paymentProcessYear = paymentProcessYear; processTypeMap.clear();/*w w w .j a va 2 s .co m*/ numberOfParticipatedProcesses = 0; numberOfActivities = 0; totalActivityDuration = 0; numberOfActivitiesForAverage = 0; if (paymentProcessYear != null) { for (final PaymentProcess paymentProcess : paymentProcessYear.getPaymentProcessSet()) { if (participated(paymentProcess)) { numberOfParticipatedProcesses++; final String processType = getProcessType(paymentProcess); UserAcquisitionProcessTypeStatistics userAcquisitionProcessTypeStatistics = getUserAcquisitionProcessTypeStatistics( processType); userAcquisitionProcessTypeStatistics.registerProcessParticipation(); paymentProcess.getExecutionLogStream().filter(l -> l.getActivityExecutor() == user) .forEach(new Consumer<WorkflowLog>() { @Override public void accept(WorkflowLog workflowLog) { numberOfActivities++; userAcquisitionProcessTypeStatistics.registerActivity(); final Duration duration = workflowLog.getDurationFromPreviousLog(); if (duration != null) { long millis = duration.getMillis(); totalActivityDuration += millis; numberOfActivitiesForAverage++; userAcquisitionProcessTypeStatistics.registerActivity(millis); } } }); } } } }