下面列出了怎么用javax.annotation.ParametersAreNonnullByDefault的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
});
}
/**
* 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;
}
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);
}
}
);
}
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();
}
};
}
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);
}
});
}
@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);
}
});
}
/**
* 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();
}
});
}
@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;
}
@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));
}
@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));
}
@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));
}
@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"));
}
/**
* @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);
}
});
}
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);
}
}
);
}
@Override
@ParametersAreNonnullByDefault
public Response intercept(Chain chain) throws IOException {
requests.incrementAndGet();
Metrics.httpRequestCounter.labels(sender.getName()).inc();
return chain.proceed(chain.request());
}
@Override
@ParametersAreNonnullByDefault
public void onResponse(Call call, Response response) {
FlareBot.LOGGER.trace("[" + response.code() + "] - " + call.request().url().toString()
.replaceFirst(Constants.getAPI(), ""));
response.close();
}
@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);
}
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);
}
});
}
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);
}
});
}
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);
}
@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;
}
@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;
}
@DataBoundConstructor
@ParametersAreNonnullByDefault
public Bar(Set<String> strings) {
this.strings = strings;
}
@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());
}
@Override
@ParametersAreNonnullByDefault
public void onFailure(Call call, IOException e) {
FlareBot.LOGGER.error("Error for " + call.request().method() + " request to " + call.request().url(), e);
}
@Override
@ParametersAreNonnullByDefault
public void onResponse(Call call, Response response) {
response.close();
FlareBot.LOGGER.debug("Response for " + call.request().method() + " request to " + call.request().url());
}
@NoWarning("NP")
@ParametersAreNonnullByDefault
int nonnullByDefault(Object x) {
return 17;
}
private void checkForNullabilityAnnotation(AbstractTypeDeclaration node) {
if (ElementUtil.hasAnnotation(node.getTypeElement(), ParametersAreNonnullByDefault.class)) {
unit.setHasNullabilityAnnotations();
}
}