Example usage for java.util.concurrent TimeUnit HOURS

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

Introduction

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

Prototype

TimeUnit HOURS

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

Click Source Link

Document

Time unit representing sixty minutes.

Usage

From source file:org.apache.druid.segment.realtime.plumber.RealtimePlumberSchoolTest.java

private void testPersist(final Object commitMetadata) throws Exception {
    Sink sink = new Sink(Intervals.utc(0, TimeUnit.HOURS.toMillis(1)), schema, tuningConfig.getShardSpec(),
            DateTimes.of("2014-12-01T12:34:56.789").toString(), tuningConfig.getMaxRowsInMemory(),
            TuningConfigs.getMaxBytesInMemoryOrDefault(tuningConfig.getMaxBytesInMemory()),
            tuningConfig.isReportParseExceptions(), tuningConfig.getDedupColumn());
    plumber.getSinks().put(0L, sink);/*from   www.  j  a  v a  2s. c o m*/
    Assert.assertNull(plumber.startJob());

    final InputRow row = EasyMock.createNiceMock(InputRow.class);
    EasyMock.expect(row.getTimestampFromEpoch()).andReturn(0L);
    EasyMock.expect(row.getDimensions()).andReturn(new ArrayList<String>());
    EasyMock.replay(row);

    final CountDownLatch doneSignal = new CountDownLatch(1);

    final Committer committer = new Committer() {
        @Override
        public Object getMetadata() {
            return commitMetadata;
        }

        @Override
        public void run() {
            doneSignal.countDown();
        }
    };
    plumber.add(row, Suppliers.ofInstance(committer));
    plumber.persist(committer);

    doneSignal.await();

    plumber.getSinks().clear();
    plumber.finishJob();
}

From source file:com.fluidops.iwb.HTMLProvider.HTMLProvider.java

/**
 * HINT: The gather(List<Statement> res) method collects the statements
 * extracted by the provider. Use the following guidelinges:
 * /*from   www . j av a  2 s.c o m*/
 * 1.) Make sure to have a clear documentation, structure, and
 * modularization. Use helper methods wherever possible to increase
 * readability of the method.
 * 
 * 2.) Whenever there is a need to create statements, use the helper methods
 * in {@link ProviderUtils}. This class helps you in generating "safe" URIs,
 * replacing invalid characters etc. It also offers common functionality for
 * filtering statements, e.g. removing statements containing null values.
 * 
 * 3.) Re-use existing ontologies! The {@link Vocabulary} class provides a
 * mix of vocabulary from common ontologies and can be easily extended. You
 * should not define URIs inside the provider itself, except these URIs are
 * absolutely provider-specific.
 * 
 * 4.) Concerning exception handling, it is best practice to throw
 * exceptions whenever the provider run cannot be finished in a regular way.
 * Since these exception will be propagated to the UI, it is recommended to
 * catch Exceptions locally first, log them, and wrap them into
 * (Runtime)Exceptions with a human-readable description. When logging
 * exceptions, the log level "warn" is appropriate.
 */
@Override
public void gather(List<Statement> res) throws Exception {
    URL registryUrl = new URL(config.location);
    HttpURLConnection registryConnection = (HttpURLConnection) registryUrl.openConnection();
    registryConnection.setRequestMethod("GET");

    // //////////////////////////////////////////////////////////////////////
    // /////////////////////////////////////////////////////////////// STEP
    // 1
    logger.info("Retrieving packages from CKAN...");

    if (registryConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        String msg = "Connection with the registry could not be established. ("
                + registryConnection.getResponseCode() + ", " + registryConnection.getResponseMessage() + ")";
        logger.warn(msg);
        throw new RuntimeException(msg); // propagate to UI
    }

    String siteContent = GenUtil.readUrl(registryConnection.getInputStream());

    JSONObject groupAsJson = null;
    JSONArray packageListJsonArray = null;
    try {
        groupAsJson = new JSONObject(new JSONTokener(siteContent));
        packageListJsonArray = groupAsJson.getJSONArray("packages");
    } catch (JSONException e) {
        String msg = "Returned content " + siteContent
                + " is not valid JSON. Check if the registry URL is valid.";
        logger.warn(msg);
        throw new RuntimeException(msg); // propagate to UI
    }

    logger.info("-> found " + packageListJsonArray.length() + " packages");

    // //////////////////////////////////////////////////////////////////////
    // /////////////////////////////////////////////////////////////// STEP
    // 2
    logger.info("Registering LOD catalog in metadata repository");

    /**
     * HINT: the method createStatement allows to create statements if
     * subject, predicate and object are all known; use this method instead
     * of opening a value factory
     */
    res.add(ProviderUtils.createStatement(CKANVocabulary.CKAN_CATALOG, RDF.TYPE, Vocabulary.DCAT.CATALOG));
    res.add(ProviderUtils.createStatement(CKANVocabulary.CKAN_CATALOG, RDFS.LABEL,
            CKANVocabulary.CKAN_CATALOG_LABEL));

    logger.info("-> done");

    // //////////////////////////////////////////////////////////////////////
    // /////////////////////////////////////////////////////////////// STEP
    // 3
    logger.info("Extracting metdata for the individual data sets listed in CKAN");

    /**
     * HINT: Set up an Apache HTTP client with a manager for multiple
     * threads; as a general guideline, use parallelization whenever
     * crawling web sources!
     */
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient client = new HttpClient(connectionManager);
    ExecutorService pool = Executors.newFixedThreadPool(10);

    // we store the data in a temporary memory store, which allows us
    // to perform transformation on the result set
    Repository repository = null;
    RepositoryConnection connection = null;
    try {
        // initialize repository and connection
        repository = new SailRepository(new MemoryStore());
        repository.initialize();
        connection = repository.getConnection();

        // Fire up a thread for every package
        logger.info("-> Fire up threads for the individual packages...");
        for (int i = 0; i < packageListJsonArray.length(); i++) {
            // we use the JSON representation to get a base URI to resolve
            // relative
            // URIs in the XML later on. (and a fallback solution)
            String host = "http://www.ckan.net/package/" + packageListJsonArray.get(i).toString();
            String baseUri = findBaseUri(
                    "http://www.ckan.net/api/rest/package/" + packageListJsonArray.get(i).toString());
            baseUri = (baseUri == null) ? host : baseUri;
            pool.execute(new MetadataReader(client, host, baseUri, CKANVocabulary.CKAN_CATALOG, connection));
        }

        logger.info("-> Waiting for all tasks to complete (" + packageListJsonArray.length()
                + "tasks/data sources)...");
        pool.shutdown();
        pool.awaitTermination(4, TimeUnit.HOURS);

        /**
         * Now the extraction has finished, all statements are available in
         * our temporary repository. We apply some conversions and
         * transformations to align the extracted statements with our target
         * ontology.
         * 
         * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         * !!!!!!!!!!!!! !!! NOTE: this code is /NOT/ best practice, we
         * should eventually extend !!! !!! ProviderUtils to deal with at
         * least lightweight transformations !!! !!! (such as changing
         * property names) or realize such tasks using !!! !!! an integrated
         * mapping framework. !!!
         * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         */

        // Extraction from temporary repository, phase 1:
        logger.info(
                "-> Extract dcterms:title AS rdfs:label, dcterms:contributor AS dcterms:creator, and dcterms:rights AS dcterms:license");
        String mappingQuery = mappingQuery();
        GraphQuery mappingGraphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL, mappingQuery);
        GraphQueryResult result = mappingGraphQuery.evaluate();

        logger.info("-> Appending extracted result to statement list");
        ProviderUtils.appendGraphQueryResultToListAndClose(result, res);

        // Label the distribution nodes
        logger.info("-> Generate labels for distributions");
        String labelDistributionQuery = labelDistributionQuery();
        GraphQuery labelDistributionGraphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL,
                labelDistributionQuery);
        GraphQueryResult result2 = labelDistributionGraphQuery.evaluate();

        logger.info("-> Appending extracted result to statement list");
        ProviderUtils.appendGraphQueryResultToListAndClose(result2, res);

        // Extraction from temporary repository, phase 2:
        logger.info("-> Deleting previously extracted triples and additional, not required information...");
        String deleteQuery = deleteQuery();
        Update deleteGraphQuery = connection.prepareUpdate(QueryLanguage.SPARQL, deleteQuery);
        deleteGraphQuery.execute();

        // Extraction from temporary repository, phase 3:
        logger.info("-> Deleting dcat:distribution and dcat:accessUrl information from"
                + "temp repository for which format information is missing...");
        String cleanDistQuery = cleanDistQuery();
        Update cleanupGraphQuery = connection.prepareUpdate(QueryLanguage.SPARQL, cleanDistQuery);
        cleanupGraphQuery.execute();

        logger.info("-> Appending remaining statements to result...");
        connection.getStatements(null, null, null, false).addTo(res);

        logger.info("Provider run finished successfully");
    } catch (Exception e) {
        logger.warn(e.getMessage());
        throw new RuntimeException(e);
    } finally {
        if (connection != null)
            connection.close();
        if (repository != null)
            repository.shutDown();
    }

    // in the end, make sure there are no statements containing null in
    // any of the position (did not take special care when creating
    // statements)
    logger.info("-> cleaning up null statements");
    res = ProviderUtils.filterNullStatements(res);
}

From source file:org.xframium.spi.RunDetails.java

public synchronized void writeHTMLIndex(File rootFolder, boolean complete) {
    Collections.sort(detailsList, new RunComparator());

    int runTime = (int) System.currentTimeMillis() - (int) startTime;
    TreeMap<String, int[]> caseMap = new TreeMap<String, int[]>();
    TreeMap<String, int[]> deviceMap = new TreeMap<String, int[]>();
    TreeMap<String, int[]> osMap = new TreeMap<String, int[]>();
    TreeMap<String, int[]> envMap = new TreeMap<String, int[]>();
    int[] stepBreakdown = new int[3];
    int[] failureBreakdown = new int[5];

    int successCount = 0;
    for (int i = 0; i < detailsList.size(); i++) {
        String runKey = (String) detailsList.get(i)[0];
        Device device = (Device) detailsList.get(i)[1];
        int success = (int) detailsList.get(i)[2];

        stepBreakdown[0] += (int) detailsList.get(i)[3];
        stepBreakdown[1] += (int) detailsList.get(i)[4];
        stepBreakdown[2] += (int) detailsList.get(i)[5];
        long startTime = (long) detailsList.get(i)[6];
        long stopTime = (long) detailsList.get(i)[7];

        failureBreakdown[0] += (int) detailsList.get(i)[8];
        failureBreakdown[1] += (int) detailsList.get(i)[9];
        failureBreakdown[2] += (int) detailsList.get(i)[10];
        failureBreakdown[3] += (int) detailsList.get(i)[11];
        failureBreakdown[4] += (int) detailsList.get(i)[12];

        String deviceKey = device.getEnvironment();

        int[] caseValue = caseMap.get(runKey);
        if (caseValue == null) {
            caseValue = new int[] { 0, 0, 0, 0, 0 };
            caseMap.put(runKey, caseValue);
        }//from  w w  w. j a  v  a  2 s  .  c  om

        if (success == 1)
            caseValue[0]++;
        else if (success == 2)
            caseValue[1]++;
        else
            caseValue[4]++;

        caseValue[2]++;
        caseValue[3] += (stopTime - startTime);

        caseValue = envMap.get(device.getEnvironment());
        if (caseValue == null) {
            caseValue = new int[] { 0, 0, 0 };
            envMap.put(device.getEnvironment(), caseValue);
        }

        if (success == 1)
            caseValue[0]++;
        else if (success == 2)
            caseValue[1]++;
        else
            caseValue[2]++;

        caseValue = deviceMap.get(deviceKey);
        if (caseValue == null) {
            caseValue = new int[] { 0, 0, 0 };
            deviceMap.put(deviceKey, caseValue);
        }

        if (success == 1)
            caseValue[0]++;
        else if (success == 2)
            caseValue[1]++;
        else
            caseValue[2]++;

        String osName = device.getOs();
        if (osName == null)
            osName = "Unknown";

        caseValue = osMap.get(osName);
        if (caseValue == null) {
            caseValue = new int[] { 0, 0, 0 };
            osMap.put(osName, caseValue);
        }

        if (success == 1)
            caseValue[0]++;
        else if (success == 2)
            caseValue[1]++;
        else
            caseValue[2]++;

        if ((int) detailsList.get(i)[2] == 1)
            successCount++;
    }

    StringBuilder stringBuilder = new StringBuilder();

    File useFile = getIndex(rootFolder);

    writePageHeader(stringBuilder, 1);

    String runLength = String.format("%dh %dm %ds", TimeUnit.MILLISECONDS.toHours(runTime),
            TimeUnit.MILLISECONDS.toMinutes(runTime)
                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(runTime)),
            TimeUnit.MILLISECONDS.toSeconds(runTime)
                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(runTime)));

    stringBuilder.append(
            "<div class=\"row\"><div class=\"pull-right text-muted\"><a hRef=\"../index.html\" style=\"margin-right: 18px;\">Return to Test Execution History</a></div></div>");
    stringBuilder.append(
            "<div class=\"panel panel-primary\"><div class=panel-heading><div class=panel-title>Execution Detail ("
                    + runLength
                    + ")</div></div><div class=panel-body><table class=\"table table-hover table-condensed\">");
    stringBuilder.append(
            "<tr><th width=\"40%\">Test</th><th width=\"40%\">Environment</th><th width=\"20%\">Duration</th><th>Status</th></tr><tbody>");
    int[] localBreakdown = new int[5];
    for (int i = 0; i < detailsList.size(); i++) {
        String runKey = (String) detailsList.get(i)[0];
        Device device = (Device) detailsList.get(i)[1];
        String location = runKey + "/" + device.getKey() + "/";
        int success = (int) detailsList.get(i)[2];
        long startTime = (long) detailsList.get(i)[6];
        long stopTime = (long) detailsList.get(i)[7];

        localBreakdown[0] = (int) detailsList.get(i)[8];
        localBreakdown[1] = (int) detailsList.get(i)[9];
        localBreakdown[2] = (int) detailsList.get(i)[10];
        localBreakdown[3] = (int) detailsList.get(i)[11];
        localBreakdown[4] = (int) detailsList.get(i)[12];

        long testRunTime = stopTime - startTime;
        String testRunLength = String.format("%2dh %2dm %2ds", TimeUnit.MILLISECONDS.toHours(testRunTime),
                TimeUnit.MILLISECONDS.toMinutes(testRunTime)
                        - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(testRunTime)),
                TimeUnit.MILLISECONDS.toSeconds(testRunTime)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(testRunTime)));

        stringBuilder.append("<tr><td><a href='").append(location + runKey + ".html'>").append(runKey)
                .append("</a></td><td>");
        stringBuilder.append(device.getEnvironment()).append("</td>");
        stringBuilder.append("<td>").append(testRunLength)
                .append("</td><td style=\"padding-top: 10px; \" align=\"center\">");
        if (success == 1)
            stringBuilder.append("<span class=\"label label-success\">Pass</span>");
        else {
            if (localBreakdown[0] > 0)
                stringBuilder.append("<span class=\"label label-danger\">Script</span>");
            else if (localBreakdown[1] > 0)
                stringBuilder.append("<span class=\"label label-danger\">Configuration</span>");
            else if (localBreakdown[2] > 0)
                stringBuilder.append("<span class=\"label label-danger\">Application</span>");
            else if (localBreakdown[3] > 0)
                stringBuilder.append("<span class=\"label label-danger\">Cloud</span>");
            else if (localBreakdown[4] > 0)
                stringBuilder.append("<span class=\"label label-warning\">Skipped</span>");
            else
                stringBuilder.append("<span class=\"label label-danger\">Fail</span>");
        }

        stringBuilder.append("</td></tr>");
    }

    stringBuilder.append("<tr><td colSpan='6' align='center'><h6>")
            .append(new File(rootFolder,
                    getRootFolder() + System.getProperty("file.separator") + "executionMap.properties")
                            .getAbsolutePath())
            .append("</h6></td></tr></tbody></table></div></div>");

    stringBuilder.append(
            "<div class=\"panel panel-primary\"><div class=panel-heading><div class=panel-title>Environment Summary</div></div><div class=panel-body><table class=\"table table-hover table-condensed\">");
    stringBuilder
            .append("<thead><tr><th width=60%>Environment</th><th nowrap>Pass Rate</th></thead></tr><tbody>");

    for (String deviceName : envMap.keySet()) {
        int[] currentRecord = deviceMap.get(deviceName);
        int totalValue = currentRecord[0] + currentRecord[1];
        double successValue = 0;
        if (totalValue > 0)
            successValue = ((double) currentRecord[0] / (double) totalValue) * 100;

        stringBuilder.append("<tr><td width=60%>").append(deviceName).append("</td><td>")
                .append(percentFormat.format(successValue)).append("%</td></tr>");
    }

    stringBuilder.append("</tbody></table></div></div>");

    stringBuilder.append(
            "<div class=\"panel panel-primary\"><div class=panel-heading><div class=panel-title>Test Summary</div></div><div class=panel-body><table class=\"table table-hover table-condensed\">");
    stringBuilder.append(
            "<thead><tr><th width=60%>Test</th><th nowrap>Pass Rate</th><th nowrap>Average Duration</th></thead></tr><tbody>");

    for (String deviceName : caseMap.keySet()) {
        int[] currentRecord = caseMap.get(deviceName);
        int totalValue = currentRecord[0] + currentRecord[1];
        double successValue = 0;
        if (totalValue > 0)
            successValue = ((double) currentRecord[0] / (double) totalValue) * 100;

        int runTimex = (int) ((double) currentRecord[3] / (double) currentRecord[2]);
        String runLengthx = String.format("%2dh %2dm %2ds", TimeUnit.MILLISECONDS.toHours(runTimex),
                TimeUnit.MILLISECONDS.toMinutes(runTimex)
                        - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(runTimex)),
                TimeUnit.MILLISECONDS.toSeconds(runTimex)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(runTimex)));

        stringBuilder.append("<tr><td width=60%>").append(deviceName).append("</td><td>")
                .append(percentFormat.format(successValue)).append("%</td><td>").append(runLengthx)
                .append("</td></tr>");
    }

    stringBuilder.append("</tbody></table></div></div>");

    stringBuilder.append(
            "<div class=\"panel panel-primary\"><div class=panel-heading><div class=panel-title>Failure Breakdown</div></div><div class=panel-body><table class=\"table table-hover table-condensed\">");
    stringBuilder.append(
            "<thead><tr><th width=90%>Failure Type</th><th nowrap>Failure Count</th></tr></thead><tbody>");
    stringBuilder.append(
            "<tbody><tr><td width=90%>Scripting Issues</td><td nowrap>" + failureBreakdown[0] + "</td></tr>");
    stringBuilder.append(
            "<tr><td width=90%>Configuration Issues</td><td nowrap>" + failureBreakdown[1] + "</td></tr>");
    stringBuilder.append(
            "<tr><td width=90%>Application Issues</td><td nowrap>" + failureBreakdown[2] + "</td></tr>");
    stringBuilder.append("<tr><td width=90%>Cloud Issues</td><td nowrap>" + failureBreakdown[3] + "</td></tr>");
    stringBuilder
            .append("<tr><td width=90%>Skipped Tests</td><td nowrap>" + failureBreakdown[4] + "</td></tr>");
    stringBuilder.append("</tbody></table></div></div></div>");
    stringBuilder.append("</div></div></div></div>");

    writePageFooter(stringBuilder);

    try {

        useFile.getParentFile().mkdirs();
        FileWriter fileWriter = new FileWriter(useFile);
        fileWriter.write(stringBuilder.toString());
        fileWriter.close();

        if (complete) {
            if (historyWriter == null)
                historyWriter = new HistoryWriter(DataManager.instance().getReportFolder());
            historyWriter.writeData(getRootFolder() + System.getProperty("file.separator") + "index.html",
                    startTime, System.currentTimeMillis(), envMap.size(), osMap.size(), successCount,
                    detailsList.size() - successCount, envMap, failureBreakdown[0], failureBreakdown[1],
                    failureBreakdown[2], failureBreakdown[3], failureBreakdown[4]);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        HttpClient httpclient = HttpClients.createDefault();

        int CONNECTION_TIMEOUT_MS = 3000; // Timeout in millis.

        Builder requestBuilder = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
                .setConnectTimeout(CONNECTION_TIMEOUT_MS).setSocketTimeout(CONNECTION_TIMEOUT_MS);

        /*if ( CloudRegistry.instance().getCloud().getProxyHost() != null && !CloudRegistry.instance().getCloud().getProxyHost().isEmpty() )
        {
        requestBuilder.setProxy( new HttpHost( CloudRegistry.instance().getCloud().getProxyHost(), Integer.parseInt( CloudRegistry.instance().getCloud().getProxyPort() ) ) );
        }*/

        if (ProxyRegistry.instance().getProxyHost() != null
                && !ProxyRegistry.instance().getProxyHost().isEmpty()) {
            requestBuilder.setProxy(new HttpHost(ProxyRegistry.instance().getProxyHost(),
                    Integer.parseInt(ProxyRegistry.instance().getProxyPort())));
        }

        RequestConfig requestConfig = requestBuilder.build();

        HttpPost httppost = new HttpPost("http://www.google-analytics.com/collect");
        httppost.setConfig(requestConfig);

        List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        params.add(new BasicNameValuePair("v", "1"));
        params.add(new BasicNameValuePair("tid", "UA-80178289-1"));
        params.add(new BasicNameValuePair("cid", "555"));
        params.add(new BasicNameValuePair("t", "pageview"));
        params.add(new BasicNameValuePair("dt", "/testExecution"));
        params.add(new BasicNameValuePair("dp", ApplicationRegistry.instance().getAUT().getName()));
        params.add(new BasicNameValuePair("an", "xFramium"));
        params.add(new BasicNameValuePair("av", Initializable.VERSION));
        params.add(new BasicNameValuePair("dh", CloudRegistry.instance().getCloud().getHostName()));

        params.add(new BasicNameValuePair("cm1", detailsList.size() + ""));
        params.add(new BasicNameValuePair("cm2", successCount + ""));
        params.add(new BasicNameValuePair("cm3", (detailsList.size() - successCount) + ""));
        params.add(
                new BasicNameValuePair("cm4", (stepBreakdown[0] + stepBreakdown[1] + stepBreakdown[2]) + ""));
        params.add(new BasicNameValuePair("cm5", stepBreakdown[0] + ""));
        params.add(new BasicNameValuePair("cm6", stepBreakdown[1] + ""));
        params.add(new BasicNameValuePair("cm7", stepBreakdown[2] + ""));
        params.add(new BasicNameValuePair("cm8", envMap.size() + ""));
        params.add(new BasicNameValuePair("cm9", (runTime / 1000) + ""));

        params.add(new BasicNameValuePair("cd2", System.getProperty("os.name")));
        params.add(new BasicNameValuePair("cd3", System.getProperty("java.version")));
        params.add(new BasicNameValuePair("cd4",
                "X" + Base64.encodeBase64String(CloudRegistry.instance().getCloud().getUserName().getBytes())
                        + "="));

        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        // Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);

    } catch (Exception e) {

    }

}

From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java

protected final String listStatuses(String stream, Map<String, Object> params)
        throws SocialDataFetchError, RateLimitExceededException {
    String url = normalizeURL(stream);

    // TODO fix//from   ww  w.ja v  a  2s. c  o  m
    if (params != null && params.get("q") != null) {
        if (url.indexOf('?') == -1) {
            url = url.concat("?");
        }

        url = url.concat("q=").concat(params.get("q").toString());
    }
    HttpGet get = new HttpGet(url);
    HttpResponse response;
    try {
        response = callHttpMethod(params, get);
    } catch (Exception e1) {
        throw new SocialDataFetchError(e1);
    }

    String body;
    try {
        body = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        throw new SocialDataFetchError(e);
    }

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        log.warn("Twitter provider could not fetch social data: " + response.getStatusLine());

        if (log.isDebugEnabled()) {
            log.debug("Body Request: " + body);

            log.debug("Headers: ");
            for (Header h : response.getAllHeaders()) {
                log.warn(h.getName() + ": " + h.getValue());
            }
        }

        Header[] hRate = response.getHeaders("X-RateLimit-Remaining");
        if (hRate != null && hRate.length > 0 && Long.parseLong(hRate[0].getValue()) == 0) {
            log.warn("Twitter provider found rate limit exceeded");

            long timeNow = System.currentTimeMillis();
            long howLong = timeNow - started;
            long haveToWait = TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS) - howLong;

            Header[] hRateReset = response.getHeaders("X-RateLimit-Reset");

            if (hRateReset != null && hRateReset.length > 0) {
                try {
                    haveToWait = Long.parseLong(hRateReset[0].getValue());
                } catch (Exception e) {
                }
            }
            log.warn("throwing RateLimitExceededException(" + haveToWait + ")");

            throw new RateLimitExceededException(haveToWait);
        }
    }

    get.abort();

    return body;
}

From source file:de.raion.xmppbot.XmppBot.java

/**
 * starting the xmppbot/* ww w .j  ava  2  s  .c o  m*/
 * @param args arguments, arg[0] should link to the named configfile, otherwise
 *         Enbot will lookup for <code>xmppbot.json</code> in the workingdirectory
 * @throws Exception if an not expected Exception occure
 */
public static void main(String[] args) throws Exception {

    XmppBot bot = new XmppBot();

    File configFile = null;

    if (args.length == 0) {
        String fileName = bot.getContext().getString("xmppbot.configuration.filename", "xmppbot.json");
        configFile = new File(fileName);

    } else {
        configFile = new File(args[0]);
    }

    log.info(configFile.getAbsolutePath());

    ObjectMapper mapper = new ObjectMapper();
    BotConfiguration config = mapper.readValue(configFile, BotConfiguration.class);

    log.debug(config.toString());

    bot.init(config);
    TimeUnit.HOURS.sleep(1);

}

From source file:org.dcache.util.histograms.HistogramModelTest.java

@Test
public void serializedTimeframeHistogramShouldDeserializeCorrectly() throws NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    givenTimeframeHistogram();/*from   w  w  w.  ja v  a2s . c om*/
    givenQueueCountValuesFor(48);
    givenBinUnitOf((double) TimeUnit.HOURS.toMillis(1));
    givenBinCountOf(48);
    givenBinLabelOf(TimeUnit.HOURS.name());
    givenDataLabelOf("COUNT");
    givenHistogramTypeOf("Queued Movers");
    givenHighestBinOf(getHoursInThePastFromNow(0));
    whenConfigureIsCalled();
    whenHistogramIsSerialized();
    whenHistogramIsDeserialized();
    whenHistogramIsSerializedAgain();
    assertThatSerializationsAreEqual();
}

From source file:org.codice.ddf.commands.catalog.DuplicateCommands.java

protected long getFilterStartTime(long now) {
    long startTime = 0;
    if (lastHours > 0) {
        startTime = now - TimeUnit.HOURS.toMillis(lastHours);
    } else if (lastDays > 0) {
        startTime = now - TimeUnit.DAYS.toMillis(lastDays);
    } else if (lastWeeks > 0) {
        Calendar weeks = GregorianCalendar.getInstance();
        weeks.setTimeInMillis(now);//from w w  w  .  ja v  a2s .  c  om
        weeks.add(Calendar.WEEK_OF_YEAR, -1 * lastWeeks);
        startTime = weeks.getTimeInMillis();
    } else if (lastMonths > 0) {
        Calendar months = GregorianCalendar.getInstance();
        months.setTimeInMillis(now);
        months.add(Calendar.MONTH, -1 * lastMonths);
        startTime = months.getTimeInMillis();
    }
    return startTime;
}

From source file:org.apache.pulsar.client.impl.RawReaderTest.java

@Test
public void testBatchingRebatch() throws Exception {
    String topic = "persistent://my-property/my-ns/my-raw-topic";

    try (Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).maxPendingMessages(3)
            .enableBatching(true).batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS)
            .messageRoutingMode(MessageRoutingMode.SinglePartition).create()) {
        producer.newMessage().key("key1").value("my-content-1".getBytes()).sendAsync();
        producer.newMessage().key("key2").value("my-content-2".getBytes()).sendAsync();
        producer.newMessage().key("key3").value("my-content-3".getBytes()).send();
    }// w w  w .  j  a va2  s.co  m

    RawReader reader = RawReader.create(pulsarClient, topic, subscription).get();
    try {
        RawMessage m1 = reader.readNextAsync().get();
        RawMessage m2 = RawBatchConverter.rebatchMessage(m1, (key, id) -> key.equals("key2")).get();
        List<ImmutablePair<MessageId, String>> idsAndKeys = RawBatchConverter.extractIdsAndKeys(m2);
        Assert.assertEquals(idsAndKeys.size(), 1);
        Assert.assertEquals(idsAndKeys.get(0).getRight(), "key2");
        m2.close();
    } finally {
        reader.closeAsync().get();
    }
}

From source file:org.apache.usergrid.tools.WarehouseExport.java

private void applyEndTime(CommandLine line) {
    if (line.hasOption(END_TIME)) {
        endTime = new Date(Long.parseLong(line.getOptionValue(END_TIME)));
    } else {/*from w w  w .j ava  2s.  c o  m*/
        endTime = new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(1L, TimeUnit.HOURS));
    }
}

From source file:org.apache.hadoop.hive.llap.daemon.impl.QueryTracker.java

public void rememberCompletedDag(QueryIdentifier queryIdentifier) {
    if (completedDagMap.add(queryIdentifier)) {
        // We will remember completed DAG for an hour to avoid execution out-of-order fragments.
        executorService.schedule(new DagMapCleanerCallable(queryIdentifier), 1, TimeUnit.HOURS);
    } else {// w  w  w  .  ja v  a  2 s .  c  o m
        LOG.warn("Couldn't add {} to completed dag set", queryIdentifier);
    }
}