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

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

Introduction

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

Prototype

public Integer toInteger() 

Source Link

Document

Gets this mutable as an instance of Integer.

Usage

From source file:com.datatorrent.lib.util.TopNUniqueSort.java

/**
 * Returns topN objects//from w  w  w.  j a v a2s .  c o m
 * @param n
 * @return Top N in an ArrayList
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public ArrayList getTopN(int n) {
    ArrayList list = new ArrayList();
    E v;
    int j = 0;
    while (((v = q.poll()) != null) && j < n) {
        list.add(v);
        j++;
    }
    ArrayList<HashMap<E, Integer>> ret = new ArrayList<HashMap<E, Integer>>(list.size());
    int size = list.size();
    int depth = size;
    if (depth > n) {
        depth = n;
    }
    for (int i = 0; i < depth; i++) {
        E o = (E) list.get(size - i - 1);
        HashMap<E, Integer> val = new HashMap<E, Integer>(1);
        MutableInt ival = hmap.get(o);
        val.put(o, ival.toInteger());
        ret.add(val);
    }
    return ret;
}

From source file:com.datatorrent.lib.math.SumCountMap.java

/**
 * Emits on all ports that are connected. Data is precomputed during process
 * on input port endWindow just emits it for each key Clears the internal data
 * before return/*  w w  w  .  ja v a2 s.c o  m*/
 */
@Override
public void endWindow() {

    // Should allow users to send each key as a separate tuple to load balance
    // This is an aggregate node, so load balancing would most likely not be
    // needed

    HashMap<K, V> tuples = new HashMap<K, V>();
    HashMap<K, Integer> ctuples = new HashMap<K, Integer>();
    HashMap<K, Double> dtuples = new HashMap<K, Double>();
    HashMap<K, Integer> ituples = new HashMap<K, Integer>();
    HashMap<K, Float> ftuples = new HashMap<K, Float>();
    HashMap<K, Long> ltuples = new HashMap<K, Long>();
    HashMap<K, Short> stuples = new HashMap<K, Short>();

    for (Map.Entry<K, MutableDouble> e : sums.entrySet()) {
        K key = e.getKey();
        MutableDouble val = e.getValue();
        tuples.put(key, getValue(val.doubleValue()));
        dtuples.put(key, val.doubleValue());
        ituples.put(key, val.intValue());
        ftuples.put(key, val.floatValue());
        ltuples.put(key, val.longValue());
        stuples.put(key, val.shortValue());
        // ctuples.put(key, counts.get(e.getKey()).toInteger());
        MutableInt c = counts.get(e.getKey());
        if (c != null) {
            ctuples.put(key, c.toInteger());
        }
    }

    sum.emit(tuples);
    sumDouble.emit(dtuples);
    sumInteger.emit(ituples);
    sumLong.emit(ltuples);
    sumShort.emit(stuples);
    sumFloat.emit(ftuples);
    count.emit(ctuples);
    clearCache();
}

From source file:mitm.common.hibernate.DatabaseActionExecutorImplTest.java

@Test
public void testRetry() throws Exception {
    final MutableInt count = new MutableInt();

    final int retries = 3;

    Integer result = databaseActionExecutor.executeTransaction(new DatabaseAction<Integer>() {
        @Override//www  .j av a 2s.c o  m
        public Integer doAction(Session session) throws DatabaseException {
            count.increment();

            if (count.intValue() < retries) {
                throw new ConstraintViolationException("Dummy ConstraintViolationException", null, "");
            }

            return count.toInteger();
        }
    }, retries);

    assertEquals(retries, result.intValue());
}

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);/*from w  ww  .j  a 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);
}

From source file:net.atos.entng.calendar.services.impl.EventServiceMongoImpl.java

@Override
public void importIcal(final String calendarId, String ics, final UserInfos user,
        final Handler<Either<String, JsonObject>> handler) {
    final JsonObject message = new JsonObject();
    message.putString("action", ICalHandler.ACTION_PUT);
    message.putString("calendarId", calendarId);
    message.putString("ics", ics);
    final EventServiceMongoImpl eventService = this;
    final MutableInt i = new MutableInt();

    eb.send(ICalHandler.ICAL_HANDLER_ADDRESS, message, new Handler<Message<JsonObject>>() {
        @Override//from w  w  w .j a  va 2  s  .  c o m
        public void handle(Message<JsonObject> reply) {
            final JsonObject result = new JsonObject();
            if ("ko".equals(reply.body().getString("status"))) {
                handler.handle(new Either.Left<String, JsonObject>(new String("Error")));
            } else {
                JsonObject body = reply.body();
                JsonArray calendarEvents = body.getArray("events");
                final JsonArray invalidCalendarEvents = body.getArray("invalidEvents");
                result.putArray("invalidEvents", invalidCalendarEvents);
                result.putNumber("createdEvents", calendarEvents.size());
                if (calendarEvents.size() == 0) {
                    handler.handle(new Either.Right<String, JsonObject>(result));
                }
                i.add(calendarEvents.size());

                for (Object e : calendarEvents) {
                    final JsonObject calendarEvent = (JsonObject) e;
                    eventService.retrieveByIcsUid(calendarId, calendarEvent.getString("icsUid"), user,
                            new Handler<Either<String, JsonObject>>() {
                                @Override
                                public void handle(Either<String, JsonObject> event) {
                                    // No existing event found
                                    if (event.isRight() && event.right().getValue().size() == 0) {
                                        eventService.create(calendarId, calendarEvent, user,
                                                new Handler<Either<String, JsonObject>>() {
                                                    @Override
                                                    public void handle(Either<String, JsonObject> event) {
                                                        i.subtract(1);
                                                        // There is no more events to create
                                                        if (i.toInteger() == 0) {
                                                            handler.handle(new Either.Right<String, JsonObject>(
                                                                    result));
                                                        }
                                                    }
                                                });
                                    } // Existing event found
                                    else if (event.isRight() && event.right().getValue().size() > 0) {
                                        eventService.update(calendarId,
                                                event.right().getValue().getString("_id"), calendarEvent, user,
                                                new Handler<Either<String, JsonObject>>() {
                                                    @Override
                                                    public void handle(Either<String, JsonObject> event) {
                                                        i.subtract(1);
                                                        // There is no more events to create
                                                        if (i.toInteger() == 0) {
                                                            handler.handle(new Either.Right<String, JsonObject>(
                                                                    result));
                                                        }
                                                    }
                                                });
                                    } // An error occured while retrieving the event
                                    else {
                                        i.subtract(1);
                                        if (i.toInteger() == 0) {
                                            handler.handle(new Either.Right<String, JsonObject>(result));
                                        }
                                    }

                                }
                            });
                }
            }
        }
    });
}

From source file:org.gnenc.yams.portlet.AccountManagement.java

public void importAccountsProcessCSV(ActionRequest actionRequest, ActionResponse actionResponse) {
    List<String[]> failedImports = new ArrayList<String[]>();
    String filePath = ParamUtil.getString(actionRequest, "filePath");
    String doneURL = ParamUtil.getString(actionRequest, "doneURL");
    String group = ParamUtil.getString(actionRequest, "group");
    MutableInt importCount = new MutableInt();

    try {/*w w w  .j  av a2s .  c om*/
        File file = new File(filePath);
        if (!file.exists()) {
            SessionErrors.add(actionRequest, "could-not-find-file-please-try-again");
        }

        failedImports = ActionUtil.parseCSV(actionRequest, file, importCount);
        filePath = file.getAbsolutePath();

    } catch (FileNotFoundException e) {
        SessionErrors.add(actionRequest, "could-not-find-file-please-try-again");

        actionResponse.setRenderParameter("jspPage", PortletUtil.ACCT_MGMT_ACCOUNT_IMPORT_ACCOUNTS_VIEW_JSP);

    } catch (UnknownImportAccountsHeaderException e) {
        SessionErrors.add(actionRequest, "invalid-header");

        actionResponse.setRenderParameter("jspPage", PortletUtil.ACCT_MGMT_ACCOUNT_IMPORT_ACCOUNTS_VIEW_JSP);
    }

    actionRequest.setAttribute("failedImports", failedImports);
    actionRequest.setAttribute("importCount", importCount.toInteger());
    actionRequest.setAttribute("group", group);
    actionRequest.setAttribute("doneURL", doneURL);

    //        if (failedImports.size() > 1) {
    //           String outputFilePath = ActionUtil.writeCSV(failedImports);
    //           actionRequest.setAttribute("filePath", outputFilePath);
    //        }

    actionResponse.setRenderParameter("jspPage", PortletUtil.ACCT_MGMT_ACCOUNT_IMPORT_ACCOUNTS_SUMMARY_JSP);
}