Search in sources :

Example 6 with GwtIncompatible

use of com.google.common.annotations.GwtIncompatible in project closure-compiler by google.

the class SourceFile method fromZipEntry.

@GwtIncompatible("java.net.URL")
public static SourceFile fromZipEntry(String originalZipPath, String absoluteZipPath, String entryPath, Charset inputCharset) throws MalformedURLException {
    String zipEntryPath = JAR_URL_PREFIX + absoluteZipPath + BANG_SLASH + entryPath;
    URL zipEntryUrl = new URL(zipEntryPath);
    return builder().withCharset(inputCharset).withOriginalPath(originalZipPath + BANG_SLASH + entryPath).buildFromUrl(zipEntryUrl);
}
Also used : URL(java.net.URL) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Example 7 with GwtIncompatible

use of com.google.common.annotations.GwtIncompatible in project closure-compiler by google.

the class VariableMap method toBytes.

/**
 * Serializes the variable map to a byte array.
 */
@GwtIncompatible("java.io.ByteArrayOutputStream")
public byte[] toBytes() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(baos, UTF_8);
    try {
        // The output order should be stable.
        for (Map.Entry<String, String> entry : ImmutableSortedSet.copyOf(comparingByKey(), map.entrySet())) {
            writer.write(escape(entry.getKey()));
            writer.write(SEPARATOR);
            writer.write(escape(entry.getValue()));
            writer.write('\n');
        }
        writer.close();
    } catch (IOException e) {
        // is just here to appease the Java compiler.
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}
Also used : OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) Map(java.util.Map) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Example 8 with GwtIncompatible

use of com.google.common.annotations.GwtIncompatible in project closure-compiler by google.

the class GoogleCodingConvention method getPackageName.

/**
 * {@inheritDoc}
 *
 * <p>In Google code, the package name of a source file is its file path.
 * Exceptions: if a source file's parent directory is "test", "tests", or
 * "testing", that directory is stripped from the package name.
 * If a file is generated, strip the "genfiles" prefix to try
 * to match the package of the generating file.
 */
@Override
// TODO(tdeegan): Remove use of Matcher#group to make this fully GWT compatible.
@GwtIncompatible
public String getPackageName(StaticSourceFile source) {
    String name = source.getName();
    Matcher genfilesMatcher = GENFILES_DIR.matcher(name);
    if (genfilesMatcher.find()) {
        name = genfilesMatcher.group(2);
    }
    Matcher m = PACKAGE_WITH_TEST_DIR.matcher(name);
    if (m.find()) {
        return m.group(1);
    } else {
        int lastSlash = name.lastIndexOf('/');
        return lastSlash == -1 ? "" : name.substring(0, lastSlash);
    }
}
Also used : Matcher(java.util.regex.Matcher) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Example 9 with GwtIncompatible

use of com.google.common.annotations.GwtIncompatible in project guava by google.

the class CacheBuilderTest method testRemovalNotification_get_basher.

/**
 * Calls get() repeatedly from many different threads, and tests that all of the removed entries
 * (removed because of size limits or expiration) trigger appropriate removal notifications.
 */
// QueuingRemovalListener
@GwtIncompatible
public void testRemovalNotification_get_basher() throws InterruptedException {
    int nTasks = 1000;
    int nThreads = 100;
    final int getsPerTask = 1000;
    final int nUniqueKeys = 10000;
    // Randoms.insecureRandom();
    final Random random = new Random();
    QueuingRemovalListener<String, String> removalListener = queuingRemovalListener();
    final AtomicInteger computeCount = new AtomicInteger();
    final AtomicInteger exceptionCount = new AtomicInteger();
    final AtomicInteger computeNullCount = new AtomicInteger();
    CacheLoader<String, String> countingIdentityLoader = new CacheLoader<String, String>() {

        @Override
        public String load(String key) throws InterruptedException {
            int behavior = random.nextInt(4);
            if (behavior == 0) {
                // throw an exception
                exceptionCount.incrementAndGet();
                throw new RuntimeException("fake exception for test");
            } else if (behavior == 1) {
                // return null
                computeNullCount.incrementAndGet();
                return null;
            } else if (behavior == 2) {
                // slight delay before returning
                Thread.sleep(5);
                computeCount.incrementAndGet();
                return key;
            } else {
                computeCount.incrementAndGet();
                return key;
            }
        }
    };
    final LoadingCache<String, String> cache = CacheBuilder.newBuilder().recordStats().concurrencyLevel(2).expireAfterWrite(100, MILLISECONDS).removalListener(removalListener).maximumSize(5000).build(countingIdentityLoader);
    ExecutorService threadPool = Executors.newFixedThreadPool(nThreads);
    for (int i = 0; i < nTasks; i++) {
        // https://errorprone.info/bugpattern/FutureReturnValueIgnored
        @SuppressWarnings("unused") Future<?> possiblyIgnoredError = threadPool.submit(new Runnable() {

            @Override
            public void run() {
                for (int j = 0; j < getsPerTask; j++) {
                    try {
                        cache.getUnchecked("key" + random.nextInt(nUniqueKeys));
                    } catch (RuntimeException e) {
                    }
                }
            }
        });
    }
    threadPool.shutdown();
    threadPool.awaitTermination(300, SECONDS);
    // Verify that each received removal notification was valid
    for (RemovalNotification<String, String> notification : removalListener) {
        assertEquals("Invalid removal notification", notification.getKey(), notification.getValue());
    }
    CacheStats stats = cache.stats();
    assertEquals(removalListener.size(), stats.evictionCount());
    assertEquals(computeCount.get(), stats.loadSuccessCount());
    assertEquals(exceptionCount.get() + computeNullCount.get(), stats.loadExceptionCount());
    // each computed value is still in the cache, or was passed to the removal listener
    assertEquals(computeCount.get(), cache.size() + removalListener.size());
}
Also used : Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Example 10 with GwtIncompatible

use of com.google.common.annotations.GwtIncompatible in project guava by google.

the class CacheBuilderTest method testRemovalNotification_clear_basher.

// "Basher tests", where we throw a bunch of stuff at a LoadingCache and check basic invariants.
/**
 * This is a less carefully-controlled version of {@link #testRemovalNotification_clear} - this is
 * a black-box test that tries to create lots of different thread-interleavings, and asserts that
 * each computation is affected by a call to {@code clear()} (and therefore gets passed to the
 * removal listener), or else is not affected by the {@code clear()} (and therefore exists in the
 * cache afterward).
 */
// QueuingRemovalListener
@GwtIncompatible
public void testRemovalNotification_clear_basher() throws InterruptedException {
    // If a clear() happens close to the end of computation, one of two things should happen:
    // - computation ends first: the removal listener is called, and the cache does not contain the
    // key/value pair
    // - clear() happens first: the removal listener is not called, and the cache contains the pair
    AtomicBoolean computationShouldWait = new AtomicBoolean();
    CountDownLatch computationLatch = new CountDownLatch(1);
    QueuingRemovalListener<String, String> listener = queuingRemovalListener();
    final LoadingCache<String, String> cache = CacheBuilder.newBuilder().removalListener(listener).concurrencyLevel(20).build(new DelayingIdentityLoader<String>(computationShouldWait, computationLatch));
    int nThreads = 100;
    int nTasks = 1000;
    int nSeededEntries = 100;
    Set<String> expectedKeys = Sets.newHashSetWithExpectedSize(nTasks + nSeededEntries);
    // entries
    for (int i = 0; i < nSeededEntries; i++) {
        String s = "b" + i;
        cache.getUnchecked(s);
        expectedKeys.add(s);
    }
    computationShouldWait.set(true);
    final AtomicInteger computedCount = new AtomicInteger();
    ExecutorService threadPool = Executors.newFixedThreadPool(nThreads);
    final CountDownLatch tasksFinished = new CountDownLatch(nTasks);
    for (int i = 0; i < nTasks; i++) {
        final String s = "a" + i;
        // https://errorprone.info/bugpattern/FutureReturnValueIgnored
        @SuppressWarnings("unused") Future<?> possiblyIgnoredError = threadPool.submit(new Runnable() {

            @Override
            public void run() {
                cache.getUnchecked(s);
                computedCount.incrementAndGet();
                tasksFinished.countDown();
            }
        });
        expectedKeys.add(s);
    }
    computationLatch.countDown();
    // let some computations complete
    while (computedCount.get() < nThreads) {
        Thread.yield();
    }
    cache.invalidateAll();
    tasksFinished.await();
    // Check all of the removal notifications we received: they should have had correctly-associated
    // keys and values. (An earlier bug saw removal notifications for in-progress computations,
    // which had real keys with null values.)
    Map<String, String> removalNotifications = Maps.newHashMap();
    for (RemovalNotification<String, String> notification : listener) {
        removalNotifications.put(notification.getKey(), notification.getValue());
        assertEquals("Unexpected key/value pair passed to removalListener", notification.getKey(), notification.getValue());
    }
    // notifications for all of them.
    for (int i = 0; i < nSeededEntries; i++) {
        assertEquals("b" + i, removalNotifications.get("b" + i));
    }
    // Each of the values added to the map should either still be there, or have seen a removal
    // notification.
    assertEquals(expectedKeys, Sets.union(cache.asMap().keySet(), removalNotifications.keySet()));
    assertTrue(Sets.intersection(cache.asMap().keySet(), removalNotifications.keySet()).isEmpty());
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Aggregations

GwtIncompatible (com.google.common.annotations.GwtIncompatible)361 NullPointerTester (com.google.common.testing.NullPointerTester)105 TestSuite (junit.framework.TestSuite)54 BigInteger (java.math.BigInteger)40 RoundingMode (java.math.RoundingMode)39 CountDownLatch (java.util.concurrent.CountDownLatch)25 ExecutorService (java.util.concurrent.ExecutorService)18 CancellationException (java.util.concurrent.CancellationException)17 Random (java.util.Random)16 ListTestSuiteBuilder (com.google.common.collect.testing.ListTestSuiteBuilder)15 ExecutionException (java.util.concurrent.ExecutionException)15 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)15 IOException (java.io.IOException)14 BigDecimal (java.math.BigDecimal)14 TestStringSetGenerator (com.google.common.collect.testing.TestStringSetGenerator)11 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)11 TimeoutException (java.util.concurrent.TimeoutException)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 EqualsTester (com.google.common.testing.EqualsTester)10 List (java.util.List)10