List of usage examples for org.apache.commons.lang.mutable MutableInt add
public void add(Number operand)
From source file:c5db.client.ProtobufUtil.java
/** * Create a protocol buffer Mutate based on a client Mutation * * @param type The type of mutation to create * @param mutation The client Mutation//ww w. ja v a 2s . c o m * @return a protobuf Mutation */ @NotNull public static MutationProto toMutation(final MutationProto.MutationType type, final Mutation mutation) { List<MutationProto.ColumnValue> columnValues = new ArrayList<>(); List<NameBytesPair> attributes = new ArrayList<>(); final MutableInt cellCount = new MutableInt(0); mutation.getFamilyCellMap().forEach((family, cells) -> { List<MutationProto.ColumnValue.QualifierValue> qualifierValues = new ArrayList<>(); for (Cell cell : cells) { KeyValue kv = KeyValueUtil.ensureKeyValue(cell); cellCount.add(1); ByteBuffer qualifier = ByteBuffer.wrap(cell.getQualifier()); ByteBuffer value = ByteBuffer.wrap(cell.getValue()); MutationProto.DeleteType deleteType; if (type == MutationProto.MutationType.DELETE) { KeyValue.Type keyValueType = KeyValue.Type.codeToType(kv.getTypeByte()); deleteType = toDeleteType(keyValueType); } else { deleteType = null; } MutationProto.ColumnValue.QualifierValue qualifierValue = new MutationProto.ColumnValue.QualifierValue( qualifier, value, cell.getTimestamp(), deleteType); qualifierValues.add(qualifierValue); } columnValues.add(new MutationProto.ColumnValue(ByteBuffer.wrap(family), qualifierValues)); }); MutationProto.Durability durability = MutationProto.Durability.valueOf(mutation.getDurability().ordinal()); return new MutationProto(ByteBuffer.wrap(mutation.getRow()), type, columnValues, mutation.getTimeStamp(), attributes, durability, new c5db.client.generated.TimeRange(), cellCount.intValue()); }
From source file:com.aionemu.gameserver.model.instance.instancereward.DredgionReward.java
public void addPointsByRace(Race race, int points) { MutableInt racePoints = getPointsByRace(race); racePoints.add(points); if (racePoints.intValue() < 0) { racePoints.setValue(0);/* w ww . j a v a 2s .c o m*/ } }
From source file:com.aionemu.gameserver.model.instance.instancereward.IdgelDomeReward.java
public void addPvpKillsByRace(Race race, int points) { MutableInt racePoints = getPvpKillsByRace(race); racePoints.add(points); if (racePoints.intValue() < 0) { racePoints.setValue(0);//from ww w . j a va2s .c om } }
From source file:com.ms.commons.test.classloader.util.VelocityTemplateUtil.java
protected static String evalString(Map<Object, Object> context, String str, MutableInt depth) { if (depth.intValue() > 5) { System.err.println("eval depth > 5 for `" + StringUtils.substring(str, 0, 50) + "`."); return str; }//from w ww.j av a 2 s.co m StringBuilder sb = new StringBuilder(); char[] chars = str.toCharArray(); boolean in = false; StringBuilder tsb = new StringBuilder(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; char nc = 0; if ((i + 1) < chars.length) { nc = chars[i + 1]; } if (in) { if (c != '}') { tsb.append(c); } else { Object value = context.get(tsb.toString()); if (value == null) { sb.append("${" + tsb.toString() + "}"); } else { sb.append(value); } tsb = new StringBuilder(); in = false; } } else { if ((c == '$') && (nc == '{')) { in = true; i++; } else { sb.append(c); } } } if (in) { throw new RuntimeException("at last is in"); } String result = sb.toString(); if (result.contains("${")) { depth.add(1); return evalString(context, result, depth); } else { return result; } }
From source file:com.iyonger.apm.web.service.ClusteredAgentManagerService.java
/** * Get the available agent count map in all regions of the user, including * the free agents and user specified agents. * * @param user current user/* w w w . ja v a 2s . c om*/ * @return user available agent count map */ @Override public Map<String, MutableInt> getAvailableAgentCountMap(User user) { Set<String> regions = getRegions(); Map<String, MutableInt> availShareAgents = newHashMap(regions); Map<String, MutableInt> availUserOwnAgent = newHashMap(regions); for (String region : regions) { availShareAgents.put(region, new MutableInt(0)); availUserOwnAgent.put(region, new MutableInt(0)); } String myAgentSuffix = "owned_" + user.getUserId(); for (GrinderAgentInfo grinderAgentInfo : getAllActive()) { // Skip all agents which are disapproved, inactive or // have no region prefix. if (!grinderAgentInfo.isApproved()) { continue; } String fullRegion = grinderAgentInfo.getRegion(); String region = extractRegionFromAgentRegion(fullRegion); if (StringUtils.isBlank(region) || !regions.contains(region)) { continue; } // It's my own agent if (fullRegion.endsWith(myAgentSuffix)) { incrementAgentCount(availUserOwnAgent, region, user.getUserId()); } else if (!fullRegion.contains("owned_")) { incrementAgentCount(availShareAgents, region, user.getUserId()); } } int maxAgentSizePerConsole = getMaxAgentSizePerConsole(); for (String region : regions) { MutableInt mutableInt = availShareAgents.get(region); int shareAgentCount = mutableInt.intValue(); mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole)); mutableInt.add(availUserOwnAgent.get(region)); } return availShareAgents; }
From source file:io.druid.query.search.SearchQueryRunner.java
@Override public Sequence<Result<SearchResultValue>> run(final Query<Result<SearchResultValue>> input, Map<String, Object> responseContext) { if (!(input instanceof SearchQuery)) { throw new ISE("Got a [%s] which isn't a %s", input.getClass(), SearchQuery.class); }/*from ww w . j a va2s. co m*/ final SearchQuery query = (SearchQuery) input; final Filter filter = Filters.convertToCNFFromQueryContext(query, Filters.toFilter(query.getDimensionsFilter())); final List<DimensionSpec> dimensions = query.getDimensions(); final SearchQuerySpec searchQuerySpec = query.getQuery(); final int limit = query.getLimit(); final boolean descending = query.isDescending(); final List<Interval> intervals = query.getQuerySegmentSpec().getIntervals(); if (intervals.size() != 1) { throw new IAE("Should only have one interval, got[%s]", intervals); } final Interval interval = intervals.get(0); // Closing this will cause segfaults in unit tests. final QueryableIndex index = segment.asQueryableIndex(); if (index != null) { final TreeMap<SearchHit, MutableInt> retVal = Maps.newTreeMap(query.getSort().getComparator()); Iterable<DimensionSpec> dimsToSearch; if (dimensions == null || dimensions.isEmpty()) { dimsToSearch = Iterables.transform(index.getAvailableDimensions(), Druids.DIMENSION_IDENTITY); } else { dimsToSearch = dimensions; } final BitmapFactory bitmapFactory = index.getBitmapFactoryForDimensions(); final ImmutableBitmap baseFilter = filter == null ? null : filter.getBitmapIndex(new ColumnSelectorBitmapIndexSelector(bitmapFactory, index)); ImmutableBitmap timeFilteredBitmap; if (!interval.contains(segment.getDataInterval())) { MutableBitmap timeBitmap = bitmapFactory.makeEmptyMutableBitmap(); final Column timeColumn = index.getColumn(Column.TIME_COLUMN_NAME); try (final GenericColumn timeValues = timeColumn.getGenericColumn()) { int startIndex = Math.max(0, getStartIndexOfTime(timeValues, interval.getStartMillis(), true)); int endIndex = Math.min(timeValues.length() - 1, getStartIndexOfTime(timeValues, interval.getEndMillis(), false)); for (int i = startIndex; i <= endIndex; i++) { timeBitmap.add(i); } final ImmutableBitmap finalTimeBitmap = bitmapFactory.makeImmutableBitmap(timeBitmap); timeFilteredBitmap = (baseFilter == null) ? finalTimeBitmap : finalTimeBitmap.intersection(baseFilter); } } else { timeFilteredBitmap = baseFilter; } for (DimensionSpec dimension : dimsToSearch) { final Column column = index.getColumn(dimension.getDimension()); if (column == null) { continue; } final BitmapIndex bitmapIndex = column.getBitmapIndex(); ExtractionFn extractionFn = dimension.getExtractionFn(); if (extractionFn == null) { extractionFn = IdentityExtractionFn.getInstance(); } if (bitmapIndex != null) { for (int i = 0; i < bitmapIndex.getCardinality(); ++i) { String dimVal = Strings.nullToEmpty(extractionFn.apply(bitmapIndex.getValue(i))); if (!searchQuerySpec.accept(dimVal)) { continue; } ImmutableBitmap bitmap = bitmapIndex.getBitmap(i); if (timeFilteredBitmap != null) { bitmap = bitmapFactory.intersection(Arrays.asList(timeFilteredBitmap, bitmap)); } if (bitmap.size() > 0) { MutableInt counter = new MutableInt(bitmap.size()); MutableInt prev = retVal.put(new SearchHit(dimension.getOutputName(), dimVal), counter); if (prev != null) { counter.add(prev.intValue()); } if (retVal.size() >= limit) { return makeReturnResult(limit, retVal); } } } } } return makeReturnResult(limit, retVal); } final StorageAdapter adapter = segment.asStorageAdapter(); if (adapter == null) { log.makeAlert("WTF!? Unable to process search query on segment.") .addData("segment", segment.getIdentifier()).addData("query", query).emit(); throw new ISE( "Null storage adapter found. Probably trying to issue a query against a segment being memory unmapped."); } final Iterable<DimensionSpec> dimsToSearch; if (dimensions == null || dimensions.isEmpty()) { dimsToSearch = Iterables.transform(adapter.getAvailableDimensions(), Druids.DIMENSION_IDENTITY); } else { dimsToSearch = dimensions; } final Sequence<Cursor> cursors = adapter.makeCursors(filter, interval, query.getGranularity(), descending); final TreeMap<SearchHit, MutableInt> retVal = cursors.accumulate( Maps.<SearchHit, SearchHit, MutableInt>newTreeMap(query.getSort().getComparator()), new Accumulator<TreeMap<SearchHit, MutableInt>, Cursor>() { @Override public TreeMap<SearchHit, MutableInt> accumulate(TreeMap<SearchHit, MutableInt> set, Cursor cursor) { if (set.size() >= limit) { return set; } Map<String, DimensionSelector> dimSelectors = Maps.newHashMap(); for (DimensionSpec dim : dimsToSearch) { dimSelectors.put(dim.getOutputName(), cursor.makeDimensionSelector(dim)); } while (!cursor.isDone()) { for (Map.Entry<String, DimensionSelector> entry : dimSelectors.entrySet()) { final DimensionSelector selector = entry.getValue(); if (selector != null) { final IndexedInts vals = selector.getRow(); for (int i = 0; i < vals.size(); ++i) { final String dimVal = selector.lookupName(vals.get(i)); if (searchQuerySpec.accept(dimVal)) { MutableInt counter = new MutableInt(1); MutableInt prev = set.put(new SearchHit(entry.getKey(), dimVal), counter); if (prev != null) { counter.add(prev.intValue()); } if (set.size() >= limit) { return set; } } } } } cursor.advance(); } return set; } }); return makeReturnResult(limit, retVal); }
From source file:com.smartitengineering.events.async.api.impl.hub.AppTest.java
@Test public void testApp() throws Exception { final String textPlain = "text/plain"; final String message = "Message"; final MutableInt mutableInt = new MutableInt(); final MutableInt startCounter = new MutableInt(); final MutableInt endCounter = new MutableInt(); EventConsumer consumer = new EventConsumer() { @Override/*from w w w . j a v a 2s . co m*/ public void consume(String eventContentType, String eventMessage) { Assert.assertEquals(textPlain, eventContentType); Assert.assertTrue(eventMessage.startsWith(message)); mutableInt.add(1); LOGGER.info("Consuming message " + eventMessage); } @Override public void startConsumption() { startCounter.increment(); } @Override public void endConsumption(boolean prematureEnd) { Assert.assertFalse(prematureEnd); endCounter.increment(); } }; subscriber.addConsumer(consumer); publisher.publishEvent(textPlain, message); LOGGER.info("Publish first event!"); Thread.sleep(1200); Assert.assertEquals(1, mutableInt.intValue()); final int count = 20; for (int i = 0; i < count; i++) { publisher.publishEvent(textPlain, message + " " + i); } LOGGER.info("Publish " + count + " more events!"); Thread.sleep(5500); Assert.assertEquals(count + 1, mutableInt.intValue()); Assert.assertEquals(2, startCounter.intValue()); Assert.assertEquals(2, endCounter.intValue()); subscriber.removeConsumer(consumer); }
From source file:com.intellectualcrafters.plot.commands.Rate.java
@Override public boolean onCommand(final PlotPlayer player, final String[] args) { if (args.length == 1) { if (args[0].equalsIgnoreCase("next")) { final ArrayList<Plot> plots = new ArrayList<>(PS.get().getBasePlots()); Collections.sort(plots, new Comparator<Plot>() { @Override//from www . java2 s .com public int compare(final Plot p1, final Plot p2) { double v1 = 0; double v2 = 0; if (p1.getSettings().ratings != null) { for (final Entry<UUID, Rating> entry : p1.getRatings().entrySet()) { v1 -= 11 - entry.getValue().getAverageRating(); } } if (p2.getSettings().ratings != null) { for (final Entry<UUID, Rating> entry : p2.getRatings().entrySet()) { v2 -= 11 - entry.getValue().getAverageRating(); } } if (v1 == v2) { return -0; } return v2 > v1 ? 1 : -1; } }); final UUID uuid = player.getUUID(); for (final Plot p : plots) { if ((!Settings.REQUIRE_DONE || p.getFlags().containsKey("done")) && p.isBasePlot() && ((p.getSettings().ratings == null) || !p.getSettings().ratings.containsKey(uuid)) && !p.isAdded(uuid)) { MainUtil.teleportPlayer(player, player.getLocation(), p); MainUtil.sendMessage(player, C.RATE_THIS); return true; } } MainUtil.sendMessage(player, C.FOUND_NO_PLOTS); return false; } } final Location loc = player.getLocation(); final Plot plot = MainUtil.getPlot(loc); if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); } if (!plot.hasOwner()) { sendMessage(player, C.RATING_NOT_OWNED); return false; } if (plot.isOwner(player.getUUID())) { sendMessage(player, C.RATING_NOT_YOUR_OWN); return false; } if (Settings.REQUIRE_DONE && !plot.getFlags().containsKey("done")) { sendMessage(player, C.RATING_NOT_DONE); return false; } if ((Settings.RATING_CATEGORIES != null) && (Settings.RATING_CATEGORIES.size() != 0)) { final Runnable run = new Runnable() { @Override public void run() { if (plot.getSettings().ratings.containsKey(player.getUUID())) { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; } final MutableInt index = new MutableInt(0); final MutableInt rating = new MutableInt(0); final String title = Settings.RATING_CATEGORIES.get(0); final PlotInventory inventory = new PlotInventory(player, 1, title) { @Override public boolean onClick(final int i) { rating.add((i + 1) * Math.pow(10, index.intValue())); index.increment(); if (index.intValue() >= Settings.RATING_CATEGORIES.size()) { close(); final int rV = rating.intValue(); final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rV)); plot.getSettings().ratings.put(player.getUUID(), result.getAggregate()); DBFunc.setRating(plot, player.getUUID(), rV); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); return false; } setTitle(Settings.RATING_CATEGORIES.get(index.intValue())); if (Permissions.hasPermission(player, "plots.comment")) { final Command<PlotPlayer> command = MainCommand.getInstance().getCommand("comment"); if (command != null) { MainUtil.sendMessage(player, C.COMMENT_THIS, command.getUsage().replaceAll("{label}", "plot")); } } return false; } }; inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8")); inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/8")); inventory.setItem(2, new PlotItemStack(35, (short) 1, 2, "2/8")); inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8")); inventory.setItem(4, new PlotItemStack(35, (short) 5, 4, "4/8")); inventory.setItem(5, new PlotItemStack(35, (short) 9, 5, "5/8")); inventory.setItem(6, new PlotItemStack(35, (short) 11, 6, "6/8")); inventory.setItem(7, new PlotItemStack(35, (short) 10, 7, "7/8")); inventory.setItem(8, new PlotItemStack(35, (short) 2, 8, "8/8")); inventory.openInventory(); } }; if (plot.getSettings().ratings == null) { if (!Settings.CACHE_RATINGS) { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } }); return true; } plot.getSettings().ratings = new HashMap<UUID, Integer>(); } run.run(); return true; } if (args.length < 1) { sendMessage(player, C.RATING_NOT_VALID); return true; } final String arg = args[0]; final int rating; if (MathMan.isInteger(arg) && (arg.length() < 3) && (arg.length() > 0)) { rating = Integer.parseInt(arg); if (rating > 10 || rating < 1) { sendMessage(player, C.RATING_NOT_VALID); return false; } } else { sendMessage(player, C.RATING_NOT_VALID); return false; } final UUID uuid = player.getUUID(); final Runnable run = new Runnable() { @Override public void run() { if (plot.getSettings().ratings.containsKey(uuid)) { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; } final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); final int resultVal = result.getAggregate(); plot.getSettings().ratings.put(uuid, resultVal); DBFunc.setRating(plot, uuid, resultVal); sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); } }; if (plot.getSettings().ratings == null) { if (!Settings.CACHE_RATINGS) { TaskManager.runTaskAsync(new Runnable() { @Override public void run() { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } }); return true; } plot.getSettings().ratings = new HashMap<UUID, Integer>(); } run.run(); return true; }
From source file:io.cloudslang.lang.tools.build.tester.parallel.services.TestCaseEventDispatchServiceTest.java
@Test public void notifyListenersSuccess() throws InterruptedException { final MutableInt mutableInt = new MutableInt(0); final MutableBoolean mutableBoolean = new MutableBoolean(false); ISlangTestCaseEventListener listenerIncrement = new ISlangTestCaseEventListener() { @Override/*w w w. j av a 2 s. c om*/ public void onEvent(SlangTestCaseEvent event) { mutableInt.increment(); } }; ISlangTestCaseEventListener listenerIncrementTwice = new ISlangTestCaseEventListener() { @Override public void onEvent(SlangTestCaseEvent event) { mutableInt.add(2); mutableBoolean.setValue(true); } }; TestCaseEventDispatchService localTestCaseEventDispatchService = new TestCaseEventDispatchService(); localTestCaseEventDispatchService.initializeListeners(); localTestCaseEventDispatchService.registerListener(listenerIncrement); localTestCaseEventDispatchService.registerListener(listenerIncrementTwice); localTestCaseEventDispatchService.notifyListeners( new SlangTestCaseEvent(new SlangTestCase("name", null, null, null, null, null, null, null, null))); while (mutableBoolean.isFalse()) { Thread.sleep(50); } // Checks that all listeners are called, order is not important assertEquals(3, mutableInt.getValue()); }
From source file:com.hp.alm.ali.idea.rest.TroubleShootServiceTest.java
@Test public void testNotification() throws IOException { File file = File.createTempFile("trouble", ""); troubleShootService.start(file);/*from www . j a va 2 s. c o m*/ final MessageBusConnection connection = getProject().getMessageBus().connect(); final MutableInt times = new MutableInt(0); connection.subscribe(Notifications.TOPIC, new Notifications() { @Override public void notify(@NotNull Notification notification) { Assert.assertEquals("HP ALM Integration", notification.getGroupId()); Assert.assertEquals("Troubleshooting mode is on and all REST communication is being tracked.", notification.getTitle()); Assert.assertEquals(NotificationType.INFORMATION, notification.getType()); times.add(1); } @Override public void register(@NotNull String groupDisplayName, @NotNull NotificationDisplayType defaultDisplayType) { } @Override public void register(@NotNull String groupDisplayName, @NotNull NotificationDisplayType defaultDisplayType, boolean shouldLog) { } // needed for 13, adapter class not defined in 12.1.1 public void register(@NotNull String groupDisplayName, @NotNull NotificationDisplayType defaultDisplayType, boolean shouldLog, boolean shouldReadAloud) { } }); troubleShootService._setNotificationDelay(60000); for (int i = 0; i < 100; i++) { troubleShootService.request(getProject(), "GET", new MyInputData("<foo/>"), "defects/{0}", "0"); } testApplication.waitForBackgroundActivityToFinish(); // only 1 notification due to notification delay Assert.assertEquals(1, times.getValue()); troubleShootService._setNotificationDelay(0); for (int i = 0; i < 100; i++) { troubleShootService.request(getProject(), "GET", new MyInputData("<foo/>"), "defects/{0}", "0"); } testApplication.waitForBackgroundActivityToFinish(); // additional 10 notifications Assert.assertEquals(11, times.getValue()); connection.disconnect(); troubleShootService.stop(); }