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

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

Introduction

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

Prototype

@Override
public void setValue(final Number value) 

Source Link

Document

Sets the value from any Number instance.

Usage

From source file:de.biomedical_imaging.ij.steger.Position.java

/** Solve the linear equation a*x+b=0 and return the result in t and the number
   of solutions in num. **//*from  www. j  a v a2 s. c o m*/
public void solve_linear(double a, double b, MutableDouble t, MutableInt num) {

    if (a == 0.0) { //
        num.setValue(0);
        return;
    } else {
        num.setValue(1);
        t.setValue(-b / a);
        return;
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJobManagerGaeMinimalTest.java

/**
 * @throws Exception if an error occurs// ww  w  .  j ava  2 s . c  om
 */
@Test
public void getJobCount() throws Exception {
    final MutableInt count = new MutableInt();
    final JavaScriptJob job = new BasicJavaScriptJob(50, null) {
        @Override
        public void run() {
            count.setValue(manager_.getJobCount());
        }
    };
    assertEquals(0, manager_.getJobCount());
    manager_.addJob(job, page_);
    final int executedJobs = eventLoop_.pumpEventLoop(1000);
    assertEquals(1, executedJobs);
    assertEquals(1, count.intValue());
    assertEquals(0, manager_.getJobCount());
}

From source file:com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJobManagerMinimalTest.java

/**
 * @throws Exception if an error occurs/*from  www  . j a  v a2s .c  o  m*/
 */
@Test
public void getJobCount() throws Exception {
    final MutableInt count = new MutableInt();
    final JavaScriptJob job = new BasicJavaScriptJob(50, null) {
        @Override
        public void run() {
            count.setValue(manager_.getJobCount());
        }
    };
    assertEquals(0, manager_.getJobCount());
    manager_.addJob(job, page_);
    manager_.waitForJobs(1000);
    assertEquals(1, count.intValue());
    assertEquals(0, manager_.getJobCount());
}

From source file:com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJobManagerGaeMinimalTest.java

/**
 * @throws Exception if an error occurs/*w ww .  ja  va  2 s.c o m*/
 */
@Test
public void addJob_multipleExecution_removeJob() throws Exception {
    final MutableInt id = new MutableInt();
    final MutableInt count = new MutableInt(0);
    final JavaScriptJob job = new BasicJavaScriptJob(50, Integer.valueOf(50)) {
        @Override
        public void run() {
            count.increment();
            if (count.intValue() >= 5) {
                manager_.removeJob(id.intValue());
            }
        }
    };
    id.setValue(manager_.addJob(job, page_));
    final int executedJobs = eventLoop_.pumpEventLoop(1000);
    assertEquals(5, executedJobs);
    assertEquals(5, count.intValue());
}

From source file:com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJobManagerMinimalTest.java

/**
 * @throws Exception if an error occurs/*ww w  .ja v  a  2 s  .com*/
 */
@Test
public void addJob_multipleExecution_removeJob() throws Exception {
    final MutableInt id = new MutableInt();
    final MutableInt count = new MutableInt(0);
    final JavaScriptJob job = new BasicJavaScriptJob(50, Integer.valueOf(50)) {
        @Override
        public void run() {
            count.increment();
            if (count.intValue() >= 5) {
                manager_.removeJob(id.intValue());
            }
        }
    };
    id.setValue(manager_.addJob(job, page_));
    manager_.waitForJobs(1000);
    assertEquals(5, count.intValue());
}

From source file:com.serphacker.serposcope.db.google.GoogleSerpRescanDB.java

public void rescanNonBulk(Integer specificRunId, Collection<GoogleTarget> targets,
        Collection<GoogleSearch> searches, boolean updateSummary) {
    LOG.debug("SERP rescan (non-bulk) : starting");
    long _start = System.currentTimeMillis();
    Run specPrevRun = null;/*from ww  w.  j av a 2s. c  o m*/
    Map<Integer, GoogleTargetSummary> specPrevRunSummaryByTarget = new HashMap<>();

    if (specificRunId != null) {
        specPrevRun = runDB.findPrevious(specificRunId);
        if (specPrevRun != null) {
            specPrevRunSummaryByTarget = targetSummaryDB.list(specPrevRun.getId()).stream()
                    .collect(Collectors.toMap(GoogleTargetSummary::getTargetId, Function.identity()));
        }
    }

    for (GoogleTarget target : targets) {

        Map<Integer, GoogleTargetSummary> summaryByRunId = new HashMap<>();
        GoogleTargetSummary specificPreviousSummary = specPrevRunSummaryByTarget.get(target.getId());
        if (specificPreviousSummary != null) {
            summaryByRunId.put(specPrevRun.getId(), specificPreviousSummary);
        }

        for (GoogleSearch search : searches) {
            final MutableInt previousRunId = new MutableInt(0);
            final MutableInt previousRank = new MutableInt(GoogleRank.UNRANKED);
            GoogleBest searchBest = new GoogleBest(target.getGroupId(), target.getId(), search.getId(),
                    GoogleRank.UNRANKED, null, null);

            if (specPrevRun != null) {
                previousRunId.setValue(specPrevRun.getId());
                previousRank.setValue(
                        rankDB.get(specPrevRun.getId(), target.getGroupId(), target.getId(), search.getId()));
                GoogleBest specificBest = rankDB.getBest(target.getGroupId(), target.getId(), search.getId());
                if (specificBest != null) {
                    searchBest = specificBest;
                }
            }
            final GoogleBest best = searchBest;

            serpDB.stream(specificRunId, specificRunId, search.getId(), (GoogleSerp res) -> {

                int rank = GoogleRank.UNRANKED;
                String rankedUrl = null;
                for (int i = 0; i < res.getEntries().size(); i++) {
                    if (target.match(res.getEntries().get(i).getUrl())) {
                        rankedUrl = res.getEntries().get(i).getUrl();
                        rank = i + 1;
                        break;
                    }
                }

                // only update last run
                GoogleRank gRank = new GoogleRank(res.getRunId(), target.getGroupId(), target.getId(),
                        search.getId(), rank, previousRank.shortValue(), rankedUrl);
                rankDB.insert(gRank);

                if (updateSummary) {
                    GoogleTargetSummary summary = summaryByRunId.get(res.getRunId());
                    if (summary == null) {
                        summaryByRunId.put(res.getRunId(),
                                summary = new GoogleTargetSummary(target.getGroupId(), target.getId(),
                                        res.getRunId(), 0));
                    }
                    summary.addRankCandidat(gRank);
                }

                if (rank != GoogleRank.UNRANKED && rank <= best.getRank()) {
                    best.setRank((short) rank);
                    best.setUrl(rankedUrl);
                    best.setRunDay(res.getRunDay());
                }

                previousRunId.setValue(res.getRunId());
                previousRank.setValue(rank);
            });

            if (best.getRank() != GoogleRank.UNRANKED) {
                rankDB.insertBest(best);
            }
        }

        // fill previous summary score
        if (updateSummary) {
            TreeMap<Integer, GoogleTargetSummary> summaries = new TreeMap<>(summaryByRunId);

            GoogleTargetSummary previousSummary = null;
            for (Map.Entry<Integer, GoogleTargetSummary> entry : summaries.entrySet()) {
                if (previousSummary != null) {
                    entry.getValue().setPreviousScoreBP(previousSummary.getScoreBP());
                }
                previousSummary = entry.getValue();
            }

            if (specPrevRun != null) {
                summaries.remove(specPrevRun.getId());
            }

            if (!summaries.isEmpty()) {
                targetSummaryDB.insert(summaries.values());
            }
        }
    }
    LOG.debug("SERP rescan : done, duration = {}",
            DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
}

From source file:com.serphacker.serposcope.db.google.GoogleSerpRescanDB.java

public void rescan(Integer specificRunId, Collection<GoogleTarget> targets, Collection<GoogleSearch> searches,
        boolean updateSummary) {
    LOG.debug("SERP rescan (bulk) : starting");
    long _start = System.currentTimeMillis();
    Map<Integer, Integer> searchCountByGroup = searchDB.countByGroup();
    Run specPrevRun = null;/*from   w  ww. j av a2 s .com*/
    Map<Integer, GoogleTargetSummary> specPrevRunSummaryByTarget = new HashMap<>();

    if (specificRunId != null) {
        specPrevRun = runDB.findPrevious(specificRunId);
        if (specPrevRun != null) {
            specPrevRunSummaryByTarget = targetSummaryDB.list(specPrevRun.getId()).stream()
                    .collect(Collectors.toMap(GoogleTargetSummary::getTargetId, Function.identity()));
        }
    }

    List<GoogleRank> ranks = new ArrayList<>();
    for (GoogleTarget target : targets) {

        Map<Integer, GoogleTargetSummary> summaryByRunId = new HashMap<>();
        GoogleTargetSummary specificPreviousSummary = specPrevRunSummaryByTarget.get(target.getId());
        if (specificPreviousSummary != null) {
            summaryByRunId.put(specPrevRun.getId(), specificPreviousSummary);
        }

        for (GoogleSearch search : searches) {
            final MutableInt previousRunId = new MutableInt(0);
            final MutableInt previousRank = new MutableInt(GoogleRank.UNRANKED);
            GoogleBest searchBest = new GoogleBest(target.getGroupId(), target.getId(), search.getId(),
                    GoogleRank.UNRANKED, null, null);

            if (specPrevRun != null) {
                previousRunId.setValue(specPrevRun.getId());
                previousRank.setValue(
                        rankDB.get(specPrevRun.getId(), target.getGroupId(), target.getId(), search.getId()));
                GoogleBest specificBest = rankDB.getBest(target.getGroupId(), target.getId(), search.getId());
                if (specificBest != null) {
                    searchBest = specificBest;
                }
            }
            final GoogleBest best = searchBest;

            serpDB.stream(specificRunId, specificRunId, search.getId(), (GoogleSerp res) -> {

                int rank = GoogleRank.UNRANKED;
                String rankedUrl = null;
                for (int i = 0; i < res.getEntries().size(); i++) {
                    if (target.match(res.getEntries().get(i).getUrl())) {
                        rankedUrl = res.getEntries().get(i).getUrl();
                        rank = i + 1;
                        break;
                    }
                }

                // only update last run
                GoogleRank gRank = new GoogleRank(res.getRunId(), target.getGroupId(), target.getId(),
                        search.getId(), rank, previousRank.shortValue(), rankedUrl);
                ranks.add(gRank);
                if (ranks.size() > 2000) {
                    rankDB.insert(ranks);
                    ranks.clear();
                }

                if (updateSummary) {
                    GoogleTargetSummary summary = summaryByRunId.get(res.getRunId());
                    if (summary == null) {
                        summaryByRunId.put(res.getRunId(),
                                summary = new GoogleTargetSummary(target.getGroupId(), target.getId(),
                                        res.getRunId(), 0));
                    }
                    summary.addRankCandidat(gRank);
                }

                if (rank != GoogleRank.UNRANKED && rank <= best.getRank()) {
                    best.setRank((short) rank);
                    best.setUrl(rankedUrl);
                    best.setRunDay(res.getRunDay());
                }

                previousRunId.setValue(res.getRunId());
                previousRank.setValue(rank);
            });

            if (best.getRank() != GoogleRank.UNRANKED) {
                rankDB.insertBest(best);
            }
        }

        // fill previous summary score
        if (updateSummary) {
            TreeMap<Integer, GoogleTargetSummary> summaries = new TreeMap<>(summaryByRunId);

            GoogleTargetSummary previousSummary = null;
            for (Map.Entry<Integer, GoogleTargetSummary> entry : summaries.entrySet()) {
                GoogleTargetSummary summary = entry.getValue();
                summary.computeScoreBP(searchCountByGroup.getOrDefault(summary.getGroupId(), 0));
                if (previousSummary != null) {
                    summary.setPreviousScoreBP(previousSummary.getScoreBP());
                }
                previousSummary = summary;
            }

            if (specPrevRun != null) {
                summaries.remove(specPrevRun.getId());
            }

            if (!summaries.isEmpty()) {
                targetSummaryDB.insert(summaries.values());
            }
        }
    }

    if (!ranks.isEmpty()) {
        rankDB.insert(ranks);
        ranks.clear();
    }

    LOG.debug("SERP rescan : done, duration = {}",
            DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
}

From source file:enumj.EnumeratorTest.java

@Test
public void testForEach() {
    System.out.println("forEach");
    final MutableInt m = new MutableInt(0);
    Enumerator.rangeInt(0, 100).forEach(i -> m.setValue(m.intValue() + 1));
    assertEquals(m.intValue(), Enumerator.rangeInt(0, 100).count());
}

From source file:bwem.Graph.java

public CPPath getPath(final Position a, final Position b, final MutableInt pLength) {
    final Area areaA = getNearestArea(a.toWalkPosition());
    final Area areaB = getNearestArea(b.toWalkPosition());

    if (areaA.equals(areaB)) {
        if (pLength != null) {
            pLength.setValue(BwemExt.getApproxDistance(a, b));
        }/*from  w ww. j av  a2s  .  c om*/
        return new CPPath();
    }

    if (!areaA.isAccessibleFrom(areaB)) {
        if (pLength != null) {
            pLength.setValue(-1);
        }
        return new CPPath();
    }

    int minDistAB = Integer.MAX_VALUE;

    ChokePoint pBestCpA = null;
    ChokePoint pBestCpB = null;

    for (final ChokePoint cpA : areaA.getChokePoints()) {
        if (!cpA.isBlocked()) {
            final int distACpA = BwemExt.getApproxDistance(a, cpA.getCenter().toPosition());
            for (final ChokePoint cpB : areaB.getChokePoints()) {
                if (!cpB.isBlocked()) {
                    final int distBToCPB = BwemExt.getApproxDistance(b, cpB.getCenter().toPosition());
                    final int distAToB = distACpA + distBToCPB + distance(cpA, cpB);
                    if (distAToB < minDistAB) {
                        minDistAB = distAToB;
                        pBestCpA = cpA;
                        pBestCpB = cpB;
                    }
                }
            }
        }
    }

    //        bwem_assert(minDistAB != numeric_limits<int>::max());
    if (minDistAB == Integer.MAX_VALUE) {
        throw new IllegalStateException();
    }

    final CPPath path = getPath(pBestCpA, pBestCpB);

    if (pLength != null) {
        //            bwem_assert(Path.size() >= 1);
        if (!(path.size() >= 1)) {
            throw new IllegalStateException();
        }

        pLength.setValue(minDistAB);

        if (path.size() == 1) {
            //                bwem_assert(pBestCpA == pBestCpB);
            if (!pBestCpA.equals(pBestCpB)) {
                throw new IllegalStateException();
            }

            final Position cpEnd1 = BwemExt.center(pBestCpA.getNodePosition(ChokePoint.Node.END1));
            final Position cpEnd2 = BwemExt.center(pBestCpA.getNodePosition(ChokePoint.Node.END2));
            if (Utils.intersect(a.getX(), a.getY(), b.getX(), b.getY(), cpEnd1.getX(), cpEnd1.getY(),
                    cpEnd2.getX(), cpEnd2.getY())) {
                pLength.setValue(BwemExt.getApproxDistance(a, b));
            } else {
                for (final ChokePoint.Node node : new ChokePoint.Node[] { ChokePoint.Node.END1,
                        ChokePoint.Node.END2 }) {
                    final Position c = BwemExt.center(pBestCpA.getNodePosition(node));
                    final int distAToB = BwemExt.getApproxDistance(a, c) + BwemExt.getApproxDistance(b, c);
                    if (distAToB < pLength.intValue()) {
                        pLength.setValue(distAToB);
                    }
                }
            }
        }
    }

    return getPath(pBestCpA, pBestCpB);
}

From source file:com.ibm.jaggr.core.impl.cache.GzipCacheImpl.java

@Override
public InputStream getInputStream(final String key, final URI source, final MutableInt retLength)
        throws IOException {
    final String sourceMethod = "getInputStream"; //$NON-NLS-1$
    final boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(sourceClass, sourceMethod, new Object[] { key, source, retLength });
    }//w  ww  . jav  a 2  s . com

    InputStream in = null, result = null;
    CacheEntry tryCacheEntry = (CacheEntry) super.get(key);
    URLConnection connection = source.toURL().openConnection();

    try {
        long lastModified = connection.getLastModified();
        if (tryCacheEntry != null) {
            // Make local copies of volatile CacheEntry fields
            byte[] bytes = tryCacheEntry.bytes;
            File file = tryCacheEntry.file;
            if (bytes != null) {
                // Important - CacheEntry.lastModified is set before CacheEntry.bytes so we can
                // safely
                // check CacheEntry.lastModified here even though we're not synchronized.
                if (lastModified != tryCacheEntry.lastModified) {
                    // stale cache entry. Remove it and create a new one below
                    cacheMap.remove(key, tryCacheEntry);
                } else {
                    retLength.setValue(tryCacheEntry.bytes.length);
                    result = new ByteArrayInputStream(tryCacheEntry.bytes);
                }
            } else if (file != null) {
                // Some platforms round file last modified times to nearest second.
                if (Math.abs(lastModified - file.lastModified()) > 1000) {
                    // Stale cache entry, remove it and create a new one below
                    cacheMap.remove(key, tryCacheEntry);
                    // also delete the associated cache file asynchronously.
                    cacheManager.deleteFileDelayed(file.getName());
                } else {
                    try {
                        retLength.setValue(file.length());
                        result = new FileInputStream(file);
                    } catch (FileNotFoundException ex) {
                        // File doesn't exist (was probably deleted outside this program)
                        // Not fatal, just fall through and create it again.
                        cacheMap.remove(key, tryCacheEntry);
                    }
                }
            }
            if (result != null) {
                // found result in cache. Return it.
                log.exiting(sourceClass, sourceMethod, result);
                return result;
            }
        }

        // Result not in cache (or we removed it). Try to create a new cache entry.
        CacheEntry newCacheEntry = new CacheEntry();
        CacheEntry oldCacheEntry = (CacheEntry) cacheMap.putIfAbsent(key, newCacheEntry);
        final CacheEntry cacheEntry = oldCacheEntry != null ? oldCacheEntry : newCacheEntry;

        // Synchronize on the cache entry so that more than one thread won't try to create the
        // zipped content.
        synchronized (cacheEntry) {
            if (cacheEntry.ex != null) {
                // An exception occurred trying to create the gzip response in another thread.
                // Re-throw the exception here.
                throw cacheEntry.ex;
            }
            // First, check to make sure that another thread didn't beat us to the punch.
            // Even though we're synchronized on the cacheEntry object, cacheEntry.bytes can be
            // cleared by the createCacheFileAsync callback, so we need to copy this volatile
            // field
            // to a local variable and access it from there.
            byte[] bytes = cacheEntry.bytes;
            if (bytes != null) {
                retLength.setValue(bytes.length);
                result = new ByteArrayInputStream(bytes);
            } else if (cacheEntry.file != null) { // once set, cacheEntry.file does not change
                // by convention
                retLength.setValue(cacheEntry.file.length());
                result = new FileInputStream(cacheEntry.file);
            } else {
                // Gzip encode the resource and save the result in the cache entry until the
                // cache
                // file is written asynchronously.
                try {
                    in = connection.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    VariableGZIPOutputStream compress = new VariableGZIPOutputStream(bos, 10240);
                    compress.setLevel(Deflater.BEST_COMPRESSION);
                    CopyUtil.copy(in, compress);

                    // Important - CacheEntry.lastModified must be set before cacheEntry.bytes
                    cacheEntry.lastModified = lastModified;
                    cacheEntry.bytes = bos.toByteArray();
                    result = new ByteArrayInputStream(cacheEntry.bytes);
                    retLength.setValue(cacheEntry.bytes.length);

                    // Call the cache manager to asynchronously save the gzipped response to
                    // disk
                    // Include the filename part of the source URI in the cached filename
                    String path = source.getPath();
                    int idx = path.lastIndexOf("/"); //$NON-NLS-1$
                    String fname = (idx != -1) ? path.substring(idx + 1) : path;
                    cacheManager.createCacheFileAsync(fname + ".gzip.", //$NON-NLS-1$
                            new ByteArrayInputStream(cacheEntry.bytes),
                            new ICacheManager.CreateCompletionCallback() {
                                @Override
                                public void completed(String filename, Exception e) {
                                    if (e != null && log.isLoggable(Level.SEVERE)) {
                                        // Exception occurred saving file. Not much we can do
                                        // except log the error
                                        log.logp(Level.SEVERE, sourceClass, sourceMethod, e.getMessage(), e);
                                        return;
                                    }
                                    File cacheFile = new File(cacheManager.getCacheDir(), filename);
                                    cacheFile.setLastModified(cacheEntry.lastModified);
                                    // Important - cacheEntry.file must be set before clearing
                                    // cacheEntry.bytes
                                    cacheEntry.file = cacheFile;
                                    cacheEntry.bytes = null;
                                }
                            });
                } catch (Throwable t) {
                    cacheEntry.ex = (t instanceof IOException) ? (IOException) t : new IOException(t);
                    cacheMap.remove(key, cacheEntry);
                    throw cacheEntry.ex;
                }
            }
        }
    } finally {
        // URLConnection doesn't have a close method. The only way to make sure a connection is
        // closed is to close the input or output stream which is obtained from the connection.
        if (in != null) {
            in.close();
        } else {
            connection.getInputStream().close();
        }
    }
    if (isTraceLogging) {
        log.exiting(sourceClass, sourceClass, result);
    }
    return result;
}