javax.annotation.ParametersAreNonnullByDefault Java Examples

The following examples show how to use javax.annotation.ParametersAreNonnullByDefault. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: ic   Author: qunarcorp   File: EventServiceImpl.java    License: MIT License 6 votes vote down vote up
public EventServiceImpl() {
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        running = false;
        logger.info("程序即将退出,publishEvents定时任务将终止");
    }));
    caches = CacheBuilder.newBuilder()
            .maximumSize(10000)
            .recordStats()
            .build(new CacheLoader<Long, Event>() {
                @Override
                @ParametersAreNonnullByDefault
                public Event load(Long key) throws Exception {
                    Event event = queryByIdFromDb(key);
                    logger.info("从数据库中加载事件{}到缓存中,添加前缓存大小为{}", key, caches.size());
                    return event;
                }
            });
}
 
Example #2
Source Project: Camera2   Author: Yuloran   File: ResolutionUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Takes selected sizes and a list of blacklisted sizes. All the blacklistes
 * sizes will be removed from the 'sizes' list.
 *
 * @param sizes           the sizes to be filtered.
 * @param blacklistString a String containing a comma-separated list of
 *                        sizes that should be removed from the original list.
 * @return A list that contains the filtered items.
 */
@ParametersAreNonnullByDefault
public static List<Size> filterBlackListedSizes(List<Size> sizes, String blacklistString)
{
    String[] blacklistStringArray = blacklistString.split(",");
    if (blacklistStringArray.length == 0)
    {
        return sizes;
    }

    Set<String> blacklistedSizes = new HashSet(Lists.newArrayList(blacklistStringArray));
    List<Size> newSizeList = new ArrayList<>();
    for (Size size : sizes)
    {
        if (!isBlackListed(size, blacklistedSizes))
        {
            newSizeList.add(size);
        }
    }
    return newSizeList;
}
 
Example #3
Source Project: retro-game   Author: retro-game   File: BodyInfoCache.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public BodyInfoCache(BodyRepository bodyRepository) {
  cache = CacheBuilder.newBuilder()
      .maximumSize(MAX_SIZE)
      .build(new CacheLoader<>() {
               @Override
               @ParametersAreNonnullByDefault
               public BodyInfoDto load(Long bodyId) {
                 var body = bodyRepository.getOne(bodyId);
                 // TODO: This will load the user, which is unnecessary. We could probably keep only the id of the
                 // owner in the body entity.
                 var userId = body.getUser().getId();
                 var coords = Converter.convert(body.getCoordinates());
                 return new BodyInfoDto(bodyId, userId, body.getName(), coords);
               }
             }
      );
}
 
Example #4
Source Project: FlareBot   Author: FlareBot   File: GzipRequestInterceptor.java    License: MIT License 6 votes vote down vote up
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            return -1; // We don't know the compressed length in advance!
        }

        @Override
        @ParametersAreNonnullByDefault
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
 
Example #5
Source Project: pravega   Author: pravega   File: SegmentStoreConnectionManager.java    License: Apache License 2.0 6 votes vote down vote up
SegmentStoreConnectionManager(final ConnectionFactory clientCF) {
    this.cache = CacheBuilder.newBuilder()
                        .maximumSize(Config.HOST_STORE_CONTAINER_COUNT)
                        // if a host is not accessed for 5 minutes, remove it from the cache
                        .expireAfterAccess(5, TimeUnit.MINUTES)
                        .removalListener((RemovalListener<PravegaNodeUri, SegmentStoreConnectionPool>) removalNotification -> {
                            // Whenever a connection manager is evicted from the cache call shutdown on it.
                            removalNotification.getValue().shutdown();
                        })
                        .build(new CacheLoader<PravegaNodeUri, SegmentStoreConnectionPool>() {
                            @Override
                            @ParametersAreNonnullByDefault
                            public SegmentStoreConnectionPool load(PravegaNodeUri nodeUri) {
                                return new SegmentStoreConnectionPool(nodeUri, clientCF);
                            }
                        });

}
 
Example #6
Source Project: pravega   Author: pravega   File: PeriodicWatermarking.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public PeriodicWatermarking(StreamMetadataStore streamMetadataStore, BucketStore bucketStore, 
                            Function<Stream, WatermarkClient> watermarkClientSupplier, ScheduledExecutorService executor) {
    this.streamMetadataStore = streamMetadataStore;
    this.bucketStore = bucketStore;
    this.executor = executor;
    this.watermarkClientCache = CacheBuilder.newBuilder()
                                            .maximumSize(MAX_CACHE_SIZE)
                                            .expireAfterAccess(10, TimeUnit.MINUTES)
                                            .removalListener((RemovalListener<Stream, WatermarkClient>) notification -> {
                                                notification.getValue().client.close();
                                            })
                                            .build(new CacheLoader<Stream, WatermarkClient>() {
                                                @ParametersAreNonnullByDefault
                                                @Override
                                                public WatermarkClient load(final Stream stream) {
                                                    return watermarkClientSupplier.apply(stream);
                                                }
                                            });
}
 
Example #7
Source Project: protostuff-compiler   Author: protostuff   File: CompositeParseTreeListener.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create new composite listener for a collection of delegates.
 */
@SafeVarargs
public static <T extends ParseTreeListener> T create(Class<T> type, T... delegates) {
    ImmutableList<T> listeners = ImmutableList.copyOf(delegates);
    return Reflection.newProxy(type, new AbstractInvocationHandler() {

        @Override
        @ParametersAreNonnullByDefault
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
            for (T listener : listeners) {
                method.invoke(listener, args);
            }
            return null;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper("CompositeParseTreeListener")
                    .add("listeners", listeners)
                    .toString();
        }
    });

}
 
Example #8
Source Project: buck   Author: facebook   File: OfflineScribeLoggerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Unit> log(
    String category, Iterable<String> lines, Optional<Integer> bucket) {
  ListenableFuture<Unit> upload = offlineScribeLogger.log(category, lines);
  Futures.addCallback(
      upload,
      new FutureCallback<Unit>() {
        @Override
        public void onSuccess(Unit result) {}

        @Override
        @ParametersAreNonnullByDefault
        public void onFailure(Throwable t) {
          if (!blacklistCategories.contains(category)) {
            storedCategoriesWithLines.incrementAndGet();
          }
        }
      },
      MoreExecutors.directExecutor());
  return upload;
}
 
Example #9
Source Project: spring-analysis-note   Author: Vip-Augus   File: AnnotationUtilsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void isAnnotationMetaPresentForPlainType() {
	assertTrue(isAnnotationMetaPresent(Order.class, Documented.class));
	assertTrue(isAnnotationMetaPresent(NonNullApi.class, Documented.class));
	assertTrue(isAnnotationMetaPresent(NonNullApi.class, Nonnull.class));
	assertTrue(isAnnotationMetaPresent(ParametersAreNonnullByDefault.class, Nonnull.class));
}
 
Example #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: AnnotatedElementUtilsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void isAnnotatedForPlainTypes() {
	assertTrue(isAnnotated(Order.class, Documented.class));
	assertTrue(isAnnotated(NonNullApi.class, Documented.class));
	assertTrue(isAnnotated(NonNullApi.class, Nonnull.class));
	assertTrue(isAnnotated(ParametersAreNonnullByDefault.class, Nonnull.class));
}
 
Example #11
Source Project: spring-analysis-note   Author: Vip-Augus   File: AnnotatedElementUtilsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void hasAnnotationForPlainTypes() {
	assertTrue(hasAnnotation(Order.class, Documented.class));
	assertTrue(hasAnnotation(NonNullApi.class, Documented.class));
	assertTrue(hasAnnotation(NonNullApi.class, Nonnull.class));
	assertTrue(hasAnnotation(ParametersAreNonnullByDefault.class, Nonnull.class));
}
 
Example #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: AnnotatedElementUtilsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void getAllAnnotationAttributesOnJavaxType() {
	MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
			ParametersAreNonnullByDefault.class, Nonnull.class.getName());
	assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes);
	assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when"));
}
 
Example #13
Source Project: garmadon   Author: criteo   File: FsBasedCheckpointer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param fs                        The FS on which checkpoints are persisted
 * @param checkpointPathGenerator   Generate a path from a date.
 */
public FsBasedCheckpointer(FileSystem fs, BiFunction<Integer, Instant, Path> checkpointPathGenerator) {
    this.fs = fs;
    this.checkpointPathGenerator = checkpointPathGenerator;
    this.checkpointsCache = CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<Path, Boolean>() {
        @ParametersAreNonnullByDefault
        @Override
        public Boolean load(Path path) throws Exception {
            return fs.exists(path);
        }
    });
}
 
Example #14
Source Project: retro-game   Author: retro-game   File: UserBodiesCache.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public UserBodiesCache(BodyRepository bodyRepository) {
  cache = CacheBuilder.newBuilder()
      .maximumSize(MAX_SIZE)
      .build(new CacheLoader<>() {
               @Override
               @ParametersAreNonnullByDefault
               public List<Long> load(Long userId) {
                 return bodyRepository.findIdsByUserIdOrderById(userId);
               }
             }
      );
}
 
Example #15
Source Project: FlareBot   Author: FlareBot   File: DataInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
@ParametersAreNonnullByDefault
public Response intercept(Chain chain) throws IOException {
    requests.incrementAndGet();
    Metrics.httpRequestCounter.labels(sender.getName()).inc();
    return chain.proceed(chain.request());
}
 
Example #16
Source Project: FlareBot   Author: FlareBot   File: DefaultCallback.java    License: MIT License 5 votes vote down vote up
@Override
@ParametersAreNonnullByDefault
public void onResponse(Call call, Response response) {
    FlareBot.LOGGER.trace("[" + response.code() + "] - " + call.request().url().toString()
            .replaceFirst(Constants.getAPI(), ""));
    response.close();
}
 
Example #17
Source Project: FlareBot   Author: FlareBot   File: GzipRequestInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
@ParametersAreNonnullByDefault
public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") == null 
            || !originalRequest.header("Content-Encoding").equals("gzip")) {
        return chain.proceed(originalRequest);
    }

    Request compressedRequest = originalRequest.newBuilder()
            .method(originalRequest.method(), gzip(originalRequest.body()))
            .build();
    return chain.proceed(compressedRequest);
}
 
Example #18
Source Project: JuniperBot   Author: JuniperBot   File: IdentityRateLimiter.java    License: GNU General Public License v3.0 5 votes vote down vote up
public IdentityRateLimiter(double permitsPerSecond) {
    this.permitsPerSecond = permitsPerSecond;
    this.limitersCache = CacheBuilder.newBuilder()
            .concurrencyLevel(7)
            .expireAfterAccess(1, TimeUnit.HOURS)
            .build(
                    new CacheLoader<>() {
                        public RateLimiter load(@ParametersAreNonnullByDefault T identity) {
                            return RateLimiter.create(permitsPerSecond);
                        }
                    });
}
 
Example #19
Source Project: pravega   Author: pravega   File: Cache.java    License: Apache License 2.0 5 votes vote down vote up
public Cache(final Function<CacheKey, CompletableFuture<VersionedMetadata<?>>> loader) {
    cache = CacheBuilder.newBuilder()
                        .maximumSize(MAX_CACHE_SIZE)
                        .expireAfterAccess(2, TimeUnit.MINUTES)
                        .build(new CacheLoader<CacheKey, CompletableFuture<VersionedMetadata<?>>>() {
                            @ParametersAreNonnullByDefault
                            @Override
                            public CompletableFuture<VersionedMetadata<?>> load(final CacheKey key) {
                                return loader.apply(key);
                            }
                        });
}
 
Example #20
Source Project: j2objc   Author: google   File: ElementUtil.java    License: Apache License 2.0 5 votes vote down vote up
public boolean areParametersNonnullByDefault(Element element, Options options) {
  if (ElementUtil.hasAnnotation(element, ParametersAreNonnullByDefault.class)) {
    return true;
  }
  PackageElement pkg = getPackage(element);
  if (ElementUtil.hasAnnotation(pkg, ParametersAreNonnullByDefault.class)) {
    return true;
  }
  String pkgName = pkg.getQualifiedName().toString();
  return options.getPackageInfoLookup().hasParametersAreNonnullByDefault(pkgName);
}
 
Example #21
Source Project: catnip   Author: mewna   File: MultipartBodyPublisher.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@ParametersAreNonnullByDefault
public MultipartBodyPublisher addPart(final String name, final String value) {
    partsSpecificationList.add(new PartsSpecification(Type.STRING, name).value(value.getBytes(StandardCharsets.UTF_8)));
    return this;
}
 
Example #22
Source Project: catnip   Author: mewna   File: MultipartBodyPublisher.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@ParametersAreNonnullByDefault
public MultipartBodyPublisher addPart(final String name, final String filename, final byte[] value) {
    partsSpecificationList.add(new PartsSpecification(Type.FILE, name).filename(filename).value(value));
    return this;
}
 
Example #23
Source Project: configuration-as-code-plugin   Author: jenkinsci   File: DataBoundConfiguratorTest.java    License: MIT License 4 votes vote down vote up
@DataBoundConstructor
@ParametersAreNonnullByDefault
public Bar(Set<String> strings) {
    this.strings = strings;
}
 
Example #24
Source Project: FlareBot   Author: FlareBot   File: Callback.java    License: MIT License 4 votes vote down vote up
@Override
@ParametersAreNonnullByDefault
default void onFailure(Call call, IOException e) {
    MessageUtils.sendException("Error on API call! URL: " + call.request().url() + "\nBody: "
            + (call.request().body() != null), e, Constants.getErrorLogChannel());
}
 
Example #25
Source Project: FlareBot   Author: FlareBot   File: WebUtils.java    License: MIT License 4 votes vote down vote up
@Override
@ParametersAreNonnullByDefault
public void onFailure(Call call, IOException e) {
    FlareBot.LOGGER.error("Error for " + call.request().method() + " request to " + call.request().url(), e);
}
 
Example #26
Source Project: FlareBot   Author: FlareBot   File: WebUtils.java    License: MIT License 4 votes vote down vote up
@Override
@ParametersAreNonnullByDefault
public void onResponse(Call call, Response response) {
    response.close();
    FlareBot.LOGGER.debug("Response for " + call.request().method() + " request to " + call.request().url());
}
 
Example #27
Source Project: spotbugs   Author: spotbugs   File: Bug1194.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
@NoWarning("NP")
@ParametersAreNonnullByDefault
int nonnullByDefault(Object x) {
    return 17;
}
 
Example #28
Source Project: j2objc   Author: google   File: Rewriter.java    License: Apache License 2.0 4 votes vote down vote up
private void checkForNullabilityAnnotation(AbstractTypeDeclaration node) {
  if (ElementUtil.hasAnnotation(node.getTypeElement(), ParametersAreNonnullByDefault.class)) {
    unit.setHasNullabilityAnnotations();
  }
}