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:org.hoteia.qalingo.core.service.CartService.java

public Cart updateCartItem(Cart cart, Store store, final String virtualCatalogCode,
        final String catalogCategoryCode, final String productSkuCode, final int quantity) throws Exception {
    Set<CartItem> cartItems = cart.getCartItems();
    boolean productSkuIsNew = true;
    for (CartItem cartItem : cartItems) {
        if (cartItem.getProductSku().getCode().equalsIgnoreCase(productSkuCode)
                && Long.compare(store.getId(), cartItem.getStoreId()) == 0) {
            cartItem.setQuantity(quantity);
            productSkuIsNew = false;//from  w w w  . j av a 2s .c o m
        }
    }
    if (productSkuIsNew) {
        final ProductSku productSku = productService.getProductSkuByCode(productSkuCode);
        if (productSku != null) {
            CartItem cartItem = new CartItem();
            cartItem.setProductSku(productSku);

            final ProductMarketing reloadedProductMarketing = productService.getProductMarketingByCode(
                    productSku.getProductMarketing().getCode(),
                    FetchPlanGraphProduct.productMarketingDefaultFetchPlan());
            cartItem.setProductMarketing(reloadedProductMarketing);

            cartItem.setQuantity(quantity);

            if (store != null) {
                cartItem.setStoreId(store.getId());
            }

            if (StringUtils.isNotEmpty(catalogCategoryCode)) {
                final CatalogCategoryVirtual defaultVirtualCatalogCategory = catalogCategoryService
                        .getVirtualCatalogCategoryByCode(catalogCategoryCode, virtualCatalogCode);
                cartItem.setCatalogCategory(defaultVirtualCatalogCategory);
            } else {
                final List<CatalogCategoryVirtual> catalogCategories = catalogCategoryService
                        .findVirtualCategoriesByProductSkuId(productSku.getId());
                final CatalogCategoryVirtual defaultVirtualCatalogCategory = productService
                        .getDefaultVirtualCatalogCategory(reloadedProductMarketing, catalogCategories, true);
                cartItem.setCatalogCategory(defaultVirtualCatalogCategory);
            }

            // TAXES
            //                List<ProductSkuStorePrice> productSkuStorePrices = productDao.findProductSkuStorePrices(store.getId(), productSku.getId());
            ProductMarketingType productMarketingType = reloadedProductMarketing.getProductMarketingType();
            List<Tax> taxes = taxService.findTaxesByMarketAreaIdAndProductType(cart.getMarketAreaId(),
                    productMarketingType.getCode());
            List<CartItemTax> cartItemTaxes = new ArrayList<CartItemTax>();
            for (Tax tax : taxes) {
                CartItemTax cartItemTax = new CartItemTax();
                cartItemTax.setTax(tax);
                cartItemTaxes.add(cartItemTax);
            }
            cartItem.setTaxes(cartItemTaxes);

            cart.getCartItems().add(cartItem);

        } else {
            // TODO : throw ??
        }
    }
    saveOrUpdateCart(cart);
    return cart;
}

From source file:org.apache.omid.tso.ReplyProcessorImpl.java

@Inject
ReplyProcessorImpl(MetricsRegistry metrics, Panicker panicker, ObjectPool<Batch> batchPool) {

    // ------------------------------------------------------------------------------------------------------------
    // Disruptor initialization
    // ------------------------------------------------------------------------------------------------------------

    ThreadFactoryBuilder threadFactory = new ThreadFactoryBuilder().setNameFormat("reply-%d");
    this.disruptorExec = Executors.newSingleThreadExecutor(threadFactory.build());

    this.disruptor = new Disruptor<>(EVENT_FACTORY, 1 << 12, disruptorExec, MULTI, new BusySpinWaitStrategy());
    disruptor.handleExceptionsWith(new FatalExceptionHandler(panicker));
    disruptor.handleEventsWith(this);
    this.replyRing = disruptor.start();

    // ------------------------------------------------------------------------------------------------------------
    // Attribute initialization
    // ------------------------------------------------------------------------------------------------------------

    this.batchPool = batchPool;
    this.nextIDToHandle.set(0);
    this.futureEvents = new PriorityQueue<>(10, new Comparator<ReplyBatchEvent>() {
        public int compare(ReplyBatchEvent replyBatchEvent1, ReplyBatchEvent replyBatchEvent2) {
            return Long.compare(replyBatchEvent1.getBatchSequence(), replyBatchEvent2.getBatchSequence());
        }// w  w w  . ja  v a  2s .com
    });

    // Metrics config
    this.abortMeter = metrics.meter(name("tso", "aborts"));
    this.commitMeter = metrics.meter(name("tso", "commits"));
    this.timestampMeter = metrics.meter(name("tso", "timestampAllocation"));

    LOG.info("ReplyProcessor initialized");

}

From source file:org.apache.cassandra.tools.nodetool.TopPartitions.java

@Override
public void execute(NodeProbe probe) {
    checkArgument(args.size() == 3, "toppartitions requires keyspace, column family name, and duration");
    checkArgument(topCount < size, "TopK count (-k) option must be smaller then the summary capacity (-s)");
    String keyspace = args.get(0);
    String cfname = args.get(1);//from   w w  w  .  ja  va  2 s  .  c om
    Integer duration = Integer.parseInt(args.get(2));
    // generate the list of samplers
    List<Sampler> targets = Lists.newArrayList();
    for (String s : samplers.split(",")) {
        try {
            targets.add(Sampler.valueOf(s.toUpperCase()));
        } catch (Exception e) {
            throw new IllegalArgumentException(
                    s + " is not a valid sampler, choose one of: " + join(Sampler.values(), ", "));
        }
    }

    Map<Sampler, CompositeData> results;
    try {
        results = probe.getPartitionSample(keyspace, cfname, size, duration, topCount, targets);
    } catch (OpenDataException e) {
        throw new RuntimeException(e);
    }
    boolean first = true;
    for (Entry<Sampler, CompositeData> result : results.entrySet()) {
        CompositeData sampling = result.getValue();
        // weird casting for http://bugs.sun.com/view_bug.do?bug_id=6548436
        List<CompositeData> topk = (List<CompositeData>) (Object) Lists
                .newArrayList(((TabularDataSupport) sampling.get("partitions")).values());
        Collections.sort(topk, new Ordering<CompositeData>() {
            public int compare(CompositeData left, CompositeData right) {
                return Long.compare((long) right.get("count"), (long) left.get("count"));
            }
        });
        if (!first)
            System.out.println();
        System.out.println(result.getKey().toString() + " Sampler:");
        System.out.printf("  Cardinality: ~%d (%d capacity)%n", (long) sampling.get("cardinality"), size);
        System.out.printf("  Top %d partitions:%n", topCount);
        if (topk.size() == 0) {
            System.out.println("\tNothing recorded during sampling period...");
        } else {
            int offset = 0;
            for (CompositeData entry : topk)
                offset = Math.max(offset, entry.get("string").toString().length());
            System.out.printf("\t%-" + offset + "s%10s%10s%n", "Partition", "Count", "+/-");
            for (CompositeData entry : topk)
                System.out.printf("\t%-" + offset + "s%10d%10d%n", entry.get("string").toString(),
                        entry.get("count"), entry.get("error"));
        }
        first = false;
    }
}

From source file:org.apache.ranger.plugin.policyevaluator.RangerAbstractPolicyEvaluator.java

@Override
public int compareTo(RangerPolicyResourceEvaluator obj) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAbstractPolicyEvaluator.compareTo()");
    }//  w  w w.  j  av  a 2  s .  c o m

    int result;

    if (obj instanceof RangerPolicyEvaluator) {
        RangerPolicyEvaluator other = (RangerPolicyEvaluator) obj;

        if (hasDeny() && !other.hasDeny()) {
            result = -1;
        } else if (!hasDeny() && other.hasDeny()) {
            result = 1;
        } else {
            result = Long.compare(other.getUsageCount(), this.usageCount);
            if (result == 0) {
                result = Integer.compare(this.evalOrder, other.getEvalOrder());
            }
        }
    } else {
        result = Long.compare(getId(), obj.getId());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAbstractPolicyEvaluator.compareTo(), result:" + result);
    }

    return result;
}

From source file:net.sourceforge.pmd.benchmark.TextTimingReportRenderer.java

private void renderCategoryMeasurements(final TimedOperationCategory category,
        final Map<String, TimedResult> labeledMeasurements, final Writer writer) throws IOException {
    renderHeader(category.displayName(), writer);

    final TimedResult grandTotal = new TimedResult();
    final TreeSet<Map.Entry<String, TimedResult>> sortedKeySet = new TreeSet<>(
            new Comparator<Map.Entry<String, TimedResult>>() {
                @Override/*from  ww  w.j av a  2s  . c o  m*/
                public int compare(final Entry<String, TimedResult> o1, final Entry<String, TimedResult> o2) {
                    return Long.compare(o1.getValue().selfTimeNanos.get(), o2.getValue().selfTimeNanos.get());
                }
            });
    sortedKeySet.addAll(labeledMeasurements.entrySet());

    for (final Map.Entry<String, TimedResult> entry : sortedKeySet) {
        renderMeasurement(entry.getKey(), entry.getValue(), writer);
        grandTotal.mergeTimes(entry.getValue());
    }

    writer.write(PMD.EOL);
    renderMeasurement("Total " + category.displayName(), grandTotal, writer);
    writer.write(PMD.EOL);
}

From source file:com.vmware.bdd.entity.NodeEntity.java

public static void sortDiskOrder(List<DiskEntity> diskSpecs) {
    //ensure the order by entity Id
    Collections.sort(diskSpecs, new Comparator<DiskEntity>() {
        @Override/* w  w w .j  a v  a 2  s  . c o m*/
        public int compare(DiskEntity o1, DiskEntity o2) {
            return Long.compare(o1.getId(), o2.getId());
        }
    });
}

From source file:com.offbynull.voip.kademlia.model.IdXorMetricComparator.java

@Override
public int compare(Id o1, Id o2) {
    Validate.notNull(o1);/*from w w w .ja va2s.  c o  m*/
    Validate.notNull(o2);
    InternalValidate.matchesLength(baseId.getBitLength(), o1);
    InternalValidate.matchesLength(baseId.getBitLength(), o2);

    int bitLen = baseId.getBitLength();

    int offset = 0;
    while (offset < bitLen) {
        // read as much as possible, up to 63 bits
        // 63 because the 64th bit will be the sign bit, and we don't want to deal negatives
        int readLen = Math.min(bitLen - offset, 63);

        // xor blocks together
        long xorBlock1 = o1.getBitsAsLong(offset, readLen) ^ baseId.getBitsAsLong(offset, readLen);
        long xorBlock2 = o2.getBitsAsLong(offset, readLen) ^ baseId.getBitsAsLong(offset, readLen);

        // move offset by the amount we read
        offset += readLen;

        // if we read hte full 64 bits, we'd have to use compareUnsigned? we don't want to do that because behind the scenes if creates
        // a BigInteger and does the comparison using that.
        //
        // compare 63 bits together, if not equal, we've found a "greater" one
        int res = Long.compare(xorBlock1, xorBlock2);
        if (res != 0) {
            return res;
        }
    }

    // Reaching this point means that o1 and o2 match baseId.
    return 0;
}

From source file:ninja.eivind.hotsreplayuploader.utils.StormHandler.java

/**
 * Retrieves a {@link List} of {@link File}s, each containing files for a specific {@link Account}.
 * @return {@link List} of directories or an empty {@link List}
 *///from www  .j  a  v  a  2  s.c o m
private List<File> getAccountDirectories() {
    final List<File> hotsAccounts = new ArrayList<>();
    File[] files = getHotSHome().listFiles((dir, name) -> name.matches(ACCOUNT_FOLDER_FILTER));
    if (files == null) {
        files = new File[0];
    }
    for (final File file : files) {
        final File[] hotsFolders = file.listFiles((dir, name) -> name.matches(hotsAccountFilter));
        Arrays.stream(hotsFolders).forEach(hotsAccounts::add);
    }

    return hotsAccounts.stream().sorted((f1, f2) -> Long.compare(maxLastModified(f2), maxLastModified(f1)))
            .collect(Collectors.toList());
}

From source file:org.ng200.openolympus.controller.solution.SolutionStatusController.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN + SecurityExpressionConstants.OR + '('
        + SecurityExpressionConstants.IS_USER + SecurityExpressionConstants.AND + '(' + "#solution.user"
        + SecurityExpressionConstants.IS_OWNER + ')' + SecurityExpressionConstants.AND
        + " @oolsec.isSolutionInCurrentContest(#solution) " + ')')
@RequestMapping(method = RequestMethod.GET)
@Cacheable(value = "solutions", key = "#solution.id")
public @ResponseBody SolutionDto solutionApi(@PathVariable(value = "id") final Solution solution,
        final Locale locale) {
    final List<Verdict> verdicts = this.solutionService.getVerdictsVisibleDuringContest(solution);

    final SolutionDto dto = new SolutionDto(
            verdicts.stream().sorted((l, r) -> Long.compare(l.getId(), r.getId()))
                    .map(verdict -> this.verdictJSONController.showVerdict(verdict, locale))
                    .collect(Collectors.toList()));
    if (verdicts.stream().anyMatch(verdict -> !verdict.isTested())) {
        return dto;
    }/*from w w  w.  j av a2 s .c  o m*/
    return dto;
}

From source file:de.qaware.chronix.timeseries.MetricTimeSeries.java

/**
 * Sorts the time series values.// w w w .ja v  a  2 s.c o m
 */
public void sort() {
    if (needsSort && timestamps.size() > 1) {

        LongList sortedTimes = new LongList(timestamps.size());
        DoubleList sortedValues = new DoubleList(values.size());

        points().sorted((o1, o2) -> Long.compare(o1.getTimestamp(), o2.getTimestamp())).forEachOrdered(p -> {
            sortedTimes.add(p.getTimestamp());
            sortedValues.add(p.getValue());
        });

        timestamps = sortedTimes;
        values = sortedValues;

        needsSort = false;
    }
}