List of usage examples for java.util.concurrent TimeUnit HOURS
TimeUnit HOURS
To view the source code for java.util.concurrent TimeUnit HOURS.
Click Source Link
From source file:com.linkedin.thirdeye.hadoop.aggregation.AggregationPhaseTest.java
@Before public void setUp() throws Exception { props.setProperty(ThirdEyeConfigProperties.THIRDEYE_TABLE_NAME.toString(), "collection"); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_DIMENSION_NAMES.toString(), "d1,d2,d3"); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_METRIC_NAMES.toString(), "m1,m2"); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_METRIC_TYPES.toString(), "INT,INT"); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_TIMECOLUMN_NAME.toString(), "hoursSinceEpoch"); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_INPUT_TIMECOLUMN_SIZE.toString(), "1"); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_INPUT_TIMECOLUMN_TYPE.toString(), TimeUnit.HOURS.toString()); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_INPUT_TIMECOLUMN_SIZE.toString(), "1"); props.setProperty(ThirdEyeConfigProperties.THIRDEYE_INPUT_TIMECOLUMN_TYPE.toString(), TimeUnit.MILLISECONDS.toString()); thirdeyeConfig = ThirdEyeConfig.fromProperties(props); // Mapper config AggregationMapper mapper = new AggregationMapper(); mapDriver = MapDriver.newMapDriver(mapper); Configuration configuration = mapDriver.getConfiguration(); configuration.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization," + "org.apache.hadoop.io.serializer.WritableSerialization"); configuration.set(AggregationPhaseConstants.AGG_PHASE_THIRDEYE_CONFIG.toString(), OBJECT_MAPPER.writeValueAsString(thirdeyeConfig)); inputSchema = new Schema.Parser().parse(ClassLoader.getSystemResourceAsStream(AVRO_SCHEMA)); setUpAvroSerialization(mapDriver.getConfiguration(), inputSchema); // Reducer config AggregationReducer reducer = new AggregationReducer(); reduceDriver = ReduceDriver.newReduceDriver(reducer); configuration = reduceDriver.getConfiguration(); configuration.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization," + "org.apache.hadoop.io.serializer.WritableSerialization"); Schema avroSchema = new Schema.Parser().parse(ClassLoader.getSystemResourceAsStream(AVRO_SCHEMA)); configuration.set(AggregationPhaseConstants.AGG_PHASE_AVRO_SCHEMA.toString(), avroSchema.toString()); configuration.set(AggregationPhaseConstants.AGG_PHASE_THIRDEYE_CONFIG.toString(), OBJECT_MAPPER.writeValueAsString(thirdeyeConfig)); TemporaryPath tmpPath = new TemporaryPath(); outputPath = tmpPath.toString();/*from ww w .java 2 s . c o m*/ configuration.set(AggregationPhaseConstants.AGG_PHASE_OUTPUT_PATH.toString(), outputPath); setUpAvroSerialization(reduceDriver.getConfiguration(), inputSchema); }
From source file:org.ahp.vinavidai.quiz.action.ProcessCreateQuestion.java
/** * /* w ww . ja v a 2 s. c om*/ * @param pCreateQuestionForm * @param pLoggedInUser */ private void storeQuestion(CreateQuestionForm pCreateQuestionForm, User pLoggedInUser) { Quiz lQuizUnderCreation = pCreateQuestionForm.getQuiz(); Question lQuestion = new Question(); Audit lAudit = AhpBusinessDelegate.createAudit(pLoggedInUser); lQuestion.setAudit(lAudit); lQuestion.setQuiz(lQuizUnderCreation); lQuestion.setQuestionType(QuestionType.valueOf(pCreateQuestionForm.getQuestionType())); lQuestion.setQuestionDescription(pCreateQuestionForm.getQuestionDescription()); lQuestion.setQuestionObjective(pCreateQuestionForm.getQuestionObjective()); if (lQuizUnderCreation.getQuestions() != null) { lQuestion.setQuestionOrder(pCreateQuestionForm.getQuiz().getQuestions().size() + 1); } else { lQuestion.setQuestionOrder(1); } Category lCategory = new Category(); lCategory.setCategoryId(pCreateQuestionForm.getSelectedQuestionCategory()); lQuestion.setCategory(lCategory); SkillLevel lSkillLevel = new SkillLevel(); lSkillLevel.setSkillLevelId(pCreateQuestionForm.getSelectedQuestionSkillLevel()); lQuestion.setSkillLevel(lSkillLevel); lQuestion.setQuestionPoints(pCreateQuestionForm.getQuestionPoints()); long lQuestionDuration = -1; if (StringUtils.isNotBlank(pCreateQuestionForm.getResponseDurationInHours())) { lQuestionDuration += TimeUnit.MILLISECONDS .convert(Long.parseLong(pCreateQuestionForm.getResponseDurationInHours()), TimeUnit.HOURS); } if (StringUtils.isNotBlank(pCreateQuestionForm.getResponseDurationInMinutes())) { lQuestionDuration += TimeUnit.MILLISECONDS .convert(Long.parseLong(pCreateQuestionForm.getResponseDurationInHours()), TimeUnit.MINUTES); } if (StringUtils.isNotBlank(pCreateQuestionForm.getResponseDurationInSeconds())) { lQuestionDuration += TimeUnit.MILLISECONDS .convert(Long.parseLong(pCreateQuestionForm.getResponseDurationInHours()), TimeUnit.SECONDS); } lQuestion.setQuestionDuration(lQuestionDuration); if (lQuestion.getQuestionType().equals(QuestionType.MultipleChoice) || lQuestion.getQuestionType().equals(QuestionType.WordList) || lQuestion.getQuestionType().equals(QuestionType.Matching) || lQuestion.getQuestionType().equals(QuestionType.Ordering)) { for (Option lOption : pCreateQuestionForm.getOptions()) { lOption.setQuestion(lQuestion); lOption.setAudit(lAudit); } } if (lQuestion.getQuestionType().equals(QuestionType.TrueOrFalse) || lQuestion.getQuestionType().equals(QuestionType.Descriptive)) { Option lOption = pCreateQuestionForm.getOptions().get(0); lOption.setQuestion(lQuestion); if (!StringUtils.isEmpty(lOption.getDescriptionQuestionMaximumSizeTypeStr())) { lOption.setDescriptionQuestionMaximumSizeType(DescriptionQuestionMaximumSizeType .valueOf(lOption.getDescriptionQuestionMaximumSizeTypeStr())); } lOption.setAudit(lAudit); List<Option> lOptions = new LinkedList<Option>(); lOptions.add(lOption); pCreateQuestionForm.setOptions(lOptions); } if (lQuestion.getQuestionType().equals(QuestionType.FillInTheBlank)) { String[] lQuestionDescriptionArray = lQuestion.getQuestionDescription().split("\\s+"); List<Option> lFillInTheBlanksOptions = new LinkedList<Option>(); for (String lWordToken : lQuestionDescriptionArray) { if (lWordToken.startsWith("$") && lWordToken.endsWith("$")) { Option lOption = new Option(); lOption.setOptionDescription(lWordToken.substring(1, lWordToken.length() - 1)); lOption.setQuestion(lQuestion); lOption.setAudit(lAudit); lFillInTheBlanksOptions.add(lOption); } } pCreateQuestionForm.setOptions(lFillInTheBlanksOptions); } // Set Options in Question Set<Option> lOptions = new LinkedHashSet<Option>(); for (Option lOption : pCreateQuestionForm.getOptions()) { lOptions.add(lOption); } lQuestion.setOptions(lOptions); if (lQuizUnderCreation.getQuestions() == null) { Set<Question> lQuestions = new LinkedHashSet<Question>(); lQuestions.add(lQuestion); lQuizUnderCreation.setQuestions(lQuestions); } else { lQuizUnderCreation.getQuestions().add(lQuestion); } lQuizUnderCreation = this.mQuizService.updateQuiz(lQuizUnderCreation); pCreateQuestionForm.setQuiz(lQuizUnderCreation); }
From source file:drusy.ui.panels.InternetStatePanel.java
private String formatInterval(final long l) { final long hr = TimeUnit.SECONDS.toHours(l); final long min = TimeUnit.SECONDS.toMinutes(l - TimeUnit.HOURS.toSeconds(hr)); final long sec = TimeUnit.SECONDS .toSeconds(l - TimeUnit.HOURS.toSeconds(hr) - TimeUnit.MINUTES.toSeconds(min)); return String.format("%02d hours %02d mins %02d secs", hr, min, sec); }
From source file:com.erudika.scoold.controllers.SearchController.java
@ResponseBody @GetMapping("/feed.xml") public ResponseEntity<String> feed() { String feed = ""; try {// w ww .j a va 2s . c o m feed = new SyndFeedOutput().outputString(getFeed()); } catch (Exception ex) { logger.error("Could not generate feed", ex); } return ResponseEntity.ok().contentType(MediaType.APPLICATION_ATOM_XML) .cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS)).eTag(Utils.md5(feed)).body(feed); }
From source file:com.pinterest.pinlater.backends.redis.RedisQueueMonitorTest.java
@Test public void testTimeoutJobHashEvicted() throws InterruptedException { // Ensure that queue monitor handles gracefully when the hash of the job is evicted but job id // is still in the in progress queue. Assert.assertTrue(backend.getQueueNames().get().contains(QUEUE_NAME)); // Enqueue 8 jobs, 4 of them with no retries, and 4 with 1 retry. PinLaterEnqueueRequest enqueueRequest = new PinLaterEnqueueRequest(); enqueueRequest.setQueueName(getQueueName()); for (int i = 0; i < 8; i++) { PinLaterJob job = new PinLaterJob(ByteBuffer.wrap(new String("job_body_" + i).getBytes())); job.setNumAttemptsAllowed(i < 4 ? 1 : 2); enqueueRequest.addToJobs(job);//from w w w. j ava 2 s. com } PinLaterEnqueueResponse enqueueResponse = getBackend().enqueueJobs(enqueueRequest).get(); Assert.assertEquals(8, enqueueResponse.getJobDescriptorsSize()); // Dequeue all 8. PinLaterDequeueRequest dequeueRequest = new PinLaterDequeueRequest(getQueueName(), 8); PinLaterDequeueResponse dequeueResponse = getBackend().dequeueJobs("test", dequeueRequest).get(); Assert.assertEquals(8, PinLaterTestUtils.getJobCount(getBackend(), getQueueName(), PinLaterJobState.IN_PROGRESS)); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); // Remove the job hash for the first 2 jobs to simulate they are evicted. Queue monitor should // just silently remove them from in process queue without adding them to any other queues. for (int i = 0; i < 2; i++) { getBackend().removeJobHash(enqueueResponse.getJobDescriptors().get(i)).get(); } // Run queue monitor configured with low job claimed timeout. createQueueMonitor(1, TimeUnit.HOURS.toMillis(1), TimeUnit.HOURS.toMillis(1)).run(); // After GC, 2 jobs should go to FAILED, 2 jobs(hash evicted) should disappear from any queue, // and remaining 4 should go to SUCCEEDED. Assert.assertEquals(2, PinLaterTestUtils.getJobCount(getBackend(), getQueueName(), PinLaterJobState.FAILED)); Assert.assertEquals(4, PinLaterTestUtils.getJobCount(getBackend(), getQueueName(), PinLaterJobState.PENDING)); }
From source file:com.omertron.slackbot.functions.scheduler.AbstractBotTask.java
/** * Convert seconds to Hours, Minutes and Seconds * * @param seconds//from w w w.j a v a2 s. c o m * @return */ protected final String formatSeconds(long seconds) { int day = (int) TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(day); long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.DAYS.toMinutes(day) - TimeUnit.HOURS.toMinutes(hours); long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.DAYS.toSeconds(day) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.MINUTES.toSeconds(minute); return String.format("%1$dh %2$dm %3$ds", hours, minute, second); }
From source file:com.doctor.other.concurrent_hash_map_based_table.ConcurrentHashMapBasedTable.java
public void startExpire() { executorService.scheduleWithFixedDelay(new Runnable() { @Override//from w w w.ja va 2s . c o m public void run() { pruneCache(); } }, 0L, ttl, TimeUnit.HOURS); }
From source file:org.mitre.openid.connect.web.ClientDynamicRegistrationEndpoint.java
/** * Create a new Client, issue a client ID, and create a registration access token. * @param jsonString/*www .j a va 2s . co m*/ * @param m * @param p * @return */ @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public String registerNewClient(@RequestBody String jsonString, Model m) { ClientDetailsEntity newClient = ClientDetailsEntityJsonProcessor.parse(jsonString); if (newClient != null) { // it parsed! // // Now do some post-processing consistency checks on it // // clear out any spurious id/secret (clients don't get to pick) newClient.setClientId(null); newClient.setClientSecret(null); // set of scopes that are OK for clients to dynamically register for Set<SystemScope> dynScopes = scopeService.getDynReg(); // scopes that the client is asking for Set<SystemScope> requestedScopes = scopeService.fromStrings(newClient.getScope()); // the scopes that the client can have must be a subset of the dynamically allowed scopes Set<SystemScope> allowedScopes = Sets.intersection(dynScopes, requestedScopes); // if the client didn't ask for any, give them the defaults if (allowedScopes == null || allowedScopes.isEmpty()) { allowedScopes = scopeService.getDefaults(); } newClient.setScope(scopeService.toStrings(allowedScopes)); // set default grant types if needed if (newClient.getGrantTypes() == null || newClient.getGrantTypes().isEmpty()) { if (newClient.getScope().contains("offline_access")) { // client asked for offline access newClient.setGrantTypes(Sets.newHashSet("authorization_code", "refresh_token")); // allow authorization code and refresh token grant types by default } else { newClient.setGrantTypes(Sets.newHashSet("authorization_code")); // allow authorization code grant type by default } } // set default response types if needed // TODO: these aren't checked by SECOAUTH // TODO: the consistency between the response_type and grant_type needs to be checked by the client service, most likely if (newClient.getResponseTypes() == null || newClient.getResponseTypes().isEmpty()) { newClient.setResponseTypes(Sets.newHashSet("code")); // default to allowing only the auth code flow } if (newClient.getTokenEndpointAuthMethod() == null) { newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); } if (newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_BASIC || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_JWT || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_POST) { // we need to generate a secret newClient = clientService.generateClientSecret(newClient); } // set some defaults for token timeouts newClient.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1)); // access tokens good for 1hr newClient.setIdTokenValiditySeconds((int) TimeUnit.MINUTES.toSeconds(10)); // id tokens good for 10min newClient.setRefreshTokenValiditySeconds(null); // refresh tokens good until revoked // this client has been dynamically registered (obviously) newClient.setDynamicallyRegistered(true); // now save it try { ClientDetailsEntity savedClient = clientService.saveNewClient(newClient); // generate the registration access token OAuth2AccessTokenEntity token = connectTokenService.createRegistrationAccessToken(savedClient); tokenService.saveAccessToken(token); // send it all out to the view RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "register/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8")); m.addAttribute("client", registered); m.addAttribute("code", HttpStatus.CREATED); // http 201 return "clientInformationResponseView"; } catch (UnsupportedEncodingException e) { logger.error("Unsupported encoding", e); m.addAttribute("code", HttpStatus.INTERNAL_SERVER_ERROR); return "httpCodeView"; } catch (IllegalArgumentException e) { logger.error("Couldn't save client", e); m.addAttribute("code", HttpStatus.BAD_REQUEST); return "httpCodeView"; } } else { // didn't parse, this is a bad request logger.error("registerNewClient failed; submitted JSON is malformed"); m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400 return "httpCodeView"; } }
From source file:com.linkedin.pinot.tools.segment.converter.DictionaryToRawIndexConverter.java
/** * Method to perform the conversion for a set of segments in the {@link #_dataDir} * * @return True if successful, False otherwise * @throws Exception//from w ww . j a v a 2 s .c o m */ public boolean convert() throws Exception { if (_help) { printUsage(); return true; } File dataDir = new File(_dataDir); File outputDir = new File(_outputDir); if (!dataDir.exists()) { LOGGER.error("Data directory '{}' does not exist.", _dataDir); return false; } else if (outputDir.exists()) { if (_overwrite) { LOGGER.info("Overwriting existing output directory '{}'", _outputDir); FileUtils.deleteQuietly(outputDir); outputDir = new File(_outputDir); outputDir.mkdir(); } else { LOGGER.error("Output directory '{}' already exists, use -overwrite to overwrite", outputDir); return false; } } File[] segmentFiles = dataDir.listFiles(); if (segmentFiles == null || segmentFiles.length == 0) { LOGGER.error("Empty data directory '{}'.", _dataDir); return false; } boolean ret = true; final File outDir = outputDir; ExecutorService executorService = Executors.newFixedThreadPool(_numThreads); for (final File segmentDir : segmentFiles) { executorService.execute(new Runnable() { @Override public void run() { try { convertSegment(segmentDir, _columns.split("\\s*,\\s*"), outDir, _compressOutput); } catch (Exception e) { LOGGER.error("Exception caught while converting segment {}", segmentDir.getName(), e); e.printStackTrace(); } } }); } executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.HOURS); return ret; }