Example usage for java.util.concurrent TimeUnit MINUTES

List of usage examples for java.util.concurrent TimeUnit MINUTES

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit MINUTES.

Prototype

TimeUnit MINUTES

To view the source code for java.util.concurrent TimeUnit MINUTES.

Click Source Link

Document

Time unit representing sixty seconds.

Usage

From source file:io.pravega.controller.store.stream.AbstractStreamMetadataStore.java

protected AbstractStreamMetadataStore(HostIndex hostIndex) {
    cache = CacheBuilder.newBuilder().maximumSize(10000).refreshAfterWrite(10, TimeUnit.MINUTES)
            .expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<Pair<String, String>, Stream>() {
                @Override/*  w w  w  . j a v a 2s  . co m*/
                @ParametersAreNonnullByDefault
                public Stream load(Pair<String, String> input) {
                    try {
                        return newStream(input.getKey(), input.getValue());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });

    scopeCache = CacheBuilder.newBuilder().maximumSize(1000).refreshAfterWrite(10, TimeUnit.MINUTES)
            .expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<String, Scope>() {
                @Override
                @ParametersAreNonnullByDefault
                public Scope load(String scopeName) {
                    try {
                        return newScope(scopeName);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });

    this.hostIndex = hostIndex;
}

From source file:com.spotify.helios.ZooKeeperClusterTestManager.java

public ZooKeeperClusterTestManager() {
    try {/*  w  w  w .j a v  a  2s .  c o m*/
        tempDir = Files.createTempDirectory("helios-zk");
        while (true) {
            try {
                start0();
                break;
            } catch (BindException ignore) {
                log.warn("zookeeper bind error, retrying");
                Thread.sleep(100);
            }
        }
        curator = createCurator(connectString(zkAddresses.values()));
        awaitUp(5, TimeUnit.MINUTES);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.apache.geode.tools.pulse.PulseDataExportTest.java

@Before
public void before() throws Throwable {
    IgnoredException.addIgnoredException("Failed to properly release resources held by the HTTP service:");
    IgnoredException.addIgnoredException("!STOPPED");

    locator = lsRule.startLocatorVMWithPulse(0, new Properties());

    gfshConnector = new GfshShellConnectionRule(locator);
    gfshConnector.connect();/*ww w  .  j ava  2 s .  c  o  m*/
    assertThat(gfshConnector.isConnected()).isTrue();

    server = lsRule.startServerVM(1, locator.getPort());

    gfshConnector.executeAndVerifyCommand("create region --name=regionA --type=REPLICATE");
    org.apache.geode.cache.Region<String, String> region = new ClientCacheFactory()
            .addPoolLocator("localhost", locator.getPort()).create()
            .<String, String>createClientRegionFactory(ClientRegionShortcut.PROXY).create("regionA");

    region.put("key1", "value1");
    region.put("key2", "value2");
    region.put("key3", "value3");
    cookieStore = new BasicCookieStore();
    httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    await().atMost(2, TimeUnit.MINUTES).until(this::pulseServerHasStarted);
}

From source file:co.mafiagame.telegraminterface.outputhandler.TelegramChannel.java

@PostConstruct
private void init() {
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    client = HttpClients.createDefault();
    this.url = telegramUrl + telegramToken + "/sendMessage";
    TimerTask timerTask = new TimerTask() {
        @Override/*from  w  w w .  j  av a2s. c  om*/
        public void run() {
            SendMessage sendMessage = null;
            try {
                if (!outQueue.isEmpty()) {
                    sendMessage = outQueue.take();
                    deliverMessage(sendMessage);
                }
            } catch (InterruptedException e) {
                logger.error("error in reading outQueue", e);
            } catch (Exception e) {
                logger.error("error sending message " + sendMessage, e);
            }
        }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS.toMillis(200));
}

From source file:com.linkedin.pinot.integration.tests.UploadRefreshDeleteIntegrationTest.java

protected void generateAndUploadRandomSegment(String segmentName, int rowCount) throws Exception {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    Schema schema = new Schema.Parser().parse(
            new File(TestUtils.getFileFromResourceUrl(getClass().getClassLoader().getResource("dummy.avsc"))));
    GenericRecord record = new GenericData.Record(schema);
    GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
    DataFileWriter<GenericRecord> fileWriter = new DataFileWriter<GenericRecord>(datumWriter);
    File avroFile = new File(_tmpDir, segmentName + ".avro");
    fileWriter.create(schema, avroFile);

    for (int i = 0; i < rowCount; i++) {
        record.put(0, random.nextInt());
        fileWriter.append(record);// ww  w.  j  a  va  2s  .  com
    }

    fileWriter.close();

    int segmentIndex = Integer.parseInt(segmentName.split("_")[1]);

    File segmentTarDir = new File(_tarsDir, segmentName);
    ensureDirectoryExistsAndIsEmpty(segmentTarDir);
    ExecutorService executor = MoreExecutors.sameThreadExecutor();
    buildSegmentsFromAvro(Collections.singletonList(avroFile), executor, segmentIndex,
            new File(_segmentsDir, segmentName), segmentTarDir, "mytable", false, null);
    executor.shutdown();
    executor.awaitTermination(1L, TimeUnit.MINUTES);

    for (String segmentFileName : segmentTarDir.list()) {
        File file = new File(segmentTarDir, segmentFileName);
        FileUploadUtils.sendFile("localhost", "8998", "segments", segmentFileName, new FileInputStream(file),
                file.length(), FileUploadUtils.SendFileMethod.POST);
    }

    avroFile.delete();
    FileUtils.deleteQuietly(segmentTarDir);
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToPlainPipelineOutputs() throws InterruptedException, JSONException {
    firstStep = newPipelineWithResponseBody("{id:123}");

    // use a synchronized set to collect the pipeline output from multiple threads
    Set<JsonPipelineOutput> distinctOutputs = Collections.synchronizedSet(new HashSet<JsonPipelineOutput>());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    ExecutorService executorService = Executors.newCachedThreadPool();
    CountDownLatch countDown = new CountDownLatch(100);
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();//w w  w  .  j av  a  2  s . c o  m
            distinctOutputs.add(firstStep.getOutput().toBlocking().single());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    // ensure all threads received the same JsonPipelineOutput instance with the expected JSON output
    assertEquals(1, distinctOutputs.size());
    JSONAssert.assertEquals("{id: 123}", firstStep.getStringOutput().toBlocking().first(),
            JSONCompareMode.STRICT);
}

From source file:com.b2international.index.GroovyMemoryLeakTest.java

@Ignore
@Test//  w  w w.  ja  va  2  s  .  c o  m
public void tryToGenerateMemoryLeak() throws Exception {
    final List<String> orderedItems = newArrayList();
    final Map<String, Data> documents = newHashMap();

    for (int i = 0; i < NUM_DOCS; i++) {
        String item = null;
        while (item == null || orderedItems.contains(item)) {
            item = RandomStringUtils.randomAlphabetic(10);
        }
        orderedItems.add(item);

        final Data data = new Data();
        data.setField1(item);
        data.setFloatField(100.0f - i);
        documents.put(Integer.toString(i), data);
    }

    indexDocuments(documents);

    ExecutorService executor = Executors.newFixedThreadPool(2);

    final Runnable theQuery = () -> {
        for (int i = 0; i < 10_000; i++) {
            final Query<Data> query = Query.select(Data.class)
                    .where(Expressions.scriptScore(Expressions.matchAll(), "floatField")).limit(NUM_DOCS)
                    .sortBy(SortBy.SCORE).build();
            search(query);
        }
    };

    // run 4 threads to simulate a bit higher load on the index
    executor.submit(theQuery, null);
    executor.submit(theQuery, null);
    executor.submit(theQuery, null);
    executor.submit(theQuery, null);

    executor.shutdown();
    // this won't pass at all, even if the fix is applied
    // the purpose of this test to detect and verify the GC via external monitoring thus it cannot be automated properly
    assertTrue(executor.awaitTermination(5, TimeUnit.MINUTES));
}

From source file:com.energysystem.videoexplorerTV.video.VideoProvider.java

public static HashMap<String, List<Video>> buildMedia(String url, Cursor data) throws JSONException {

    mMovieList = new HashMap<String, List<Video>>();
    mMovieList.clear();//  www. ja v a2 s  .  co m
    Log.e("Abrimos", "Videos");
    List<Video> categoryList = new ArrayList<Video>();
    List<Video> categoryList2 = new ArrayList<Video>();

    while (data.moveToNext()) {
        int videoID = data.getInt(data.getColumnIndex(MediaStore.Video.Media._ID));
        int title = data.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE);
        int category = data.getColumnIndexOrThrow(MediaStore.Video.Media.CATEGORY);
        int durationID = data.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
        int data_string = data.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        //int videoUrl = data.getColumnIndexOrThrow(MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString());
        // int bgImageUrl = data.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI.toString());

        int duration = Integer.parseInt(data.getString(durationID));

        String categoria = new File(data.getString(data_string)).getParent();
        Log.e("Ruta:", categoria);
        if (categoria.equals("/storage/emulated/0/Movies")) {
            categoryList.add(buildMovieInfo(categoria, data.getString(title), "Descripcion",
                    String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(duration),
                            TimeUnit.MILLISECONDS.toSeconds(duration)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))),
                    ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoID).toString(),
                    ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoID).toString(),
                    ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoID)
                            .toString()));
            mMovieList.put("Almacenamiento Interno", categoryList);
        } else {
            categoryList2.add(buildMovieInfo(categoria, data.getString(title), "Descripcion",
                    String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(duration),
                            TimeUnit.MILLISECONDS.toSeconds(duration)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))),
                    ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoID).toString(),
                    ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoID).toString(),
                    ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoID)
                            .toString()));
            mMovieList.put("USB", categoryList2);
        }
    }

    /*JSONObject jsonObj = new VideoProvider().parseUrl(url);
    JSONArray categories = jsonObj.getJSONArray(TAG_GOOGLE_VIDEOS);
    if (null != categories) {
    Log.d(TAG, "category #: " + categories.length());
    String title;
    String videoUrl;
    String bgImageUrl;
    String cardImageUrl;
    String studio;
    for (int i = 0; i < categories.length(); i++) {
        JSONObject category = categories.getJSONObject(i);
        String category_name = category.getString(TAG_CATEGORY);
        JSONArray videos = category.getJSONArray(TAG_MEDIA);
        Log.d(TAG,
                "category: " + i + " Name:" + category_name + " video length: "
                        + videos.length());
        List<Video> categoryList = new ArrayList<Video>();
        if (null != videos) {
            for (int j = 0; j < videos.length(); j++) {
                JSONObject video = videos.getJSONObject(j);
                String description = video.getString(TAG_DESCRIPTION);
                JSONArray videoUrls = video.getJSONArray(TAG_SOURCES);
                if (null == videoUrls || videoUrls.length() == 0) {
                    continue;
                }
                title = video.getString(TAG_TITLE);
                videoUrl = getVideoPrefix(category_name, videoUrls.getString(0));
                bgImageUrl = getThumbPrefix(category_name, title,
                        video.getString(TAG_BACKGROUND));
                cardImageUrl = getThumbPrefix(category_name, title,
                        video.getString(TAG_CARD_THUMB));
                studio = video.getString(TAG_STUDIO);
                categoryList.add(buildMovieInfo(category_name, title, description, studio,
                        videoUrl, cardImageUrl,
                        bgImageUrl));
            }
            mMovieList.put(category_name, categoryList);
        }
    }
    }*/
    Log.e("VideoProvider", "Tamano mMovie: " + mMovieList.size());
    return mMovieList;
}

From source file:me.adaptive.services.notification.NotificationSender.java

@Scheduled(fixedDelay = 60000)
//sends notifications every minute
void sendNotifications() {
    LOGGER.info("Sending pending notifications");
    for (NotificationChannel channel : notificationServices.keySet()) {
        executorService.submit(new NotificationChannelTask(channel));

        try {/*w  w w  .  ja va2s .  c  om*/
            executorService.awaitTermination(NOTIFICATION_MAX_EXEC_TIME_MIN, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            LOGGER.warn(
                    "Could not send notifications in {} minutes, this most likely will cause overlapping of notifications",
                    NOTIFICATION_MAX_EXEC_TIME_MIN);
        }
    }
}

From source file:com.stimulus.archiva.index.VolumeIndex.java

public void deleteMessage(EmailID emailID) throws MessageSearchException {
    if (emailID == null)
        throw new MessageSearchException("assertion failure: null emailID", logger);
    logger.debug("delete message {'" + emailID + "'}");
    try {/* w  w w.  j a v a2 s.  c  o  m*/
        boolean isLocked = indexLock.tryLock(10, TimeUnit.MINUTES);
        if (!isLocked) {
            throw new MessageSearchException(
                    "failed to delete email from index. could not acquire lock on index", logger);
        }
        openIndex();
        try {
            writer.deleteDocuments(new Term("uid", emailID.getUniqueID()));
        } catch (Exception e) {
            throw new MessageSearchException("failed to delete email from index.", e, logger);
        }
    } catch (InterruptedException ie) {
        throw new MessageSearchException("failed to delete email from index. interrupted.", logger);
    } finally {
        indexLock.unlock();
    }
}