Example usage for java.lang Long compare

List of usage examples for java.lang Long compare

Introduction

In this page you can find the example usage for java.lang Long compare.

Prototype

public static int compare(long x, long y) 

Source Link

Document

Compares two long values numerically.

Usage

From source file:io.horizondb.model.core.records.TimeSeriesRecord.java

/**
 * {@inheritDoc}/*from   ww  w .j  a  va2 s .  com*/
 */
@Override
public int compareTo(TimeSeriesRecord o) {
    return Long.compare(this.getTimestampInNanos(0), o.getTimestampInNanos(0));
}

From source file:org.hawkular.alerts.api.model.event.Event.java

@Override
public int compareTo(Event o) {
    /*/*from w  ww  . j a  v  a2s.  c  o  m*/
    Comparition only should be used on events with proper dataId defined.
     */
    if (this.dataId == null) {
        return this.id.compareTo(o.id);
    }
    int c = this.dataId.compareTo(o.dataId);
    if (0 != c)
        return c;
    c = Long.compare(this.ctime, o.ctime);
    if (0 != c) {
        return c;
    }
    return this.id.compareTo(o.id);
}

From source file:org.apache.sentry.tests.e2e.dbprovider.TestConcurrentClients.java

/**
 * Test when concurrent sentry clients talking to sentry server, threads data are synchronized
 * @throws Exception/*w ww  .  ja v  a2  s.c om*/
 */
@Test
public void testConcurrentSentryClient() throws Exception {
    final String HIVE_KEYTAB_PATH = System.getProperty("sentry.e2etest.hive.policyOwnerKeytab");
    final SentryPolicyServiceClient client = getSentryClient("hive", HIVE_KEYTAB_PATH);
    ExecutorService executor = Executors.newFixedThreadPool(NUM_OF_THREADS);

    final TestRuntimeState state = new TestRuntimeState();
    for (int i = 0; i < NUM_OF_TASKS; i++) {
        LOGGER.info("Start to test sentry client with task id [" + i + "]");
        executor.execute(new Runnable() {
            @Override
            public void run() {
                if (state.failed) {
                    LOGGER.error("found one failed state, abort test from here.");
                    return;
                }
                try {
                    String randStr = randomString(5);
                    String test_role = "test_role_" + randStr;
                    LOGGER.info("Start to test role: " + test_role);
                    Long startTime = System.currentTimeMillis();
                    Long elapsedTime = 0L;
                    while (Long.compare(elapsedTime, SENTRY_CLIENT_TEST_DURATION_MS) <= 0) {
                        LOGGER.info("Test role " + test_role + " runs " + elapsedTime + " ms.");
                        client.createRole(ADMIN1, test_role);
                        client.listRoles(ADMIN1);
                        client.grantServerPrivilege(ADMIN1, test_role, "server1", false);
                        client.listAllPrivilegesByRoleName(ADMIN1, test_role);
                        client.dropRole(ADMIN1, test_role);
                        elapsedTime = System.currentTimeMillis() - startTime;
                    }
                    state.setNumSuccess();
                } catch (Exception e) {
                    LOGGER.error("Sentry Client Testing Exception: ", e);
                    state.setFirstException(e);
                }
            }
        });
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
        Thread.sleep(1000); //millisecond
    }
    Throwable ex = state.getFirstException();
    assertFalse(ex == null ? "Test failed" : ex.toString(), state.failed);
    assertEquals(NUM_OF_TASKS, state.getNumSuccess());
}

From source file:org.cgiar.ccafs.marlo.action.summaries.SearchTermsSummaryAction.java

private TypedTableModel getActivitiesTableModel() {

    TypedTableModel model = new TypedTableModel(
            new String[] { "project_id", "title", "act_id", "act_title", "act_desc", "start_date", "end_date",
                    "lead_ins", "leader", "project_url", "phaseID" },
            new Class[] { String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, Long.class },
            0);/*w ww.j av  a  2s.c  o m*/
    if (!keys.isEmpty()) {
        // Pattern case insensitive
        String patternString = "(?i)\\b(" + StringUtils.join(keys, "|") + ")\\b";
        Pattern pattern = Pattern.compile(patternString);
        // date format for star and end dates
        SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM yyyy");
        // Search projects with activities
        List<Project> projects = new ArrayList<>();
        if (this.getSelectedPhase() != null) {
            for (ProjectPhase projectPhase : this.getSelectedPhase().getProjectPhases().stream()
                    .sorted((pf1, pf2) -> Long.compare(pf1.getProject().getId(), pf2.getProject().getId()))
                    .filter(pf -> pf.getProject() != null && pf.getProject().isActive())
                    .collect(Collectors.toList())) {
                projects.add((projectPhase.getProject()));
            }
            for (Project project : projects) {
                ProjectInfo projectInfo = project.getProjecInfoPhase(this.getSelectedPhase());
                // Get active activities
                for (Activity activity : project.getActivities().stream()
                        .sorted((a1, a2) -> Long.compare(a1.getId(), a1.getId())).filter(a -> a.isActive()
                                && a.getPhase() != null && a.getPhase().equals(this.getSelectedPhase()))
                        .collect(Collectors.toList())) {

                    String actTit = activity.getTitle();
                    String actDesc = activity.getDescription();
                    String startDate = null;
                    String endDate = null;
                    String projectTitle = projectInfo.getTitle();
                    String insLeader = "";
                    String leader = "";
                    // Search keys in activity title
                    // count and store occurrences
                    Set<String> matchesTitle = new HashSet<>();
                    Set<String> matchesDescription = new HashSet<>();
                    if (activity.getTitle() != null) {
                        actTit = "<font size=2 face='Segoe UI' color='#000000'>" + activity.getTitle()
                                + "</font>";
                        // Find keys in title
                        Matcher matcher = pattern.matcher(actTit);
                        // while are occurrences
                        while (matcher.find()) {
                            // add elements to matches
                            matchesTitle.add(matcher.group(1));
                        }
                        for (String match : matchesTitle) {
                            actTit = actTit.replaceAll("\\b" + match + "\\b",
                                    "<font size=2 face='Segoe UI' color='#FF0000'><b>$0</b></font>");
                        }
                    } else {
                        actTit = "<font size=2 face='Segoe UI' color='#000000'></font>";
                    }
                    if (activity.getDescription() != null) {
                        actDesc = "<font size=2 face='Segoe UI' color='#000000'>" + activity.getDescription()
                                + "</font>";
                        // Hash set list of matches, avoiding duplicates
                        // Find keys in description
                        Matcher matcher = pattern.matcher(actDesc);
                        // while are occurrences
                        while (matcher.find()) {
                            // add elements to matches
                            matchesDescription.add(matcher.group(1));
                        }
                        for (String match : matchesDescription) {
                            actDesc = actDesc.replaceAll("\\b" + match + "\\b",
                                    "<font size=2 face='Segoe UI' color='#FF0000'><b>$0</b></font>");
                        }
                    } else {
                        actDesc = "<font size=2 face='Segoe UI' color='#000000'></font>";
                    }
                    // If matches is found
                    if ((matchesDescription.size() + matchesTitle.size()) > 0) {
                        // set dates
                        if (activity.getStartDate() != null) {
                            startDate = "<font size=2 face='Segoe UI' color='#000000'>"
                                    + dateFormatter.format(activity.getStartDate()) + "</font>";
                        } else {
                            startDate = "<font size=2 face='Segoe UI' color='#000000'></font>";
                        }
                        if (activity.getEndDate() != null) {
                            endDate = "<font size=2 face='Segoe UI' color='#000000'>"
                                    + dateFormatter.format(activity.getEndDate()) + "</font>";
                        } else {
                            endDate = "<font size=2 face='Segoe UI' color='#000000'></font>";
                        }
                        if (projectInfo.getTitle() != null) {
                            projectTitle = "<font size=2 face='Segoe UI' color='#000000'>"
                                    + projectInfo.getTitle() + "</font>";
                        } else {
                            projectTitle = "<font size=2 face='Segoe UI' color='#000000'></font>";
                        }
                        String projectId = "<font size=2 face='Segoe UI' color='#0000ff'>P"
                                + project.getId().toString() + "</font>";
                        String projectU = project.getId().toString();
                        String actId = "<font size=2 face='Segoe UI' color='#0000ff'>A"
                                + activity.getId().toString() + "</font>";
                        // Set leader
                        if (activity.getProjectPartnerPerson() != null) {
                            leader = "<font size=2 face='Segoe UI' color='#000000'>"
                                    + activity.getProjectPartnerPerson().getUser().getComposedName() + "\n&lt;"
                                    + activity.getProjectPartnerPerson().getUser().getEmail() + "&gt;</font>";
                        }
                        if (leader.isEmpty()) {
                            leader = "<font size=2 face='Segoe UI' color='#000000'></font>";
                        }
                        // Set leader institution
                        if (activity.getProjectPartnerPerson() != null) {
                            if (activity.getProjectPartnerPerson().getProjectPartner() != null) {
                                if (activity.getProjectPartnerPerson().getProjectPartner()
                                        .getInstitution() != null) {
                                    insLeader = "<font size=2 face='Segoe UI' color='#000000'>";
                                    insLeader += activity.getProjectPartnerPerson().getProjectPartner()
                                            .getInstitution().getComposedName();
                                }
                            }
                        }
                        if (insLeader.isEmpty()) {
                            insLeader = "<font size=2 face='Segoe UI' color='#000000'></font>";
                        } else {
                            insLeader += "</font>";
                        }
                        Long phaseID = this.getSelectedPhase().getId();
                        model.addRow(new Object[] { projectId, projectTitle, actId, actTit, actDesc, startDate,
                                endDate, insLeader, leader, projectU, phaseID });
                    }
                }
            }
        }
    }
    return model;
}

From source file:org.apache.drill.exec.store.hive.HiveMetadataProvider.java

/**
 * <p>//from  w  ww. j  av a2  s .  c o m
 * Groups input splits by file path. Each inout split group is ordered by starting bytes
 * to ensure file parts in correct order.
 * </p>
 * <p>
 * Example:
 * <pre>
 * hdfs:///tmp/table/file_1.txt  -> hdfs:///tmp/table/file_1.txt:0+10000
 *                                  hdfs:///tmp/table/file_1.txt:10001+20000
 * hdfs:///tmp/table/file_2.txt  -> hdfs:///tmp/table/file_2.txt:0+10000
 * </pre>
 * </p>
 * @param inputSplits input splits
 * @return multimap where key is file path and value is group of ordered file splits
 */
private Multimap<Path, FileSplit> transformFileSplits(InputSplit[] inputSplits) {
    Multimap<Path, FileSplit> inputSplitGroups = TreeMultimap.create(Ordering.<Path>natural(),
            new Comparator<FileSplit>() {
                @Override
                public int compare(FileSplit f1, FileSplit f2) {
                    return Long.compare(f1.getStart(), f2.getStart());
                }
            });

    for (InputSplit inputSplit : inputSplits) {
        FileSplit fileSplit = (FileSplit) inputSplit;
        inputSplitGroups.put(fileSplit.getPath(), fileSplit);
    }
    return inputSplitGroups;
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ProjectHighlightsSummaryAction.java

private TypedTableModel getProjectHighligthsTableModel() {
    TypedTableModel model = new TypedTableModel(
            new String[] { "id", "title", "author", "subject", "publisher", "year_reported", "highlights_types",
                    "highlights_is_global", "start_date", "end_date", "keywords", "countries", "image",
                    "highlight_desc", "introduction", "results", "partners", "links", "width", "heigth",
                    "project_id", "imageurl", "imageName", "phaseID" },
            new Class[] { Long.class, String.class, String.class, String.class, String.class, Long.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    Integer.class, Integer.class, String.class, String.class, String.class, Long.class },
            0);//from  w  w  w . j av a 2 s  .c om
    SimpleDateFormat formatter = new SimpleDateFormat("MMM yyyy");
    for (ProjectHighlight projectHighlight : projectHighLightManager.findAll().stream()
            .filter(ph -> ph.isActive() && ph.getProject() != null && ph.getProject().isActive()
                    && ph.getProjectHighlightInfo(this.getSelectedPhase()) != null
                    && ph.getProjectHighlightInfo().getYear() != null
                    && ph.getProjectHighlightInfo().getYear() == this.getSelectedYear()
                    && ph.getProject().getProjecInfoPhase(this.getSelectedPhase()) != null)
            .sorted((ph1, ph2) -> Long.compare(ph1.getProject().getId(), ph2.getProject().getId()))
            .collect(Collectors.toList())) {
        String title = null, author = null, subject = null, publisher = null, highlightsTypes = "",
                highlightsIsGlobal = null, startDate = null, endDate = null, keywords = null, countries = "",
                highlightDesc = null, introduction = null, results = null, partners = null, links = null,
                projectId = null, image = "", imageurl = null, imageName = null;
        Long yearReported = null;
        int width = 244;
        int heigth = 163;
        if (projectHighlight.getProjectHighlightInfo().getTitle() != null
                && !projectHighlight.getProjectHighlightInfo().getTitle().isEmpty()) {
            title = projectHighlight.getProjectHighlightInfo().getTitle();
        }
        if (projectHighlight.getProjectHighlightInfo().getAuthor() != null
                && !projectHighlight.getProjectHighlightInfo().getAuthor().isEmpty()) {
            author = projectHighlight.getProjectHighlightInfo().getAuthor();
        }
        if (projectHighlight.getProjectHighlightInfo().getSubject() != null
                && !projectHighlight.getProjectHighlightInfo().getSubject().isEmpty()) {
            subject = projectHighlight.getProjectHighlightInfo().getSubject();
        }
        if (projectHighlight.getProjectHighlightInfo().getPublisher() != null
                && !projectHighlight.getProjectHighlightInfo().getPublisher().isEmpty()) {
            publisher = projectHighlight.getProjectHighlightInfo().getPublisher();
        }
        if (projectHighlight.getProjectHighlightInfo().getYear() != null) {
            yearReported = projectHighlight.getProjectHighlightInfo().getYear();
        }
        for (ProjectHighlightType projectHighlightType : projectHighlight.getProjectHighligthsTypes().stream()
                .filter(pht -> pht.isActive()).collect(Collectors.toList())) {
            if (ProjectHighligthsTypeEnum.getEnum(projectHighlightType.getIdType() + "") != null) {
                if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
                    highlightsTypes += "\n? " + ProjectHighligthsTypeEnum
                            .getEnum(projectHighlightType.getIdType() + "").getDescription();
                } else {
                    highlightsTypes += "<br>? " + ProjectHighligthsTypeEnum
                            .getEnum(projectHighlightType.getIdType() + "").getDescription();
                }
            }
        }
        if (highlightsTypes.isEmpty()) {
            highlightsTypes = null;
        }
        if (projectHighlight.getProjectHighlightInfo().isGlobal() == true) {
            highlightsIsGlobal = "Yes";
        } else {
            highlightsIsGlobal = "No";
        }
        if (projectHighlight.getProjectHighlightInfo().getStartDate() != null) {
            startDate = formatter.format(projectHighlight.getProjectHighlightInfo().getStartDate());
        }
        if (projectHighlight.getProjectHighlightInfo().getEndDate() != null) {
            endDate = formatter.format(projectHighlight.getProjectHighlightInfo().getEndDate());
        }
        if (projectHighlight.getProjectHighlightInfo().getKeywords() != null
                && !projectHighlight.getProjectHighlightInfo().getKeywords().isEmpty()) {
            keywords = projectHighlight.getProjectHighlightInfo().getKeywords();
        }
        int countriesFlag = 0;
        for (ProjectHighlightCountry projectHighlightCountry : projectHighlight.getProjectHighlightCountries()
                .stream().filter(phc -> phc.isActive()).collect(Collectors.toList())) {

            if (projectHighlightCountry.getLocElement() != null) {
                if (countriesFlag == 0) {
                    countries += projectHighlightCountry.getLocElement().getName();
                    countriesFlag++;
                } else {
                    countries += ", " + projectHighlightCountry.getLocElement().getName();
                    countriesFlag++;
                }
            }
        }
        if (countries.isEmpty()) {
            countries = null;
        }
        if (projectHighlight.getProjectHighlightInfo().getDescription() != null
                && !projectHighlight.getProjectHighlightInfo().getDescription().isEmpty()) {
            if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
                highlightDesc = projectHighlight.getProjectHighlightInfo().getDescription();
            } else {
                highlightDesc = HTMLParser
                        .plainTextToHtml(projectHighlight.getProjectHighlightInfo().getDescription());
            }
        }
        if (projectHighlight.getProjectHighlightInfo().getObjectives() != null
                && !projectHighlight.getProjectHighlightInfo().getObjectives().isEmpty()) {
            if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
                introduction = projectHighlight.getProjectHighlightInfo().getObjectives();
            } else {
                introduction = HTMLParser
                        .plainTextToHtml(projectHighlight.getProjectHighlightInfo().getObjectives());
            }
        }
        if (projectHighlight.getProjectHighlightInfo().getResults() != null
                && !projectHighlight.getProjectHighlightInfo().getResults().isEmpty()) {
            if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
                results = projectHighlight.getProjectHighlightInfo().getResults();
            } else {
                results = HTMLParser.plainTextToHtml(projectHighlight.getProjectHighlightInfo().getResults());
            }
        }
        if (projectHighlight.getProjectHighlightInfo().getPartners() != null
                && !projectHighlight.getProjectHighlightInfo().getPartners().isEmpty()) {
            if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
                partners = projectHighlight.getProjectHighlightInfo().getPartners();
            } else {
                partners = HTMLParser.plainTextToHtml(projectHighlight.getProjectHighlightInfo().getPartners());
            }
        }
        if (projectHighlight.getProjectHighlightInfo().getLinks() != null
                && !projectHighlight.getProjectHighlightInfo().getLinks().isEmpty()) {
            if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
                links = projectHighlight.getProjectHighlightInfo().getLinks();
            } else {
                links = HTMLParser.plainTextToHtml(projectHighlight.getProjectHighlightInfo().getLinks());
            }
        }
        if (projectHighlight.getProject() != null) {
            projectId = projectHighlight.getProject().getId().toString();
        }
        if (projectHighlight.getProjectHighlightInfo().getFile() != null) {
            double pageWidth = 612 * 0.4;
            double pageHeigth = 792 * 0.4;
            double imageWidth = 244;
            double imageHeigth = 163;
            image = this.getHightlightImagePath(projectHighlight.getProject().getId())
                    + projectHighlight.getProjectHighlightInfo().getFile().getFileName();
            imageurl = this.getHighlightsImagesUrl(projectHighlight.getProject().getId().toString())
                    + projectHighlight.getProjectHighlightInfo().getFile().getFileName();
            imageName = projectHighlight.getProjectHighlightInfo().getFile().getFileName();
            Image imageFile = null;
            LOG.info("image.getURL.replace " + image);
            File url;
            try {
                url = new File(image);
            } catch (Exception e) {
                LOG.warn("Failed to get image File. Url was set to null. Exception: " + e.getMessage());
                url = null;
                image = "";
                imageurl = null;
                imageName = null;
            }
            if (url != null && url.exists()) {
                try {
                    imageFile = Image.getInstance(FileManager.readURL(url));
                    // System.out.println("W: " + imageFile.getWidth() + " \nH: " + imageFile.getHeight());
                    if (imageFile.getWidth() >= imageFile.getHeight()) {
                        imageWidth = pageWidth;
                        imageHeigth = imageFile.getHeight()
                                * (((pageWidth * 100) / imageFile.getWidth()) / 100);
                    } else {
                        imageHeigth = pageHeigth;
                        imageWidth = imageFile.getWidth()
                                * (((pageHeigth * 100) / imageFile.getHeight()) / 100);
                    }
                    // System.out.println("New W: " + imageWidth + " \nH: " + imageHeigth);
                    width = (int) imageWidth;
                    heigth = (int) imageHeigth;
                    // If successful, process the message
                } catch (BadElementException e) {
                    LOG.warn("BadElementException getting image: " + e.getMessage());
                    image = "";
                    imageurl = null;
                    imageName = null;
                } catch (MalformedURLException e) {
                    LOG.warn("MalformedURLException getting image: " + e.getMessage());
                    image = "";
                    imageurl = null;
                    imageName = null;
                } catch (IOException e) {
                    LOG.warn("IOException getting image: " + e.getMessage());
                    image = "";
                    imageurl = null;
                    imageName = null;
                }
            } else {
                image = "";
                imageurl = null;
                imageName = null;
            }
        }
        Long phaseID = this.getSelectedPhase().getId();
        model.addRow(new Object[] { projectHighlight.getId(), title, author, subject, publisher, yearReported,
                highlightsTypes, highlightsIsGlobal, startDate, endDate, keywords, countries, image,
                highlightDesc, introduction, results, partners, links, width, heigth, projectId, imageurl,
                imageName, phaseID });
    }
    return model;
}

From source file:org.apache.carbondata.core.statusmanager.SegmentUpdateStatusManager.java

private List<String> getFilePaths(CarbonFile blockDir, final String blockNameFromTuple, final String extension,
        List<String> deleteFileList, final long deltaStartTimestamp, final long deltaEndTimeStamp)
        throws IOException {
    if (null != blockDir.getParentFile()) {
        CarbonFile[] files = blockDir.getParentFile().listFiles(new CarbonFileFilter() {

            @Override/*from  www  .ja va2 s .c o  m*/
            public boolean accept(CarbonFile pathName) {
                String fileName = pathName.getName();
                if (fileName.endsWith(extension) && pathName.getSize() > 0) {
                    String firstPart = fileName.substring(0, fileName.lastIndexOf('.'));
                    String blockName = firstPart.substring(0,
                            firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN));
                    long timestamp = Long.parseLong(firstPart.substring(
                            firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN) + 1, firstPart.length()));
                    if (blockNameFromTuple.equals(blockName)
                            && ((Long.compare(timestamp, deltaEndTimeStamp) <= 0)
                                    && (Long.compare(timestamp, deltaStartTimestamp) >= 0))) {
                        return true;
                    }
                }
                return false;
            }
        });

        for (CarbonFile cfile : files) {
            if (null == deleteFileList) {
                deleteFileList = new ArrayList<String>(files.length);
            }
            deleteFileList.add(cfile.getCanonicalPath());
        }
    } else {
        throw new IOException("Parent file could not found");
    }
    return deleteFileList;
}

From source file:org.hawkular.metrics.api.jaxrs.influx.InfluxSeriesHandler.java

private void select(AsyncResponse asyncResponse, String tenantId, SelectQueryContext selectQueryContext,
        InfluxTimeUnit timePrecision) {//from  w ww . jav a2  s . c o  m

    SelectQueryDefinitionsParser definitionsParser = new SelectQueryDefinitionsParser();
    parseTreeWalker.walk(definitionsParser, selectQueryContext);

    SelectQueryDefinitions queryDefinitions = definitionsParser.getSelectQueryDefinitions();

    try {
        queryValidator.validateSelectQuery(queryDefinitions);
    } catch (IllegalQueryException e) {
        asyncResponse.resume(errorResponse(BAD_REQUEST, "Illegal query: " + e.getMessage()));
        return;
    }

    String influxObjectName = queryDefinitions.getFromClause().getName();
    MetricTypeAndName metricTypeAndName = new MetricTypeAndName(influxObjectName);
    MetricType<?> metricType = metricTypeAndName.getType();
    String metricName = metricTypeAndName.getName();

    BooleanExpression whereClause = queryDefinitions.getWhereClause();
    Interval timeInterval;
    if (whereClause == null) {
        timeInterval = new Interval(new Instant(0), Instant.now());
    } else {
        timeInterval = toIntervalTranslator.toInterval(whereClause);
    }
    if (timeInterval == null) {
        asyncResponse.resume(errorResponse(BAD_REQUEST, "Invalid time interval"));
        return;
    }
    String columnName = getColumnName(queryDefinitions);
    Buckets buckets;
    try {
        buckets = getBucketConfig(queryDefinitions, timeInterval);
    } catch (IllegalArgumentException e) {
        asyncResponse.resume(errorResponse(BAD_REQUEST, e.getMessage()));
        return;
    }

    metricsService.idExists(new MetricId<>(tenantId, metricType, metricName)).flatMap(idExists -> {
        if (idExists != Boolean.TRUE) {
            return Observable.just(null);
        }
        long start = timeInterval.getStartMillis();
        long end = timeInterval.getEndMillis();
        MetricId<? extends Number> metricId;
        if (metricType == GAUGE) {
            metricId = new MetricId<>(tenantId, GAUGE, metricName);
            return metricsService.findDataPoints(metricId, start, end, 0, Order.DESC).toList();
        }
        if (metricType == COUNTER) {
            metricId = new MetricId<>(tenantId, COUNTER, metricName);
            return metricsService.findDataPoints(metricId, start, end, 0, Order.DESC)
                    .toSortedList((dataPoint, dataPoint2) -> {
                        return Long.compare(dataPoint2.getTimestamp(), dataPoint.getTimestamp());
                    });
        }
        return Observable.just(null);
    }).map(inputMetrics -> {
        if (inputMetrics == null) {
            return null;
        }

        List<? extends DataPoint<? extends Number>> metrics = inputMetrics;
        if (buckets != null) {
            AggregatedColumnDefinition aggregatedColumnDefinition = (AggregatedColumnDefinition) queryDefinitions
                    .getColumnDefinitions().get(0);
            metrics = applyMapping(aggregatedColumnDefinition.getAggregationFunction(),
                    aggregatedColumnDefinition.getAggregationFunctionArguments(), inputMetrics, buckets);
        }

        if (!queryDefinitions.isOrderDesc()) {
            metrics = Lists.reverse(metrics);
        }

        if (queryDefinitions.getLimitClause() != null) {
            metrics = metrics.subList(0, queryDefinitions.getLimitClause().getLimit());
        }

        List<InfluxObject> objects = new ArrayList<>(1);

        List<String> columns = new ArrayList<>(2);
        columns.add("time");
        columns.add(columnName);

        InfluxObject.Builder builder = new InfluxObject.Builder(influxObjectName, columns)
                .withForeseenPoints(metrics.size());

        for (DataPoint<? extends Number> m : metrics) {
            List<Object> data = new ArrayList<>();
            if (timePrecision == null) {
                data.add(m.getTimestamp());
            } else {
                data.add(timePrecision.convert(m.getTimestamp(), InfluxTimeUnit.MILLISECONDS));
            }
            data.add(m.getValue());
            builder.addPoint(data);
        }

        objects.add(builder.createInfluxObject());

        return objects;
    }).subscribe(objects -> {
        if (objects == null) {
            String msg = "Metric with id [" + influxObjectName + "] not found. ";
            asyncResponse.resume(errorResponse(NOT_FOUND, msg));
        } else {
            ResponseBuilder builder = Response.ok(objects);
            asyncResponse.resume(builder.build());
        }
    }, asyncResponse::resume);
}

From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java

private void autoSearch() {
    new Thread(() -> {
        File[] files = filechooser.getInitialDirectory().listFiles(new FileFilter() {
            @Override//w  w w. ja v  a 2  s. c  o  m
            public boolean accept(File pathname) {
                String x = FilenameUtils.getExtension(pathname.getAbsolutePath());
                return x.compareToIgnoreCase("tsv") == 0;
            }
        });

        File mostRecent = Arrays.stream(files).max((x, y) -> Long.compare(x.lastModified(), y.lastModified()))
                .orElse(null);
        if (mostRecent == null) {
            return;
        }
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setContentText("We found the following TSV file in your default location:\n\""
                    + mostRecent.getName() + "\"\n" + "Modified: " + new Date(mostRecent.lastModified())
                    + "\n\n" + "Would you like load this file?");
            Optional<ButtonType> answer = alert.showAndWait();
            if (answer.isPresent() && answer.get().getButtonData().equals(ButtonData.OK_DONE)) {
                System.out.println(answer.get());
                setInputFile(mostRecent);

                //setting the input file is enough to trigger the load!
                //     loadInInfo(mostRecent);
                //not safe, just load the file in for you.
                //                    onBtnGo(null);
            } else {
            }
        });

    }).start();
}

From source file:io.fabric8.jenkins.openshiftsync.JenkinsUtils.java

public static void handleBuildList(WorkflowJob job, List<Build> builds,
        BuildConfigProjectProperty buildConfigProjectProperty) {
    if (builds.isEmpty()) {
        return;// w ww .  j  a v  a 2s.c om
    }
    boolean isSerialLatestOnly = SERIAL_LATEST_ONLY.equals(buildConfigProjectProperty.getBuildRunPolicy());
    if (isSerialLatestOnly) {
        // Try to cancel any builds that haven't actually started, waiting for executor perhaps.
        cancelNotYetStartedBuilds(job, buildConfigProjectProperty.getUid());
    }
    sort(builds, new Comparator<Build>() {
        @Override
        public int compare(Build b1, Build b2) {
            // Order so cancellations are first in list so we can stop processing build list when build run policy is
            // SerialLatestOnly and job is currently building.
            Boolean b1Cancelled = b1.getStatus() != null && b1.getStatus().getCancelled() != null
                    ? b1.getStatus().getCancelled()
                    : false;
            Boolean b2Cancelled = b2.getStatus() != null && b2.getStatus().getCancelled() != null
                    ? b2.getStatus().getCancelled()
                    : false;
            // Inverse comparison as boolean comparison would put false before true. Could have inverted both cancellation
            // states but this removes that step.
            int cancellationCompare = b2Cancelled.compareTo(b1Cancelled);
            if (cancellationCompare != 0) {
                return cancellationCompare;
            }

            return Long.compare(
                    Long.parseLong(b1.getMetadata().getAnnotations().get(OPENSHIFT_ANNOTATIONS_BUILD_NUMBER)),
                    Long.parseLong(b2.getMetadata().getAnnotations().get(OPENSHIFT_ANNOTATIONS_BUILD_NUMBER)));
        }
    });
    boolean isSerial = SERIAL.equals(buildConfigProjectProperty.getBuildRunPolicy());
    boolean jobIsBuilding = job.isBuilding();
    for (int i = 0; i < builds.size(); i++) {
        Build b = builds.get(i);
        // For SerialLatestOnly we should try to cancel all builds before the latest one requested.
        if (isSerialLatestOnly) {
            // If the job is currently building, then let's return on the first non-cancellation request so we do not try to
            // queue a new build.
            if (jobIsBuilding && !isCancelled(b.getStatus())) {
                return;
            }

            if (i < builds.size() - 1) {
                cancelQueuedBuild(job, b);
                updateOpenShiftBuildPhase(b, CANCELLED);
                continue;
            }
        }
        boolean buildAdded = false;
        try {
            buildAdded = buildAdded(b);
        } catch (IOException e) {
            ObjectMeta meta = b.getMetadata();
            LOGGER.log(WARNING, "Failed to add new build " + meta.getNamespace() + "/" + meta.getName(), e);
        }
        // If it's a serial build then we only need to schedule the first build request.
        if (isSerial && buildAdded) {
            return;
        }
    }
}