Example usage for com.google.common.collect Multiset isEmpty

List of usage examples for com.google.common.collect Multiset isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect Multiset isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

From source file:org.onebusaway.nyc.vehicle_tracking.impl.simulator.SimulatorTask.java

private boolean processResultRecord(NycTestInferredLocationRecord record) {

    final NycTestInferredLocationRecord rr = _vehicleLocationInferenceService
            .getNycTestInferredLocationRecordForVehicle(record.getVehicleId());

    if (rr == null || rr.getTimestamp() < record.getTimestamp())
        return false;

    rr.setVehicleId(_vehicleId);/*from w w  w  .j a  v a 2s. c o m*/

    if (_fillActualProperties) {
        rr.setActualRunId(rr.getInferredRunId());
        rr.setActualBlockId(rr.getInferredBlockId());
        rr.setActualTripId(rr.getInferredTripId());
        rr.setActualBlockLat(rr.getInferredBlockLat());
        rr.setActualBlockLon(rr.getInferredBlockLon());
        rr.setActualDistanceAlongBlock(rr.getInferredDistanceAlongBlock());
        rr.setActualScheduleTime(rr.getInferredScheduleTime());
        rr.setActualDsc(rr.getInferredDsc());
        rr.setActualPhase(rr.getInferredPhase());
        rr.setActualServiceDate(rr.getInferredServiceDate());
        rr.setActualStatus(rr.getInferredStatus());

        rr.clearInferredValues();
    }

    rr.setAssignedRunId(record.getAssignedRunId());
    rr.setActualIsRunFormal(record.getActualIsRunFormal());
    rr.setActualRunId(record.getActualRunId());
    rr.setActualBlockId(record.getActualBlockId());
    rr.setActualTripId(record.getActualTripId());
    rr.setActualBlockLat(record.getActualBlockLat());
    rr.setActualBlockLon(record.getActualBlockLon());
    rr.setActualDistanceAlongBlock(record.getActualDistanceAlongBlock());
    rr.setActualScheduleTime(record.getActualScheduleTime());
    rr.setActualDsc(record.getActualDsc());
    rr.setActualPhase(record.getActualPhase());
    rr.setActualServiceDate(record.getActualServiceDate());
    rr.setActualStatus(record.getActualStatus());

    synchronized (_results) {
        _results.add(rr);
        rr.setRecordNumber(_results.size() - 1);
    }

    final VehicleLocationDetails details = new VehicleLocationDetails();
    details.setId(_id);
    details.setVehicleId(_vehicleId);
    details.setLastObservation(RecordLibrary.getNycTestInferredLocationRecordAsNycRawLocationRecord(record));

    final Multiset<Particle> weightedParticles = TreeMultiset.create(Ordering.natural());
    weightedParticles.addAll(_vehicleLocationInferenceService.getCurrentParticlesForVehicleId(_vehicleId));
    if (!weightedParticles.isEmpty()) {
        details.setParticles(weightedParticles);
        details.setSampledParticles(weightedParticles);
    }

    if (_details.size() < _maxParticleHistorySize)
        _details.add(details);

    return true;
}

From source file:com.addthis.hydra.data.filter.value.ValueFilterGrepTags.java

@Override
@Nullable/*from w  w  w  .j  a v a 2 s.  com*/
public ValueObject filterValue(ValueObject value) {
    if (value == null) {
        return null;
    }

    String html = value.asString().asNative();
    if (html == null) {
        return null;
    }

    @Nonnull
    Multiset<String> valueCounts = HashMultiset.create();
    try {
        Parser parser = Parser.htmlParser().setTrackErrors(0);
        @Nonnull
        Document doc = parser.parseInput(html, "");
        @Nonnull
        Elements tags = doc.select(tagName);

        for (Element tag : tags) {
            for (String tagAttr : tagAttrs) {
                @Nonnull
                String attrValue = tag.attr(tagAttr).toLowerCase();
                for (String matchValue : values) {
                    if (attrValue.contains(matchValue)) {
                        valueCounts.add(matchValue);
                    }
                }
            }
        }
    } catch (Exception e) {
        if (parserErrors++ % logEveryN == 0) {
            log.error("Failed to extract tags due to : {} Total Parser Errors : {}", e.getMessage(),
                    parserErrors);
        }
    }

    return valueCounts.isEmpty() ? null : multisetToValueMap(valueCounts);
}

From source file:org.eclipse.viatra.query.runtime.base.core.NavigationHelperContentAdapter.java

/**
 * This method uses either the original {@link EStructuralFeature} instance or the String id.
 *///from  ww  w  .  ja  va2s .c o  m
private void removeFromReversedFeatureMap(final Object feature, final EObject holder) {
    final Multiset<EObject> setVal = featureToHolderMap.get(feature);
    if (setVal != null) {
        setVal.remove(holder);

        if (setVal.isEmpty()) {
            featureToHolderMap.remove(feature);
        }
    }
}

From source file:com.dssmp.agent.tailing.FirehoseSender.java

@Override
protected BufferSendResult<FirehoseRecord> attemptSend(RecordBuffer<FirehoseRecord> buffer) {
    activeBatchPutCalls.incrementAndGet();
    IMetricsScope metrics = agentContext.beginScope();
    metrics.addDimension(Metrics.DESTINATION_DIMENSION, "DeliveryStream:" + getDestination());
    try {//from  w ww  . j a  v  a 2s.com
        BufferSendResult<FirehoseRecord> sendResult = null;
        List<Record> requestRecords = new ArrayList<>();
        for (FirehoseRecord data : buffer) {
            Record record = new Record();
            record.setData(data.data());
            requestRecords.add(record);
        }
        PutRecordBatchRequest request = new PutRecordBatchRequest();
        request.setRecords(requestRecords);
        request.setDeliveryStreamName(getDestination());
        PutRecordBatchResult result = null;
        Stopwatch timer = Stopwatch.createStarted();
        totalBatchPutCalls.incrementAndGet();
        try {
            logger.trace("{}: Sending buffer {} to firehose {}...", flow.getId(), buffer, getDestination());
            metrics.addCount(RECORDS_ATTEMPTED_METRIC, requestRecords.size());
            result = agentContext.getFirehoseClient().putRecordBatch(request);
            metrics.addCount(SERVICE_ERRORS_METRIC, 0);
        } catch (AmazonServiceException e) {
            metrics.addCount(SERVICE_ERRORS_METRIC, 1);
            totalBatchPutServiceErrors.incrementAndGet();
            throw e;
        } catch (Exception e) {
            metrics.addCount(SERVICE_ERRORS_METRIC, 1);
            totalBatchPutOtherErrors.incrementAndGet();
            throw e;
        } finally {
            totalBatchPutLatency.addAndGet(timer.elapsed(TimeUnit.MILLISECONDS));
        }
        if (sendResult == null) {
            List<Integer> sentRecords = new ArrayList<>(requestRecords.size());
            Multiset<String> errors = HashMultiset.<String>create();
            int index = 0;
            long totalBytesSent = 0;
            for (PutRecordBatchResponseEntry responseEntry : result.getRequestResponses()) {
                Record record = requestRecords.get(index);
                if (responseEntry.getErrorCode() == null) {
                    sentRecords.add(index);
                    totalBytesSent += record.getData().limit();
                } else {
                    logger.trace("{}:{} Record {} returned error code {}: {}", flow.getId(), buffer, index,
                            responseEntry.getErrorCode(), responseEntry.getErrorMessage());
                    errors.add(responseEntry.getErrorCode());
                }
                ++index;
            }
            if (sentRecords.size() == requestRecords.size()) {
                sendResult = BufferSendResult.succeeded(buffer);
            } else {
                buffer = buffer.remove(sentRecords);
                sendResult = BufferSendResult.succeeded_partially(buffer, requestRecords.size());
            }
            metrics.addData(BYTES_SENT_METRIC, totalBytesSent, StandardUnit.Bytes);
            int failedRecordCount = requestRecords.size() - sentRecords.size();
            metrics.addCount(RECORD_ERRORS_METRIC, failedRecordCount);
            logger.debug("{}:{} Records sent firehose {}: {}. Failed records: {}", flow.getId(), buffer,
                    getDestination(), sentRecords.size(), failedRecordCount);
            totalRecordsAttempted.addAndGet(requestRecords.size());
            totalRecordsSent.addAndGet(sentRecords.size());
            totalRecordsFailed.addAndGet(failedRecordCount);

            if (logger.isDebugEnabled() && !errors.isEmpty()) {
                synchronized (totalErrors) {
                    StringBuilder strErrors = new StringBuilder();
                    for (Multiset.Entry<String> err : errors.entrySet()) {
                        AtomicLong counter = totalErrors.get(err.getElement());
                        if (counter == null)
                            totalErrors.put(err.getElement(), counter = new AtomicLong());
                        counter.addAndGet(err.getCount());
                        if (strErrors.length() > 0)
                            strErrors.append(", ");
                        strErrors.append(err.getElement()).append(": ").append(err.getCount());
                    }
                    logger.debug("{}:{} Errors from firehose {}: {}", flow.getId(), buffer,
                            flow.getDestination(), strErrors.toString());
                }
            }
        }
        return sendResult;
    } finally {
        metrics.commit();
        activeBatchPutCalls.decrementAndGet();
    }
}

From source file:com.amazon.kinesis.streaming.agent.tailing.KinesisSender.java

@Override
protected BufferSendResult<KinesisRecord> attemptSend(RecordBuffer<KinesisRecord> buffer) {
    activePutRecordsCalls.incrementAndGet();
    IMetricsScope metrics = agentContext.beginScope();
    metrics.addDimension(Metrics.DESTINATION_DIMENSION, "KinesisStream:" + getDestination());
    try {/*from  w  w w  . jav  a2  s .c om*/
        BufferSendResult<KinesisRecord> sendResult = null;
        List<PutRecordsRequestEntry> requestRecords = new ArrayList<>();
        for (KinesisRecord data : buffer) {
            PutRecordsRequestEntry record = new PutRecordsRequestEntry();
            record.setData(data.data());
            record.setPartitionKey(data.partitionKey());
            requestRecords.add(record);
        }
        PutRecordsRequest request = new PutRecordsRequest();
        request.setStreamName(getDestination());
        request.setRecords(requestRecords);
        PutRecordsResult result = null;
        Stopwatch timer = Stopwatch.createStarted();
        totalPutRecordsCalls.incrementAndGet();
        try {
            logger.trace("{}: Sending buffer {} to kinesis stream {}...", flow.getId(), buffer,
                    getDestination());
            metrics.addCount(RECORDS_ATTEMPTED_METRIC, requestRecords.size());
            result = agentContext.getKinesisClient().putRecords(request);
            metrics.addCount(SERVICE_ERRORS_METRIC, 0);
        } catch (AmazonServiceException e) {
            metrics.addCount(SERVICE_ERRORS_METRIC, 1);
            totalPutRecordsServiceErrors.incrementAndGet();
            throw e;
        } catch (Exception e) {
            metrics.addCount(SERVICE_ERRORS_METRIC, 1);
            totalPutRecordsOtherErrors.incrementAndGet();
            throw e;
        } finally {
            totalPutRecordsLatency.addAndGet(timer.elapsed(TimeUnit.MILLISECONDS));
        }
        if (sendResult == null) {
            List<Integer> sentRecords = new ArrayList<>(requestRecords.size());
            Multiset<String> errors = HashMultiset.<String>create();
            int index = 0;
            long totalBytesSent = 0;
            for (final PutRecordsResultEntry responseEntry : result.getRecords()) {
                final PutRecordsRequestEntry record = requestRecords.get(index);
                if (responseEntry.getErrorCode() == null) {
                    sentRecords.add(index);
                    totalBytesSent += record.getData().limit();
                } else {
                    logger.trace("{}:{} Record {} returned error code {}: {}", flow.getId(), buffer, index,
                            responseEntry.getErrorCode(), responseEntry.getErrorMessage());
                    errors.add(responseEntry.getErrorCode());
                }
                ++index;
            }
            if (sentRecords.size() == requestRecords.size()) {
                sendResult = BufferSendResult.succeeded(buffer);
            } else {
                buffer = buffer.remove(sentRecords);
                sendResult = BufferSendResult.succeeded_partially(buffer, requestRecords.size());
            }
            metrics.addData(BYTES_SENT_METRIC, totalBytesSent, StandardUnit.Bytes);
            int failedRecordCount = requestRecords.size() - sentRecords.size();
            metrics.addCount(RECORD_ERRORS_METRIC, failedRecordCount);
            logger.debug("{}:{} Records sent to kinesis stream {}: {}. Failed records: {}", flow.getId(),
                    buffer, getDestination(), sentRecords.size(), failedRecordCount);
            totalRecordsAttempted.addAndGet(requestRecords.size());
            totalRecordsSent.addAndGet(sentRecords.size());
            totalRecordsFailed.addAndGet(failedRecordCount);

            if (logger.isDebugEnabled() && !errors.isEmpty()) {
                synchronized (totalErrors) {
                    StringBuilder strErrors = new StringBuilder();
                    for (Multiset.Entry<String> err : errors.entrySet()) {
                        AtomicLong counter = totalErrors.get(err.getElement());
                        if (counter == null)
                            totalErrors.put(err.getElement(), counter = new AtomicLong());
                        counter.addAndGet(err.getCount());
                        if (strErrors.length() > 0)
                            strErrors.append(", ");
                        strErrors.append(err.getElement()).append(": ").append(err.getCount());
                    }
                    logger.debug("{}:{} Errors from kinesis stream {}: {}", flow.getId(), buffer,
                            flow.getDestination(), strErrors.toString());
                }
            }
        }
        return sendResult;
    } finally {
        metrics.commit();
        activePutRecordsCalls.decrementAndGet();
    }
}

From source file:com.wasteofplastic.askyblock.LevelCalcByChunk.java

/**
 * Calculates the level of an island//from  w ww .  j a  va2s . c om
 * @param plugin
 * @param targetPlayer - UUID of island owner or team member
 * @param sender - requester of the level calculation, if anyone
 * @param silent - if true, calculation will be done silently
 * @param report - provide a report to the asker
 */
public LevelCalcByChunk(final ASkyBlock plugin, final UUID targetPlayer, final CommandSender sender,
        final boolean report) {
    if (report && plugin.getServer().getVersion().contains("(MC: 1.7")) {
        sender.sendMessage(ChatColor.RED + "This option is not available in V1.7 servers, sorry.");
        return;
    }
    //plugin.getLogger().info("DEBUG: running level calc " + silent);
    // Get player's island
    final Island island = plugin.getGrid().getIsland(targetPlayer,
            ((Player) sender).getWorld().getEnvironment());
    if (island != null) {
        // Get the permission multiplier if it is available
        Player player = plugin.getServer().getPlayer(targetPlayer);
        int multiplier = 1;
        if (player != null) {
            // Get permission multiplier                
            for (PermissionAttachmentInfo perms : player.getEffectivePermissions()) {
                if (perms.getPermission().startsWith(Settings.PERMPREFIX + "island.multiplier.")) {
                    // Get the max value should there be more than one
                    multiplier = Math.max(multiplier, Integer.valueOf(
                            perms.getPermission().split(Settings.PERMPREFIX + "island.multiplier.")[1]));
                }
                // Do some sanity checking
                if (multiplier < 1) {
                    multiplier = 1;
                }
            }
        }
        final int levelMultiplier = multiplier;
        // Get the handicap
        final int levelHandicap = island.getLevelHandicap();
        // Get the death handicap
        int deaths = plugin.getPlayers().getDeaths(targetPlayer);
        if (plugin.getPlayers().inTeam(targetPlayer)) {
            // Get the team leader's deaths
            deaths = plugin.getPlayers().getDeaths(plugin.getPlayers().getTeamLeader(targetPlayer));
            if (Settings.sumTeamDeaths) {
                deaths = 0;
                //plugin.getLogger().info("DEBUG: player is in team");
                for (UUID member : plugin.getPlayers().getMembers(targetPlayer)) {
                    deaths += plugin.getPlayers().getDeaths(member);
                }
            }
        }
        final int deathHandicap = deaths;
        // Check if player's island world is the nether or overworld and adjust accordingly
        final World world = plugin.getPlayers().getIslandLocation(targetPlayer).getWorld();
        // Get the chunks
        //long nano = System.nanoTime();
        Set<ChunkSnapshot> chunkSnapshot = new HashSet<ChunkSnapshot>();
        for (int x = island.getMinProtectedX(); x < (island.getMinProtectedX() + island.getProtectionSize()
                + 16); x += 16) {
            for (int z = island.getMinProtectedZ(); z < (island.getMinProtectedZ() + island.getProtectionSize()
                    + 16); z += 16) {
                if (!world.getBlockAt(x, 0, z).getChunk().isLoaded()) {
                    world.getBlockAt(x, 0, z).getChunk().load();
                    chunkSnapshot.add(world.getBlockAt(x, 0, z).getChunk().getChunkSnapshot());
                    world.getBlockAt(x, 0, z).getChunk().unload();
                } else {
                    chunkSnapshot.add(world.getBlockAt(x, 0, z).getChunk().getChunkSnapshot());
                }
                //plugin.getLogger().info("DEBUG: getting chunk at " + x + ", " + z);
            }
        }
        //plugin.getLogger().info("DEBUG: time = " + (System.nanoTime() - nano) / 1000000 + " ms");
        //plugin.getLogger().info("DEBUG: size of chunk ss = " + chunkSnapshot.size());
        final Set<ChunkSnapshot> finalChunk = chunkSnapshot;
        final int worldHeight = world.getMaxHeight();
        //plugin.getLogger().info("DEBUG:world height = " +worldHeight);
        plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {

            @SuppressWarnings("deprecation")
            @Override
            public void run() {
                // Logging
                File log = null;
                PrintWriter out = null;
                List<MaterialData> mdLog = null;
                List<MaterialData> uwLog = null;
                List<MaterialData> noCountLog = null;
                List<MaterialData> overflowLog = null;
                if (Settings.levelLogging) {
                    log = new File(plugin.getDataFolder(), "level.log");
                    try {
                        if (log.exists()) {
                            out = new PrintWriter(new FileWriter(log, true));
                        } else {
                            out = new PrintWriter(log);
                        }
                    } catch (FileNotFoundException e) {
                        System.out.println("Level log (level.log) could not be opened...");
                        e.printStackTrace();
                    } catch (IOException e) {
                        System.out.println("Level log (level.log) could not be opened...");
                        e.printStackTrace();
                    }
                }
                if (Settings.levelLogging || report) {
                    mdLog = new ArrayList<MaterialData>();
                    uwLog = new ArrayList<MaterialData>();
                    noCountLog = new ArrayList<MaterialData>();
                    overflowLog = new ArrayList<MaterialData>();
                }
                // Copy the limits hashmap
                HashMap<MaterialData, Integer> limitCount = new HashMap<MaterialData, Integer>(
                        Settings.blockLimits);
                // Calculate the island score
                int blockCount = 0;
                int underWaterBlockCount = 0;
                for (ChunkSnapshot chunk : finalChunk) {
                    for (int x = 0; x < 16; x++) {
                        // Check if the block coord is inside the protection zone and if not, don't count it
                        if (chunk.getX() * 16 + x < island.getMinProtectedX() || chunk.getX() * 16
                                + x >= island.getMinProtectedX() + island.getProtectionSize()) {
                            //plugin.getLogger().info("Block is outside protected area - x = " + (chunk.getX() * 16 + x));
                            continue;
                        }
                        for (int z = 0; z < 16; z++) {
                            // Check if the block coord is inside the protection zone and if not, don't count it
                            if (chunk.getZ() * 16 + z < island.getMinProtectedZ() || chunk.getZ() * 16
                                    + z >= island.getMinProtectedZ() + island.getProtectionSize()) {
                                //plugin.getLogger().info("Block is outside protected area - z = " + (chunk.getZ() * 16 + z));
                                continue;
                            }
                            for (int y = 0; y < worldHeight; y++) {
                                int type = chunk.getBlockTypeId(x, y, z);
                                int data = chunk.getBlockData(x, y, z);
                                MaterialData md = new MaterialData(type, (byte) data);
                                MaterialData generic = new MaterialData(type);
                                if (type != 0) { // AIR
                                    if (limitCount.containsKey(md) && Settings.blockValues.containsKey(md)) {
                                        int count = limitCount.get(md);
                                        //plugin.getLogger().info("DEBUG: Count for non-generic " + md + " is " + count);
                                        if (count > 0) {
                                            limitCount.put(md, --count);
                                            if (Settings.sea_level > 0 && y <= Settings.sea_level) {
                                                underWaterBlockCount += Settings.blockValues.get(md);
                                                if (Settings.levelLogging || report) {
                                                    uwLog.add(md);
                                                }
                                            } else {
                                                blockCount += Settings.blockValues.get(md);
                                                if (Settings.levelLogging || report) {
                                                    mdLog.add(md);
                                                }
                                            }
                                        } else if (Settings.levelLogging || report) {
                                            overflowLog.add(md);
                                        }
                                    } else if (limitCount.containsKey(generic)
                                            && Settings.blockValues.containsKey(generic)) {
                                        int count = limitCount.get(generic);
                                        //plugin.getLogger().info("DEBUG: Count for generic " + generic + " is " + count);
                                        if (count > 0) {
                                            limitCount.put(generic, --count);
                                            if (Settings.sea_level > 0 && y <= Settings.sea_level) {
                                                underWaterBlockCount += Settings.blockValues.get(generic);
                                                if (Settings.levelLogging || report) {
                                                    uwLog.add(md);
                                                }
                                            } else {
                                                blockCount += Settings.blockValues.get(generic);
                                                if (Settings.levelLogging || report) {
                                                    mdLog.add(md);
                                                }
                                            }
                                        } else if (Settings.levelLogging || report) {
                                            overflowLog.add(md);
                                        }
                                    } else if (Settings.blockValues.containsKey(md)) {
                                        //plugin.getLogger().info("DEBUG: Adding " + md + " = " + Settings.blockValues.get(md));
                                        if (Settings.sea_level > 0 && y <= Settings.sea_level) {
                                            underWaterBlockCount += Settings.blockValues.get(md);
                                            if (Settings.levelLogging || report) {
                                                uwLog.add(md);
                                            }
                                        } else {
                                            blockCount += Settings.blockValues.get(md);
                                            if (Settings.levelLogging || report) {
                                                mdLog.add(md);
                                            }
                                        }
                                    } else if (Settings.blockValues.containsKey(generic)) {
                                        //plugin.getLogger().info("DEBUG: Adding " + generic + " = " + Settings.blockValues.get(generic));
                                        if (Settings.sea_level > 0 && y <= Settings.sea_level) {
                                            underWaterBlockCount += Settings.blockValues.get(generic);
                                            if (Settings.levelLogging || report) {
                                                uwLog.add(md);
                                            }
                                        } else {
                                            blockCount += Settings.blockValues.get(generic);
                                            if (Settings.levelLogging || report) {
                                                mdLog.add(md);
                                            }
                                        }
                                    } else if (Settings.levelLogging || report) {
                                        noCountLog.add(md);
                                    }
                                }
                            }
                        }
                    }
                }

                blockCount += (int) ((double) underWaterBlockCount * Settings.underWaterMultiplier);
                //System.out.println("block count = "+blockCount);

                final int score = (((blockCount * levelMultiplier) - (deathHandicap * Settings.deathpenalty))
                        / Settings.levelCost) - levelHandicap;
                // Logging or report
                if (Settings.levelLogging || report) {
                    // provide counts
                    Multiset<MaterialData> uwCount = HashMultiset.create(uwLog);
                    Multiset<MaterialData> mdCount = HashMultiset.create(mdLog);
                    Multiset<MaterialData> ncCount = HashMultiset.create(noCountLog);
                    Multiset<MaterialData> ofCount = HashMultiset.create(overflowLog);
                    reportLines.add("Level Log for island at " + island.getCenter());
                    if (sender instanceof Player) {
                        reportLines.add("Asker is " + sender.getName() + " ("
                                + ((Player) sender).getUniqueId().toString() + ")");
                    } else {
                        reportLines.add("Asker is console");
                    }
                    reportLines.add("Target player UUID = " + targetPlayer.toString());
                    reportLines.add("Total block value count = " + String.format("%,d", blockCount));
                    reportLines.add("Level cost = " + Settings.levelCost);
                    reportLines.add("Level multiplier = " + levelMultiplier
                            + " (Player must be online to get a permission multiplier)");
                    reportLines.add("Schematic level handicap = " + levelHandicap
                            + " (level is reduced by this amount)");
                    reportLines.add("Deaths handicap = " + (deathHandicap * Settings.deathpenalty) + " ("
                            + deathHandicap + " deaths)");
                    reportLines.add("Level calculated = " + score);
                    reportLines.add("==================================");
                    int total = 0;
                    if (!uwCount.isEmpty()) {
                        reportLines.add("Underwater block count (Multiplier = x" + Settings.underWaterMultiplier
                                + ") value");
                        reportLines.add(
                                "Total number of underwater blocks = " + String.format("%,d", uwCount.size()));
                        Iterable<Multiset.Entry<MaterialData>> entriesSortedByCount = Multisets
                                .copyHighestCountFirst(uwCount).entrySet();
                        Iterator<Entry<MaterialData>> it = entriesSortedByCount.iterator();
                        while (it.hasNext()) {
                            Entry<MaterialData> type = it.next();
                            int value = 0;
                            if (Settings.blockValues.containsKey(type)) {
                                // Specific
                                value = Settings.blockValues.get(type);
                            } else if (Settings.blockValues
                                    .containsKey(new MaterialData(type.getElement().getItemType()))) {
                                // Generic
                                value = Settings.blockValues
                                        .get(new MaterialData(type.getElement().getItemType()));
                            }
                            if (value > 0) {
                                reportLines.add(type.getElement().toString() + ":"
                                        + String.format("%,d", type.getCount()) + " blocks x " + value + " = "
                                        + (value * type.getCount()));
                                total += (value * type.getCount());
                            }
                        }
                        reportLines.add("Subtotal = " + total);
                        reportLines.add("==================================");
                    }
                    reportLines.add("Regular block count");
                    reportLines.add("Total number of blocks = " + String.format("%,d", mdCount.size()));
                    Iterable<Multiset.Entry<MaterialData>> entriesSortedByCount = Multisets
                            .copyHighestCountFirst(mdCount).entrySet();
                    Iterator<Entry<MaterialData>> it = entriesSortedByCount.iterator();
                    while (it.hasNext()) {
                        Entry<MaterialData> type = it.next();
                        int value = 0;
                        if (Settings.blockValues.containsKey(type)) {
                            // Specific
                            value = Settings.blockValues.get(type);
                        } else if (Settings.blockValues
                                .containsKey(new MaterialData(type.getElement().getItemType()))) {
                            // Generic
                            value = Settings.blockValues.get(new MaterialData(type.getElement().getItemType()));
                        }
                        if (value > 0) {
                            reportLines.add(
                                    type.getElement().toString() + ":" + String.format("%,d", type.getCount())
                                            + " blocks x " + value + " = " + (value * type.getCount()));
                            total += (value * type.getCount());
                        }
                    }
                    reportLines.add("Total = " + total);
                    reportLines.add("==================================");
                    reportLines.add("Blocks not counted because they exceeded limits: "
                            + String.format("%,d", ofCount.size()));
                    entriesSortedByCount = Multisets.copyHighestCountFirst(ofCount).entrySet();
                    it = entriesSortedByCount.iterator();
                    while (it.hasNext()) {
                        Entry<MaterialData> type = it.next();
                        Integer limit = Settings.blockLimits.get(type.getElement());
                        String explain = ")";
                        if (limit == null) {
                            MaterialData generic = new MaterialData(type.getElement().getItemType());
                            limit = Settings.blockLimits.get(generic);
                            explain = " - All types)";
                        }
                        reportLines.add(type.getElement().toString() + ": "
                                + String.format("%,d", type.getCount()) + " blocks (max " + limit + explain);
                    }
                    reportLines.add("==================================");
                    reportLines.add("Blocks on island that are not in blockvalues.yml");
                    reportLines.add("Total number = " + String.format("%,d", ncCount.size()));
                    entriesSortedByCount = Multisets.copyHighestCountFirst(ncCount).entrySet();
                    it = entriesSortedByCount.iterator();
                    while (it.hasNext()) {
                        Entry<MaterialData> type = it.next();
                        reportLines.add(type.getElement().toString() + ": "
                                + String.format("%,d", type.getCount()) + " blocks");
                    }
                    reportLines.add("=================================");
                }
                if (out != null) {
                    // Write to file
                    for (String line : reportLines) {
                        out.println(line);
                    }
                    System.out.println("Finished writing level log.");
                    out.close();
                }

                // Return to main thread
                plugin.getServer().getScheduler().runTask(plugin, new Runnable() {

                    @Override
                    public void run() {
                        //plugin.getLogger().info("DEBUG: updating player");
                        int oldLevel = plugin.getPlayers().getIslandLevel(targetPlayer);
                        // Update player and team mates
                        plugin.getPlayers().setIslandLevel(targetPlayer, score);
                        //plugin.getLogger().info("DEBUG: set island level, now trying to save player");
                        plugin.getPlayers().save(targetPlayer);
                        //plugin.getLogger().info("DEBUG: save player, now looking at team members");
                        // Update any team members too
                        if (plugin.getPlayers().inTeam(targetPlayer)) {
                            //plugin.getLogger().info("DEBUG: player is in team");
                            for (UUID member : plugin.getPlayers().getMembers(targetPlayer)) {
                                //plugin.getLogger().info("DEBUG: updating team member level too");
                                plugin.getPlayers().setIslandLevel(member, score);
                                plugin.getPlayers().save(member);
                            }
                        }
                        //plugin.getLogger().info("DEBUG: finished team member saving");
                        if (sender != null) {
                            if (!(sender instanceof Player)) {
                                // Console  
                                if (!report) {
                                    sender.sendMessage(ChatColor.GREEN + plugin.myLocale().islandislandLevelis
                                            + " " + ChatColor.WHITE
                                            + plugin.getPlayers().getIslandLevel(targetPlayer));
                                } else {
                                    for (String line : reportLines) {
                                        sender.sendMessage(line);
                                    }
                                }
                            } else {
                                if (!report) {
                                    // Tell offline team members the island level increased.
                                    if (plugin.getPlayers().getIslandLevel(targetPlayer) > oldLevel) {
                                        //plugin.getLogger().info("DEBUG: telling offline players");
                                        plugin.getMessages().tellOfflineTeam(targetPlayer,
                                                ChatColor.GREEN
                                                        + plugin.myLocale(targetPlayer).islandislandLevelis
                                                        + " " + ChatColor.WHITE
                                                        + plugin.getPlayers().getIslandLevel(targetPlayer));
                                    }
                                    if (sender instanceof Player && ((Player) sender).isOnline()) {
                                        String message = ChatColor.GREEN
                                                + plugin.myLocale(
                                                        ((Player) sender).getUniqueId()).islandislandLevelis
                                                + " " + ChatColor.WHITE
                                                + plugin.getPlayers().getIslandLevel(targetPlayer);
                                        if (Settings.deathpenalty != 0) {
                                            message += " " + plugin
                                                    .myLocale(((Player) sender).getUniqueId()).levelDeaths
                                                            .replace("[number]", String.valueOf(plugin
                                                                    .getPlayers().getDeaths(targetPlayer)));
                                        }
                                        sender.sendMessage(message);
                                    }
                                } else {
                                    if (((Player) sender).isOnline()) {
                                        for (String line : reportLines) {
                                            sender.sendMessage(line);
                                        }
                                    }
                                }
                            }
                        }
                        //plugin.getLogger().info("DEBUG: updating top ten");
                        // Only update top ten if the asker doesn't have this permission
                        if (!(sender instanceof Player)) {
                            return;
                        }
                        if (!(((Player) sender).getUniqueId().equals(targetPlayer)
                                && sender.hasPermission(Settings.PERMPREFIX + "excludetopten"))) {
                            if (plugin.getPlayers().inTeam(targetPlayer)) {
                                UUID leader = plugin.getPlayers().getTeamLeader(targetPlayer);
                                if (leader != null) {
                                    TopTen.topTenAddEntry(leader, score);
                                }
                            } else {
                                TopTen.topTenAddEntry(targetPlayer, score);
                            }
                        }
                        // Fire the level event
                        Island island = plugin.getGrid().getIsland(targetPlayer,
                                ((Player) sender).getWorld().getEnvironment());
                        final IslandLevelEvent event = new IslandLevelEvent(targetPlayer, island, score);
                        plugin.getServer().getPluginManager().callEvent(event);
                    }
                });
            }
        });
    }
}

From source file:fabric.worker.transaction.DeadlockDetectorThread.java

/**
 * Resolves deadlocks by aborting transactions.
 * /*from   w w  w . j  ava2 s. c om*/
 * @param cycles
 *          the set of deadlocks, represented by the logs of transactions
 *          involved in waits-for cycles.
 */
private void resolveDeadlocks(Set<Set<Log>> cycles) {
    // Turn the set of cycles into a map from top-level TIDs to sorted multisets
    // of transaction logs. The multisets are sorted by transaction depth, outer
    // transactions first.
    LongKeyMap<Multiset<Log>> logsByTopLevelTid = new LongKeyHashMap<Multiset<Log>>();
    for (Set<Log> cycle : cycles) {
        for (Log log : cycle) {
            long topLevelTid = log.getTid().topTid;
            Multiset<Log> logs = logsByTopLevelTid.get(topLevelTid);
            if (logs == null) {
                logs = TreeMultiset.create(LOG_COMPARATOR);
                logsByTopLevelTid.put(topLevelTid, logs);
            }

            logs.add(log);
        }
    }

    // Abort transactions to break up cycles. Transactions involved in more
    // cycles are aborted first.
    while (!cycles.isEmpty()) {
        // Figure out which top-level transaction(s) is involved in the most number
        // of deadlocks.
        int curMax = 0;
        LongSet abortCandidates = new LongHashSet();
        for (LongKeyMap.Entry<Multiset<Log>> entry : logsByTopLevelTid.entrySet()) {
            int curSize = entry.getValue().size();
            if (curMax > curSize)
                continue;

            if (curMax < curSize) {
                curMax = curSize;
                abortCandidates.clear();
            }

            abortCandidates.add(entry.getKey());
        }

        // Figure out which transaction to abort. (Pick the newest one.)
        Log toAbort = null;
        Multiset<Log> abortSet = null;
        for (LongIterator it = abortCandidates.iterator(); it.hasNext();) {
            long curTopLevelTid = it.next();
            Multiset<Log> curCandidateSet = logsByTopLevelTid.get(curTopLevelTid);
            Log curCandidate = curCandidateSet.iterator().next();

            if (toAbort == null || toAbort.startTime < curCandidate.startTime) {
                toAbort = curCandidate;
                abortSet = curCandidateSet;
            }
        }

        // Abort the transaction.
        WORKER_DEADLOCK_LOGGER.log(Level.FINE, "Aborting {0}", toAbort);
        toAbort.flagRetry();

        // Fix up our data structures to reflect the aborted transaction.
        for (Iterator<Set<Log>> cycleIt = cycles.iterator(); cycleIt.hasNext();) {
            Set<Log> cycle = cycleIt.next();

            // Check if the cycle has a transaction that was aborted.
            if (!haveCommonElements(cycle, abortSet.elementSet()))
                continue;

            // Cycle was broken, so remove from the set of cycles.
            cycleIt.remove();

            // Fix up logsByTopLevelTid.
            for (Log log : cycle) {
                long topLevelTid = log.getTid().topTid;
                Multiset<Log> logs = logsByTopLevelTid.get(topLevelTid);
                logs.remove(log);
                if (logs.isEmpty()) {
                    logsByTopLevelTid.remove(topLevelTid);
                }
            }
        }
    }
}