List of usage examples for java.util.concurrent TimeUnit DAYS
TimeUnit DAYS
To view the source code for java.util.concurrent TimeUnit DAYS.
Click Source Link
From source file:com.asakusafw.operation.tools.hadoop.fs.CleanTest.java
private File touch(String path, double day) throws IOException { File file = file(path);/*from ww w . java 2s .c o m*/ if (file.exists() == false) { file.getParentFile().mkdirs(); try { file.createNewFile(); } catch (IOException e) { throw new AssertionError(e); } } File root = folder.getRoot().getCanonicalFile(); File current = file; while (true) { current = current.getCanonicalFile(); if (root.equals(current)) { break; } boolean succeed = current.setLastModified((long) (day * TimeUnit.DAYS.toMillis(1))); if (succeed == false) { break; } current = current.getParentFile(); if (current == null) { break; } } return file; }
From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java
/** Builds the default request handlers **/ private PathTrie<RequestHandler> defaultHandlers(final Map<String, Bucket> buckets, final Bucket ec2Bucket, final Bucket ecsBucket) { final PathTrie<RequestHandler> handlers = new PathTrie<>(RestUtils.REST_DECODER); // HEAD Object ///*w w w . j av a2s . co m*/ // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html objectsPaths(authPath(HttpHead.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) { if (object.getKey().equals(objectName)) { return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } } return newObjectNotFoundError(request.getId(), objectName); })); // PUT Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html objectsPaths(authPath(HttpPut.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String destBucketName = request.getParam("bucket"); final Bucket destBucket = buckets.get(destBucketName); if (destBucket == null) { return newBucketNotFoundError(request.getId(), destBucketName); } final String destObjectName = objectName(request.getParameters()); // This is a chunked upload request. We should have the header "Content-Encoding : aws-chunked,gzip" // to detect it but it seems that the AWS SDK does not follow the S3 guidelines here. // // See https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html // String headerDecodedContentLength = request.getHeader("X-amz-decoded-content-length"); if (headerDecodedContentLength != null) { int contentLength = Integer.valueOf(headerDecodedContentLength); // Chunked requests have a payload like this: // // 105;chunk-signature=01d0de6be013115a7f4794db8c4b9414e6ec71262cc33ae562a71f2eaed1efe8 // ... bytes of data .... // 0;chunk-signature=f890420b1974c5469aaf2112e9e6f2e0334929fd45909e03c0eff7a84124f6a4 // try (BufferedInputStream inputStream = new BufferedInputStream( new ByteArrayInputStream(request.getBody()))) { int b; // Moves to the end of the first signature line while ((b = inputStream.read()) != -1) { if (b == '\n') { break; } } final byte[] bytes = new byte[contentLength]; inputStream.read(bytes, 0, contentLength); destBucket.objects.put(destObjectName, bytes); return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } } return newInternalError(request.getId(), "Something is wrong with this PUT request"); })); // DELETE Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html objectsPaths(authPath(HttpDelete.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); bucket.objects.remove(objectName); return new Response(RestStatus.NO_CONTENT.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); })); // GET Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html objectsPaths(authPath(HttpGet.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); if (bucket.objects.containsKey(objectName)) { return new Response(RestStatus.OK.getStatus(), contentType("application/octet-stream"), bucket.objects.get(objectName)); } return newObjectNotFoundError(request.getId(), objectName); })); // HEAD Bucket // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html handlers.insert(authPath(HttpHead.METHOD_NAME, "/{bucket}"), (request) -> { String bucket = request.getParam("bucket"); if (Strings.hasText(bucket) && buckets.containsKey(bucket)) { return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } else { return newBucketNotFoundError(request.getId(), bucket); } }); // GET Bucket (List Objects) Version 1 // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html handlers.insert(authPath(HttpGet.METHOD_NAME, "/{bucket}/"), (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } String prefix = request.getParam("prefix"); if (prefix == null) { prefix = request.getHeader("Prefix"); } return newListBucketResultResponse(request.getId(), bucket, prefix); }); // Delete Multiple Objects // // https://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html handlers.insert(nonAuthPath(HttpPost.METHOD_NAME, "/"), (request) -> { final List<String> deletes = new ArrayList<>(); final List<String> errors = new ArrayList<>(); if (request.getParam("delete") != null) { // The request body is something like: // <Delete><Object><Key>...</Key></Object><Object><Key>...</Key></Object></Delete> String requestBody = Streams .copyToString(new InputStreamReader(new ByteArrayInputStream(request.getBody()), UTF_8)); if (requestBody.startsWith("<Delete>")) { final String startMarker = "<Key>"; final String endMarker = "</Key>"; int offset = 0; while (offset != -1) { offset = requestBody.indexOf(startMarker, offset); if (offset > 0) { int closingOffset = requestBody.indexOf(endMarker, offset); if (closingOffset != -1) { offset = offset + startMarker.length(); final String objectName = requestBody.substring(offset, closingOffset); boolean found = false; for (Bucket bucket : buckets.values()) { if (bucket.objects.containsKey(objectName)) { final Response authResponse = authenticateBucket(request, bucket); if (authResponse != null) { return authResponse; } bucket.objects.remove(objectName); found = true; } } if (found) { deletes.add(objectName); } else { errors.add(objectName); } } } } return newDeleteResultResponse(request.getId(), deletes, errors); } } return newInternalError(request.getId(), "Something is wrong with this POST multiple deletes request"); }); // non-authorized requests TriFunction<String, String, String, Response> credentialResponseFunction = (profileName, key, token) -> { final Date expiration = new Date(new Date().getTime() + TimeUnit.DAYS.toMillis(1)); final String response = "{" + "\"AccessKeyId\": \"" + key + "\"," + "\"Expiration\": \"" + DateUtils.formatISO8601Date(expiration) + "\"," + "\"RoleArn\": \"" + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"SecretAccessKey\": \"" + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"Token\": \"" + token + "\"" + "}"; final Map<String, String> headers = new HashMap<>(contentType("application/json")); return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8)); }; // GET // // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/"), (request) -> { final String response = EC2_PROFILE; final Map<String, String> headers = new HashMap<>(contentType("text/plain")); return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8)); }); // GET // // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html handlers.insert( nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/{profileName}"), (request) -> { final String profileName = request.getParam("profileName"); if (EC2_PROFILE.equals(profileName) == false) { return new Response(RestStatus.NOT_FOUND.getStatus(), new HashMap<>(), "unknown profile".getBytes(UTF_8)); } return credentialResponseFunction.apply(profileName, ec2Bucket.key, ec2Bucket.token); }); // GET // // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/ecs_credentials_endpoint"), (request) -> credentialResponseFunction.apply("CPV_ECS", ecsBucket.key, ecsBucket.token)); return handlers; }
From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java
@Test public void testRaftActorForwardsToRaftActorSnapshotMessageSupport() { String persistenceId = factory.generateActorId("leader-"); DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); RaftActorSnapshotMessageSupport mockSupport = mock(RaftActorSnapshotMessageSupport.class); TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId) .config(config).snapshotMessageSupport(mockSupport).props()); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); // Wait for akka's recovery to complete so it doesn't interfere. mockRaftActor.waitForRecoveryComplete(); ApplySnapshot applySnapshot = new ApplySnapshot(mock(Snapshot.class)); doReturn(true).when(mockSupport).handleSnapshotMessage(same(applySnapshot), any(ActorRef.class)); mockRaftActor.handleCommand(applySnapshot); CaptureSnapshot captureSnapshot = new CaptureSnapshot(1, 1, 1, 1, 0, 1, null); doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshot), any(ActorRef.class)); mockRaftActor.handleCommand(captureSnapshot); CaptureSnapshotReply captureSnapshotReply = new CaptureSnapshotReply(new byte[0]); doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshotReply), any(ActorRef.class)); mockRaftActor.handleCommand(captureSnapshotReply); SaveSnapshotSuccess saveSnapshotSuccess = new SaveSnapshotSuccess(new SnapshotMetadata("", 0L, 0L)); doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess), any(ActorRef.class)); mockRaftActor.handleCommand(saveSnapshotSuccess); SaveSnapshotFailure saveSnapshotFailure = new SaveSnapshotFailure(new SnapshotMetadata("", 0L, 0L), new Throwable()); doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure), any(ActorRef.class)); mockRaftActor.handleCommand(saveSnapshotFailure); doReturn(true).when(mockSupport)/*ww w . j a v a 2 s . c o m*/ .handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT), any(ActorRef.class)); mockRaftActor.handleCommand(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT); doReturn(true).when(mockSupport).handleSnapshotMessage(same(GetSnapshot.INSTANCE), any(ActorRef.class)); mockRaftActor.handleCommand(GetSnapshot.INSTANCE); verify(mockSupport).handleSnapshotMessage(same(applySnapshot), any(ActorRef.class)); verify(mockSupport).handleSnapshotMessage(same(captureSnapshot), any(ActorRef.class)); verify(mockSupport).handleSnapshotMessage(same(captureSnapshotReply), any(ActorRef.class)); verify(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess), any(ActorRef.class)); verify(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure), any(ActorRef.class)); verify(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT), any(ActorRef.class)); verify(mockSupport).handleSnapshotMessage(same(GetSnapshot.INSTANCE), any(ActorRef.class)); }
From source file:org.apache.hadoop.metrics2.sink.RollingFileSystemSink.java
/** * Extract the roll interval from the configuration and return it in * milliseconds.//from ww w. j a va 2 s . c om * * @return the roll interval in millis */ @VisibleForTesting protected long getRollInterval() { String rollInterval = properties.getString(ROLL_INTERVAL_KEY, DEFAULT_ROLL_INTERVAL); Pattern pattern = Pattern.compile("^\\s*(\\d+)\\s*([A-Za-z]*)\\s*$"); Matcher match = pattern.matcher(rollInterval); long millis; if (match.matches()) { String flushUnit = match.group(2); int rollIntervalInt; try { rollIntervalInt = Integer.parseInt(match.group(1)); } catch (NumberFormatException ex) { throw new MetricsException("Unrecognized flush interval: " + rollInterval + ". Must be a number followed by an optional " + "unit. The unit must be one of: minute, hour, day", ex); } if ("".equals(flushUnit)) { millis = TimeUnit.HOURS.toMillis(rollIntervalInt); } else { switch (flushUnit.toLowerCase()) { case "m": case "min": case "minute": case "minutes": millis = TimeUnit.MINUTES.toMillis(rollIntervalInt); break; case "h": case "hr": case "hour": case "hours": millis = TimeUnit.HOURS.toMillis(rollIntervalInt); break; case "d": case "day": case "days": millis = TimeUnit.DAYS.toMillis(rollIntervalInt); break; default: throw new MetricsException("Unrecognized unit for flush interval: " + flushUnit + ". Must be one of: minute, hour, day"); } } } else { throw new MetricsException("Unrecognized flush interval: " + rollInterval + ". Must be a number followed by an optional unit." + " The unit must be one of: minute, hour, day"); } if (millis < 60000) { throw new MetricsException( "The flush interval property must be " + "at least 1 minute. Value was " + rollInterval); } return millis; }
From source file:com.moviejukebox.model.Library.java
/** * Calculate the Movie and TV New category properties *//*from ww w . jav a2s .c o m*/ private static void getNewCategoryProperties() { newMovieDays = PropertiesUtil.getReplacedLongProperty("mjb.newdays.movie", "mjb.newdays", 7); newMovieCount = PropertiesUtil.getReplacedIntProperty("mjb.newcount.movie", "mjb.newcount", 0); newTvDays = PropertiesUtil.getReplacedLongProperty("mjb.newdays.tv", "mjb.newdays", 7); newTvCount = PropertiesUtil.getReplacedIntProperty("mjb.newcount.tv", "mjb.newcount", 0); if (newMovieDays > 0) { LOG.debug("New Movie category will have {} most recent movies in the last {} days", newMovieCount > 0 ? ("the " + newMovieCount) : "all of the", newMovieDays); // Convert newDays from DAYS to MILLISECONDS for comparison purposes newMovieDays = TimeUnit.DAYS.toMillis(newMovieDays); } else { LOG.debug("New Movie category is disabled"); } if (newTvDays > 0) { LOG.debug("New TV category will have {} most recent TV Shows in the last {} days", newTvCount > 0 ? ("the " + newTvCount) : "all of the", newTvDays); // Convert newDays from DAYS to MILLISECONDS for comparison purposes newTvDays = TimeUnit.DAYS.toMillis(newTvDays); } else { LOG.debug("New category is disabled"); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.scheduler.quota.QuotaService.java
public void recover() { long _miliSec = System.currentTimeMillis(); final long _day = TimeUnit.DAYS.convert(_miliSec, TimeUnit.MILLISECONDS); try {/* w ww .ja v a 2s . c om*/ LightWeightRequestHandler recoveryHandler = new LightWeightRequestHandler(YARNOperationType.TEST) { @Override public Object performTask() throws IOException { connector.beginTransaction(); connector.writeLock(); YarnProjectsDailyCostDataAccess _pdcDA = (YarnProjectsDailyCostDataAccess) RMStorageFactory .getDataAccess(YarnProjectsDailyCostDataAccess.class); projectsDailyCostCache = _pdcDA.getByDay(_day); ContainersCheckPointsDataAccess ccpDA = (ContainersCheckPointsDataAccess) RMStorageFactory .getDataAccess(ContainersCheckPointsDataAccess.class); containersCheckPoints = ccpDA.getAll(); connector.commit(); return null; } }; recoveryHandler.handle(); //getAll LightWeightRequestHandler logsHandler = new LightWeightRequestHandler(YARNOperationType.TEST) { @Override public Object performTask() throws IOException { connector.beginTransaction(); connector.readLock(); //Get Data ** ContainersLogs ** ContainersLogsDataAccess _csDA = (ContainersLogsDataAccess) RMStorageFactory .getDataAccess(ContainersLogsDataAccess.class); Map<String, ContainersLogs> hopContainersLogs = _csDA.getAll(); connector.commit(); return hopContainersLogs; } }; final Map<String, ContainersLogs> hopContainersLogs = (Map<String, ContainersLogs>) logsHandler .handle(); //run logic on all computeAndApplyCharge(hopContainersLogs.values(), true); } catch (StorageException ex) { LOG.error(ex, ex); } catch (IOException ex) { LOG.error(ex, ex); } }
From source file:org.wso2.carbon.cloud.gateway.transport.CGTransportSender.java
private static long getDurationAsMillisecond(TimeUnit timeUnit, long duration) { if (timeUnit == TimeUnit.MILLISECONDS) { return TimeUnit.MILLISECONDS.toMillis(duration); } else if (timeUnit == TimeUnit.SECONDS) { return TimeUnit.SECONDS.toMillis(duration); } else if (timeUnit == TimeUnit.MINUTES) { return TimeUnit.MINUTES.toMillis(duration); } else if (timeUnit == TimeUnit.HOURS) { return TimeUnit.HOURS.toMillis(duration); } else if (timeUnit == TimeUnit.DAYS) { return TimeUnit.DAYS.toMillis(duration); } else {// w ww . j a va 2 s. co m log.warn("TimeUnit type '" + timeUnit + "' is not supported. Default TimeUnit will be " + "assumed"); return TimeUnit.DAYS.toMillis(duration); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.quota.QuotaService.java
public void recover() throws IOException { final long day = TimeUnit.DAYS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS); cashDay = day;//from ww w . j a v a2 s. com LightWeightRequestHandler recoveryHandler = new LightWeightRequestHandler(YARNOperationType.TEST) { @Override public Object performTask() throws IOException { connector.beginTransaction(); connector.writeLock(); ProjectsDailyCostDataAccess pdcDA = (ProjectsDailyCostDataAccess) RMStorageFactory .getDataAccess(ProjectsDailyCostDataAccess.class); projectsDailyCostCache = pdcDA.getByDay(day); ContainersCheckPointsDataAccess ccpDA = (ContainersCheckPointsDataAccess) RMStorageFactory .getDataAccess(ContainersCheckPointsDataAccess.class); containersCheckPoints = ccpDA.getAll(); //Get Data ** ContainersLogs ** ContainersLogsDataAccess csDA = (ContainersLogsDataAccess) RMStorageFactory .getDataAccess(ContainersLogsDataAccess.class); Map<String, ContainerLog> hopContainersLogs = csDA.getAll(); connector.commit(); return hopContainersLogs; } }; final Map<String, ContainerLog> hopContainersLogs = (Map<String, ContainerLog>) recoveryHandler.handle(); //run logic on all computeAndApplyCharge(hopContainersLogs.values(), true); }
From source file:org.dllearner.algorithms.qtl.QTL.java
public void init() {// TODO: further improve code quality // private QTL() { if (endpointKS == null) { qef = new QueryExecutionFactoryModel(this.model); cbdGenerator = new CachingConciseBoundedDescriptionGenerator( new ConciseBoundedDescriptionGeneratorImpl(model)); nbr = new NBR<String>(model); } else {//from w ww . jav a2 s . co m if (endpointKS.isRemote()) { SparqlEndpoint endpoint = endpointKS.getEndpoint(); QueryExecutionFactory qef = new QueryExecutionFactoryHttp(endpoint.getURL().toString(), endpoint.getDefaultGraphURIs()); if (cacheDirectory != null) { try { long timeToLive = TimeUnit.DAYS.toMillis(30); CacheCoreEx cacheBackend = CacheCoreH2.create(cacheDirectory, timeToLive, true); CacheEx cacheFrontend = new CacheExImpl(cacheBackend); qef = new QueryExecutionFactoryCacheEx(qef, cacheFrontend); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } // qef = new QueryExecutionFactoryPaginated(qef, 10000); } else { qef = new QueryExecutionFactoryModel(((LocalModelBasedSparqlEndpointKS) endpointKS).getModel()); } } if (learningProblem instanceof PosOnlyLP) { this.posExamples = convert(((PosOnlyLP) learningProblem).getPositiveExamples()); this.negExamples = new ArrayList<String>(); } else if (learningProblem instanceof PosNegLP) { this.posExamples = convert(((PosNegLP) learningProblem).getPositiveExamples()); this.negExamples = convert(((PosNegLP) learningProblem).getNegativeExamples()); } treeCache = new QueryTreeCache(); treeCache.addAllowedNamespaces(allowedNamespaces); if (endpointKS == null) { } else { nbr = new NBR<String>(endpoint); nbr.setMaxExecutionTimeInSeconds(maxExecutionTimeInSeconds); if (endpointKS instanceof LocalModelBasedSparqlEndpointKS) { cbdGenerator = new CachingConciseBoundedDescriptionGenerator( new ConciseBoundedDescriptionGeneratorImpl( ((LocalModelBasedSparqlEndpointKS) endpointKS).getModel())); } else { endpoint = endpointKS.getEndpoint(); cbdGenerator = new CachingConciseBoundedDescriptionGenerator( new ConciseBoundedDescriptionGeneratorImpl(endpoint, endpointKS.getCache())); } } cbdGenerator.setRecursionDepth(maxQueryTreeDepth); lggGenerator = new LGGGeneratorImpl<String>(); posExampleTrees = new ArrayList<QueryTree<String>>(); negExampleTrees = new ArrayList<QueryTree<String>>(); }
From source file:com.persinity.ndt.datamutator.DataMutator.java
private String formatRunningTime() { final long elapsedMs = runningTime.elapsed(TimeUnit.MILLISECONDS); final String res; if (runningTime.elapsed(TimeUnit.DAYS) > 0) { res = DurationFormatUtils.formatDuration(elapsedMs, "dd:HH:mm:ss"); } else if (runningTime.elapsed(TimeUnit.HOURS) > 0) { res = DurationFormatUtils.formatDuration(elapsedMs, "HH:mm:ss"); } else {/*from ww w . jav a 2s .c o m*/ res = DurationFormatUtils.formatDuration(elapsedMs, "mm:ss"); } return res; }