• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java CompletionCallback类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中javax.ws.rs.container.CompletionCallback的典型用法代码示例。如果您正苦于以下问题:Java CompletionCallback类的具体用法?Java CompletionCallback怎么用?Java CompletionCallback使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CompletionCallback类属于javax.ws.rs.container包,在下文中一共展示了CompletionCallback类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: aroundRequest

import javax.ws.rs.container.CompletionCallback; //导入依赖的package包/类
@Override
public void aroundRequest(HttpRequest req, RunnableWithException<IOException> continuation) throws IOException {
       BoundRequestContext cdiContext = CDI.current().select(BoundRequestContext.class).get();
       Map<String,Object> contextMap = new HashMap<String,Object>();
       cdiContext.associate(contextMap);
       cdiContext.activate();
       try {
       	// FIXME: associate CDI thread context on thread change, like Resteasy context?
       	continuation.run();
       }finally {
   		if(req.getAsyncContext().isSuspended()) {
   			req.getAsyncContext().getAsyncResponse().register((CompletionCallback)(t) -> {
       			cdiContext.invalidate();
       			cdiContext.deactivate();
       			cdiContext.dissociate(contextMap);
   			});
   		}else {
   			cdiContext.invalidate();
   			cdiContext.deactivate();
   			cdiContext.dissociate(contextMap);
   		}		
       }
}
 
开发者ID:FroMage,项目名称:redpipe,代码行数:24,代码来源:CdiPlugin.java


示例2: doBind

import javax.ws.rs.container.CompletionCallback; //导入依赖的package包/类
void doBind(final AsyncResponse response, final AsyncFuture<?> callback) {
    response.setTimeoutHandler(asyncResponse -> {
        log.debug("client timed out");
        callback.cancel();
    });

    response.register((CompletionCallback) throwable -> {
        log.debug("client completed");
        callback.cancel();
    });

    response.register((ConnectionCallback) disconnected -> {
        log.debug("client disconnected");
        callback.cancel();
    });
}
 
开发者ID:spotify,项目名称:heroic,代码行数:17,代码来源:CoreJavaxRestFramework.java


示例3: asyncGetWithCallback

import javax.ws.rs.container.CompletionCallback; //导入依赖的package包/类
@GET
@Path("/withCallback")
public void asyncGetWithCallback(@Suspended final AsyncResponse asyncResponse) {
	asyncResponse.register(new CompletionCallback() {
		@Override
		public void onComplete(Throwable throwable) {
			if (throwable == null) {
				numberOfSuccessResponses++;
			} else {
				numberOfFailures++;
				lastException = throwable;
			}
		}
	});

	new Thread(new Runnable() {
		@Override
		public void run() {
			String result = veryExpensiveOperation();
			asyncResponse.resume(result);
		}

		private String veryExpensiveOperation() {
			return new MagicNumber(22) + "";
		}
	}).start();
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:28,代码来源:AsyncResource.java


示例4: preProcess

import javax.ws.rs.container.CompletionCallback; //导入依赖的package包/类
@Override
public Object[] preProcess(Method method, Object[] args, MonitorContext context) {
	int i = INIT;
	AsyncResponse asyncResponse = null;
	if (cache.containsKey(method)) {
		i = cache.get(method);
		if (i == IGNORE)
			return args;
		asyncResponse = (AsyncResponse) args[i];
	} else {
		for (Annotation a : method.getDeclaredAnnotations()) {
			if (a.annotationType().isAnnotationPresent(HttpMethod.class)) {
				Parameter[] params = method.getParameters();
				for (i = 0; i < args.length; i++) {
					Object arg = args[i];
					Parameter param = params[i];
					if (arg instanceof AsyncResponse && param.isAnnotationPresent(Suspended.class)) {
						cache.putIfAbsent(method, i);
						asyncResponse = (AsyncResponse) arg;
						break;
					}
				}
				break;
			}
		}
		if (asyncResponse == null)
			cache.putIfAbsent(method, IGNORE);
	}
	if (asyncResponse != null) {
		context.setAsync(true);
		asyncResponse.register(new CompletionCallback() {

			@Override
			public void onComplete(Throwable throwable) {
				context.doReport();
			}

		});
	}
	return args;
}
 
开发者ID:NewTranx,项目名称:newtranx-utils,代码行数:42,代码来源:JaxRsAsyncHandler.java


示例5: poll

import javax.ws.rs.container.CompletionCallback; //导入依赖的package包/类
private void poll(final long timeout,
                  final String deviceId,
                  final String networkIdsCsv,
                  final String deviceTypeIdsCsv,
                  final String namesCsv,
                  final String timestamp,
                  final AsyncResponse asyncResponse) throws InterruptedException {
    final HiveAuthentication authentication = (HiveAuthentication) SecurityContextHolder.getContext().getAuthentication();

    final Date ts = Optional.ofNullable(timestamp).map(TimestampQueryParamParser::parse)
            .orElse(timestampService.getDate());
    
    final Response response = ResponseFactory.response(
            Response.Status.OK,
            Collections.emptyList(),
            JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT);

    asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response));

    Set<String> names = Optional.ofNullable(StringUtils.split(namesCsv, ','))
            .map(Arrays::asList)
            .map(list -> list.stream().collect(Collectors.toSet()))
            .orElse(null);
    Set<Long> networks = Optional.ofNullable(StringUtils.split(networkIdsCsv, ','))
            .map(Arrays::asList)
            .map(list -> list.stream()
                    .map(n -> gson.fromJson(n, Long.class))
                    .collect(Collectors.toSet())
            ).orElse(null);
    Set<Long> deviceTypes = Optional.ofNullable(StringUtils.split(deviceTypeIdsCsv, ','))
            .map(Arrays::asList)
            .map(list -> list.stream()
                    .map(dt -> gson.fromJson(dt, Long.class))
                    .collect(Collectors.toSet())
            ).orElse(null);

    BiConsumer<DeviceNotification, Long> callback = (notification, subscriptionId) -> {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(
                    Response.Status.OK,
                    Collections.singleton(notification),
                    JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT));
        }
    };

    Set<Filter> filters = filterBuilderService.getFilterList(deviceId, networks, deviceTypes, NOTIFICATION_EVENT.name(), names, authentication);

    if (!filters.isEmpty()) {
        Pair<Long, CompletableFuture<List<DeviceNotification>>> pair = notificationService
                .subscribe(filters, names, ts, callback);
        pair.getRight().thenAccept(collection -> {
            if (!collection.isEmpty() && !asyncResponse.isDone()) {
                asyncResponse.resume(ResponseFactory.response(
                        Response.Status.OK,
                        collection,
                        JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT));
            }

            if (timeout == 0) {
                asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause
                // the thread to suspend indefinitely, see AsyncResponse docs
            } else {
                asyncResponse.setTimeout(timeout, TimeUnit.SECONDS);
            }
        });

        asyncResponse.register((CompletionCallback) throwable -> notificationService.unsubscribe(Collections.singleton(pair.getLeft())));
    } else {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(response);
        }
    }
}
 
开发者ID:devicehive,项目名称:devicehive-java-server,代码行数:74,代码来源:DeviceNotificationResourceImpl.java


示例6: poll

import javax.ws.rs.container.CompletionCallback; //导入依赖的package包/类
private void poll(final long timeout,
                  final String deviceId,
                  final String networkIdsCsv,
                  final String deviceTypeIdsCsv,
                  final String namesCsv,
                  final String timestamp,
                  final boolean returnUpdated,
                  final Integer limit,
                  final AsyncResponse asyncResponse) throws InterruptedException {
    final HiveAuthentication authentication = (HiveAuthentication) SecurityContextHolder.getContext().getAuthentication();

    final Date ts = Optional.ofNullable(timestamp).map(TimestampQueryParamParser::parse)
            .orElse(timestampService.getDate());

    final Response response = ResponseFactory.response(
            OK,
            Collections.emptyList(),
            Policy.COMMAND_LISTED);

    asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response));

    Set<String> names = Optional.ofNullable(StringUtils.split(namesCsv, ','))
            .map(Arrays::asList)
            .map(list -> list.stream().collect(Collectors.toSet()))
            .orElse(null);
    Set<Long> networks = Optional.ofNullable(StringUtils.split(networkIdsCsv, ','))
            .map(Arrays::asList)
            .map(list -> list.stream()
                    .map(n -> gson.fromJson(n, Long.class))
                    .collect(Collectors.toSet())
            ).orElse(null);
    Set<Long> deviceTypes = Optional.ofNullable(StringUtils.split(deviceTypeIdsCsv, ','))
            .map(Arrays::asList)
            .map(list -> list.stream()
                    .map(dt -> gson.fromJson(dt, Long.class))
                    .collect(Collectors.toSet())
            ).orElse(null);

    BiConsumer<DeviceCommand, Long> callback = (command, subscriptionId) -> {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(
                    OK,
                    Collections.singleton(command),
                    Policy.COMMAND_LISTED));
        }
    };

    Set<Filter> filters = filterBuilderService.getFilterList(deviceId, networks, deviceTypes, COMMAND_EVENT.name(), names, authentication);

    if (!filters.isEmpty()) {
        Pair<Long, CompletableFuture<List<DeviceCommand>>> pair = commandService
                .sendSubscribeRequest(filters, names, ts, returnUpdated, limit, callback);
        pair.getRight().thenAccept(collection -> {
            if (!collection.isEmpty() && !asyncResponse.isDone()) {
                asyncResponse.resume(ResponseFactory.response(
                        OK,
                        collection,
                        Policy.COMMAND_LISTED));
            }

            if (timeout == 0) {
                asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause
                // the thread to suspend indefinitely, see AsyncResponse docs
            } else {
                asyncResponse.setTimeout(timeout, TimeUnit.SECONDS);
            }
        });

        asyncResponse.register((CompletionCallback) throwable -> commandService.sendUnsubscribeRequest(Collections.singleton(pair.getLeft())));
    } else {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(response);
        }
    }

}
 
开发者ID:devicehive,项目名称:devicehive-java-server,代码行数:77,代码来源:DeviceCommandResourceImpl.java


示例7: waitForCommand

import javax.ws.rs.container.CompletionCallback; //导入依赖的package包/类
private void waitForCommand(DeviceVO device, final String commandId, final long timeout,
        DeviceCommand command, final AsyncResponse asyncResponse) {
    String deviceId = device.getDeviceId();
    

    if (!command.getDeviceId().equals(device.getDeviceId())) {
        logger.warn("DeviceCommand wait request failed. BAD REQUEST: Command with id = {} was not sent for device with id = {}",
                commandId, deviceId);
        asyncResponse.resume(ResponseFactory.response(BAD_REQUEST));
        return;
    }

    BiConsumer<DeviceCommand, Long> callback = (com, subscriptionId) -> {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(
                    OK,
                    com,
                    COMMAND_TO_DEVICE));
        }
    };

    if (!command.getIsUpdated()) {
        CompletableFuture<Pair<Long, DeviceCommand>> future = commandService
                .sendSubscribeToUpdateRequest(Long.valueOf(commandId), device, callback);
        future.thenAccept(pair -> {
            final DeviceCommand deviceCommand = pair.getRight();
            if (!asyncResponse.isDone() && deviceCommand.getIsUpdated()) {
                asyncResponse.resume(ResponseFactory.response(
                        OK,
                        deviceCommand,
                        COMMAND_TO_DEVICE));
            }

            if (timeout == 0) {
                asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause
                // the thread to suspend indefinitely, see AsyncResponse docs
            } else {
                asyncResponse.setTimeout(timeout, TimeUnit.SECONDS);
            }
        });
        asyncResponse.register((CompletionCallback) throwable -> {
            try {
                commandService.sendUnsubscribeRequest(Collections.singleton(future.get().getLeft()));
            } catch (InterruptedException | ExecutionException e) {
                if (!asyncResponse.isDone()) {
                    asyncResponse.resume(ResponseFactory.response(INTERNAL_SERVER_ERROR));
                }
            }
        });
    } else {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(OK, command, COMMAND_TO_DEVICE));
        }
    }
}
 
开发者ID:devicehive,项目名称:devicehive-java-server,代码行数:56,代码来源:DeviceCommandResourceImpl.java



注:本文中的javax.ws.rs.container.CompletionCallback类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java ConnectionStateCallback类代码示例发布时间:2022-05-23
下一篇:
Java GMLReaderTestSuite类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap