Example usage for org.apache.commons.lang.mutable MutableInt setValue

List of usage examples for org.apache.commons.lang.mutable MutableInt setValue

Introduction

In this page you can find the example usage for org.apache.commons.lang.mutable MutableInt setValue.

Prototype

public void setValue(Object value) 

Source Link

Document

Sets the value from any Number instance.

Usage

From source file:net.pj.games.eulerproject.elements.StringPermutator.java

private static int getIndexOfMax(String s) {

    final MutableInt maxIndex = new MutableInt(-1);
    s.chars().max().ifPresent(m -> maxIndex.setValue(s.indexOf(m)));
    return maxIndex.intValue();
}

From source file:com.topekalabs.bigmachine.lib.testutils.SimpleContinuationRunnable.java

@Override
public void run() {
    MutableInt val = (MutableInt) Continuation.getContext();
    val.setValue(FIRST_VALUE);
    count = SECOND_VALUE;/*from   ww  w.j  a  v a2s. c  o m*/

    Continuation.suspend();

    val = (MutableInt) Continuation.getContext();
    val.setValue(count);
}

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);//from w ww .j a v a 2 s  .co m
    if (racePoints.intValue() < 0) {
        racePoints.setValue(0);
    }
}

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);//  w  w w. j a  v  a  2  s. c  om
    if (racePoints.intValue() < 0) {
        racePoints.setValue(0);
    }
}

From source file:net.landora.video.addons.AddonManager.java

private List<Addon> createOrderedAddons() {

    ServiceLoader<Addon> loader = ServiceLoader.load(Addon.class);

    final Map<String, Addon> allProviders = new HashMap<String, Addon>();
    for (Addon provider : loader) {
        allProviders.put(provider.getAddonId(), provider);
    }// w  ww .jav  a 2 s.co m

    final Map<String, MutableInt> orders = new HashMap<String, MutableInt>();
    for (String id : allProviders.keySet()) {
        orders.put(id, new MutableInt());
    }

    boolean ordersChanged;
    do {
        ordersChanged = false;
        for (Map.Entry<String, Addon> entry : allProviders.entrySet()) {
            String id = entry.getKey();
            MutableInt myOrder = orders.get(id);

            for (String requiredId : entry.getValue().getRequiredAddons()) {
                MutableInt other = orders.get(requiredId);
                if (other.intValue() >= myOrder.intValue()) {
                    myOrder.setValue(other.intValue() + 1);
                    ordersChanged = true;
                }
            }

            if (myOrder.intValue() > 1000) {
                throw new IllegalStateException("Possible circular dependancy detected: " + id);
            }
        }
    } while (ordersChanged);

    List<String> ids = new ArrayList<String>(allProviders.keySet());
    Comparator<String> cmp = new Comparator<String>() {

        public int compare(String o1, String o2) {
            return orders.get(o1).compareTo(orders.get(o2));
        }
    };
    Collections.sort(ids, cmp);

    List<Addon> result = new ArrayList<Addon>(ids.size());
    for (String id : ids) {
        result.add(allProviders.get(id));
    }

    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 ww .  j av  a2  s.  c o m
 * @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:com.novartis.pcs.ontology.service.parser.obo.OBOTagHandler.java

protected String substr(String value, char startChar, char endChar, MutableInt fromIndex) {
    String substr = null;/*from   w w  w  . j a  va2 s . c om*/
    int start = indexOf(value, startChar, fromIndex.intValue());
    if (start != -1) {
        int end = indexOf(value, endChar, start + 1);

        if (end == -1) {
            throw new InvalidFormatException("Invalid OBO " + tagName.getName() + " format: " + value);
        }
        substr = value.substring(start + 1, end);
        fromIndex.setValue(end + 1);
    }
    return substr;
}

From source file:com.novartis.pcs.ontology.service.parser.obo.SynonymTagHandler.java

private Synonym.Type parseType(String value, MutableInt fromIndex) {
    Synonym.Type type = Synonym.Type.RELATED;

    while (fromIndex.intValue() < value.length()
            && Character.isWhitespace(value.charAt(fromIndex.intValue()))) {
        fromIndex.increment();//from   w  ww . jav a2 s  .  com
    }

    int start = fromIndex.intValue();

    while (fromIndex.intValue() < value.length() && Character.isLetter(value.charAt(fromIndex.intValue()))) {
        fromIndex.increment();
    }

    if (start < fromIndex.intValue()) {
        String scope = value.substring(start, fromIndex.intValue());
        try {
            type = Synonym.Type.valueOf(scope.toUpperCase());
        } catch (IllegalArgumentException e) {
            type = Synonym.Type.RELATED;
            fromIndex.setValue(start);
        }
    }

    return type;
}

From source file:com.datatorrent.contrib.hdht.MockFileAccess.java

@Override
public FileReader getReader(final long bucketKey, final String fileName) throws IOException {
    final HashMap<Slice, Pair<byte[], Integer>> data = Maps.newHashMap();
    final ArrayList<Slice> keys = Lists.newArrayList();
    final MutableInt index = new MutableInt();

    DataInputStream is = getInputStream(bucketKey, fileName);
    Input input = new Input(is);
    while (!input.eof()) {
        byte[] keyBytes = kryo.readObject(input, byte[].class);
        byte[] value = kryo.readObject(input, byte[].class);
        Slice key = new Slice(keyBytes, 0, keyBytes.length);
        data.put(key, new Pair<byte[], Integer>(value, keys.size()));
        keys.add(key);//w  w w .j  a  v  a2s  . c o  m
    }
    input.close();
    is.close();

    return new FileReader() {

        @Override
        public void readFully(TreeMap<Slice, Slice> result) throws IOException {
            for (Map.Entry<Slice, Pair<byte[], Integer>> e : data.entrySet()) {
                result.put(e.getKey(), new Slice(e.getValue().first));
            }
        }

        @Override
        public void reset() throws IOException {
            index.setValue(0);
        }

        @Override
        public boolean seek(Slice key) throws IOException {
            Pair<byte[], Integer> v = data.get(key);
            if (v == null) {
                index.setValue(0);
                return false;
            }
            index.setValue(v.second);
            return true;
        }

        @Override
        public boolean next(Slice key, Slice value) throws IOException {

            if (deletedFiles.contains("" + bucketKey + fileName)) {
                throw new IOException("Simulated error for deleted file: " + fileName);
            }

            int pos = index.intValue();
            if (pos < keys.size()) {
                Slice k = keys.get(pos);
                key.buffer = k.buffer;
                key.offset = k.offset;
                key.length = k.length;
                Pair<byte[], Integer> v = data.get(k);
                value.buffer = v.first;
                value.offset = 0;
                value.length = v.first.length;
                index.increment();
                return true;
            }
            return false;
        }

        @Override
        public void close() throws IOException {
        }
    };
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransactionTest.java

@Test
public void testTransactionAtomicity() throws Exception {
    // This test runs multiple transactions in parallel, with KeyValueService.put calls throwing
    // a RuntimeException from time to time and hanging other times. which effectively kills the
    // thread. We ensure that every transaction either adds 5 rows to the table or adds 0 rows
    // by checking at the end that the number of rows is a multiple of 5.
    final String tableName = "table";
    Random random = new Random(1);

    final UnstableKeyValueService unstableKvs = new UnstableKeyValueService(keyValueService, random);
    final TestTransactionManager unstableTransactionManager = new TestTransactionManagerImpl(unstableKvs,
            timestampService, lockClient, lockService, transactionService, conflictDetectionManager,
            sweepStrategyManager);/* w w  w . ja  v a2  s.c o  m*/

    ScheduledExecutorService service = PTExecutors.newScheduledThreadPool(20);

    for (int i = 0; i < 30; i++) {
        final int threadNumber = i;
        service.schedule(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                if (threadNumber == 10) {
                    unstableKvs.setRandomlyThrow(true);
                }
                if (threadNumber == 20) {
                    unstableKvs.setRandomlyHang(true);
                }

                Transaction transaction = unstableTransactionManager.createNewTransaction();
                BatchingVisitable<RowResult<byte[]>> results = transaction.getRange(tableName,
                        RangeRequest.builder().build());

                final MutableInt nextIndex = new MutableInt(0);
                results.batchAccept(1,
                        AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() {
                            @Override
                            public boolean visit(RowResult<byte[]> row) throws Exception {
                                byte[] dataBytes = row.getColumns().get("data".getBytes());
                                BigInteger dataValue = new BigInteger(dataBytes);
                                nextIndex.setValue(Math.max(nextIndex.toInteger(), dataValue.intValue() + 1));
                                return true;
                            }
                        }));

                // nextIndex now contains the least row number not already in the table. Add 5 more
                // rows to the table.
                for (int j = 0; j < 5; j++) {
                    int rowNumber = nextIndex.toInteger() + j;
                    Cell cell = Cell.create(("row" + rowNumber).getBytes(), "data".getBytes());
                    transaction.put(tableName,
                            ImmutableMap.of(cell, BigInteger.valueOf(rowNumber).toByteArray()));
                    Thread.yield();
                }
                transaction.commit();
                return null;
            }
        }, i * 20, TimeUnit.MILLISECONDS);
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.SECONDS);

    // Verify each table has a number of rows that's a multiple of 5
    Transaction verifyTransaction = txManager.createNewTransaction();
    BatchingVisitable<RowResult<byte[]>> results = verifyTransaction.getRange(tableName,
            RangeRequest.builder().build());

    final MutableInt numRows = new MutableInt(0);
    results.batchAccept(1, AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() {
        @Override
        public boolean visit(RowResult<byte[]> row) throws Exception {
            numRows.increment();
            return true;
        }
    }));

    Assert.assertEquals(0, numRows.toInteger() % 5);
}