Axon framework version : 4.4.7
Axon server : 4.5.7
#Component
#ProcessingGroup("product-group")
public class ProductEventHandler {
private final ProductRepository productsRepository;
private final QueryUpdateEmitter queryUpdateEmitter;
public ProductEventHandler(ProductRepository productsRepository, QueryUpdateEmitter queryUpdateEmitter) {
this.productsRepository = productsRepository;
this.queryUpdateEmitter = queryUpdateEmitter;
}
#EventHandler
public void handle(ProductCreatedEvent event) throws Exception {
ProductEntity entity = new ProductEntity();
BeanUtils.copyProperties(event, entity);
try {
productsRepository.save(entity);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
#EventHandler
public void handle(ProductUpdatedEvent event) {
ProductEntity entity = new ProductEntity();
BeanUtils.copyProperties(event, entity);
try {
productsRepository.save(entity);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
ProductResponse productResponse = new ProductResponse();
productResponse.setProductId(event.getProductId());
productResponse.setStatus("Updated");
//queryUpdateEmitter.emit(FetchProductQuery.class, query -> true, productResponse);
queryUpdateEmitter.emit(FetchProductQuery.class,
query -> query.getProductId().equals(event.getProductId()), productResponse);
}
}
#RestController
#RequestMapping("/product")
public class ProductController {
private final CommandGateway commandGateway;
private final QueryGateway queryGateway;
private SubscriptionQueryResult<ProductResponse, ProductResponse> queryResult;
#Autowired
public ProductController(CommandGateway commandGateway, QueryGateway queryGateway) {
this.queryGateway = queryGateway;
this.commandGateway = commandGateway;
}
#PutMapping("/{id}")
public ProductResponse updateProduct(#PathVariable("id") String id,
#Valid #RequestBody ProductRequest request) {
UpdateProductCommand updateProductCommand = UpdateProductCommand.builder().productId(id)
.price(request.getPrice()).quantity(request.getQuantity()).title(request.getTitle()).build();
commandGateway.sendAndWait(updateProductCommand);
queryResult = queryGateway.subscriptionQuery(
FetchProductQuery.builder().productId(id), ResponseTypes.instanceOf(ProductResponse.class),
ResponseTypes.instanceOf(ProductResponse.class));
try {
// return queryResult.updates().blockFirst();
return queryResult.initialResult().block();
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
queryResult.close();
}
}
}
#Component
public class ProductsQueryHandler {
private final ProductRepository productsRepository;
public ProductsQueryHandler(ProductRepository productsRepository) {
this.productsRepository = productsRepository;
}
#QueryHandler
public ProductResponse handler(FetchProductQuery query) {
ProductEntity productEntity = productsRepository.findByProductId(query.getProductId());
ProductResponse productResponse = new ProductResponse();
BeanUtils.copyProperties(productEntity, productResponse);
return productResponse;
}
}
I could not see any subscription queries in AXON dashboard, getting below error. Can you please help me for the cause and solution???
2021-10-21 18:09:42.468[0;39m [32m INFO[0;39m [35m19608[0;39m [2m---[0;39m [2m[nio-8888-exec-2][0;39m [36mo.a.m.interceptors.LoggingInterceptor [0;39m [2m:[0;39m Dispatched messages: [FetchProductQueryBuilder]
org.axonframework.axonserver.connector.AxonServerException: CANCELLED: AXONIQ-5000
at org.axonframework.axonserver.connector.ErrorCode.lambda$static$24(ErrorCode.java:145)
at org.axonframework.axonserver.connector.ErrorCode.convert(ErrorCode.java:182)
at org.axonframework.axonserver.connector.ErrorCode.convert(ErrorCode.java:213)
at org.axonframework.axonserver.connector.ErrorCode.convert(ErrorCode.java:202)
at org.axonframework.axonserver.connector.event.util.GrpcExceptionParser.parse(GrpcExceptionParser.java:57)
at reactor.core.publisher.Mono.lambda$onErrorMap$31(Mono.java:3437)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94)
at reactor.core.publisher.MonoCompletionStage.lambda$subscribe$0(MonoCompletionStage.java:79)
at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
at java.base/java.util.concurrent.CompletableFuture.uniWhenCompleteStage(CompletableFuture.java:883)
at java.base/java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:2321)
at java.base/java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:143)
at reactor.core.publisher.MonoCompletionStage.subscribe(MonoCompletionStage.java:57)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
at reactor.core.publisher.Mono.subscribe(Mono.java:4099)
at reactor.core.publisher.Mono.block(Mono.java:1702)
at com.demo.product.controller.ProductController.updateProduct(ProductController.java:75)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:920)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:831)
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)
at reactor.core.publisher.Mono.block(Mono.java:1703)
... 51 more
[2m2021-10-21 18:09:42.493[0;39m [33m WARN[0;39m [35m19608[0;39m [2m---[0;39m [2m[nio-8888-exec-2][0;39m [36m.m.m.a.ExceptionHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.axonframework.axonserver.connector.AxonServerException: CANCELLED: AXONIQ-5
000]
The error code AXONIQ-5000 indicates that no query handler for the given query request type could be found.
I don't have the complete code, of course, but checking the code it looks like the first parameter of the query request is a builder (the result of FetchProductQuery.builder().productId(id)) and not a FetchProductQuery instance.
Related
I'm using spring-kafka 2.3.8 and I'm trying to log the recovered records and commit the offsets using RetryingBatchErrorHandler. How would you commit the offset in the recoverer?
public class Customizer implements ContainerCustomizer{
private static ConsumerRecordRecoverer createConsumerRecordRecoverer() {
return (consumerRecord, e) -> {
log.info("Number of attempts exhausted. parition: " consumerRecord.partition() + ", offset: " + consumerRecord.offset());
# need to commit the offset
};
}
#Override
public void configure(AbstractMessageListenerContainer container) {
container.setBatchErrorHandler(new RetryingBatchErrorHandler(new FixedBackOff(5000L, 3L), createConsumerRecordRecoverer()));
}
The container will automatically commit the offsets if the error handler "handles" the exception, unless you set the ackAfterHandle property to false (it is true by default).
EDIT
This works as expected for me:
#SpringBootApplication
public class So69534923Application {
private static final Logger log = LoggerFactory.getLogger(So69534923Application.class);
public static void main(String[] args) {
SpringApplication.run(So69534923Application.class, args);
}
#KafkaListener(id = "so69534923", topics = "so69534923")
void listen(List<String> in) {
System.out.println(in);
throw new RuntimeException("test");
}
#Bean
RetryingBatchErrorHandler eh() {
return new RetryingBatchErrorHandler(new FixedBackOff(1000L, 2), (rec, ex) -> {
this.log.info("Retries exchausted for " + ListenerUtils.recordToString(rec, true));
});
}
#Bean
ApplicationRunner runner(ConcurrentKafkaListenerContainerFactory<?, ?> factory,
KafkaTemplate<String, String> template) {
factory.getContainerProperties().setCommitLogLevel(Level.INFO);
return args -> {
template.send("so69534923", "foo");
template.send("so69534923", "bar");
};
}
}
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.listener.type=batch
so69534923: partitions assigned: [so69534923-0]
[foo, bar]
[foo, bar]
[foo, bar]
Retries exchausted for so69534923-0#2
Retries exchausted for so69534923-0#3
Committing: {so69534923-0=OffsetAndMetadata{offset=4, leaderEpoch=null, metadata=''}}
The log was from the second run.
EDIT2
It does not work with 2.3.x; you should upgrade to a supported version.
https://spring.io/projects/spring-kafka#learn
i am coding a http server with netty-all-4.1.0.Final.jar,while the server listening,sometimes while happen "connection reset by peer",the detail like below:
Connection reset by peer
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1098)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:350)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:112)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:544)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:485)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:399)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:371)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:742)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:145)
at java.lang.Thread.run(Thread.java:748)
this is my main server code:
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
//将同一个http请求的内容组装到一起,调用一次handler
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new HttpServerHandler());
}
});
int port = ConfUtils.port;
ChannelFuture f = b.bind(port).sync();
logger.info("start lisner-------port is {}",port);
f.channel().closeFuture().sync();
} catch(Exception e){
logger.error(e.getMessage(),e);
}
finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
this is my handler class:
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if(msg instanceof FullHttpRequest){
try{
logger.info("accept http msg!");
FullHttpRequest fullHttpRequest = (FullHttpRequest)msg;
ProcessMsg.dealMsg(fullHttpRequest);
logger.info("full header is {}",fullHttpRequest);
String responseHtml = "response from server!";
byte[] responseBytes = responseHtml.getBytes("UTF-8");
int contentLength = responseBytes.length;
FullHttpResponse response = new
DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/html; charset=utf-8");
response.headers().set("Content-Length", Integer.toString(contentLength));
Thread.sleep(1000 * 5);
ctx.writeAndFlush(response);
ctx.flush();
logger.info("response from server!");
}catch(Exception e){
logger.error(e.getMessage(),e);
}
}
else{
logger.info("this is not http request");
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LoggerFactory.getLogger("excplog").error(cause.getMessage(),cause);
ctx.close();
}
}
it's not always happend,sometimes happen and most times not,and we can't find any question about request
Showing Null pointer exception** in this code.
** yrWebService.getUserInfo()**
I have tried most of the things but I can't figure it out.
Anyone please help to fix this issue.
The getUserInfo() throwing null pointer exception.
someone help me to solve this. I pasted the interface down there.
public void fetchUserProfile() {
YRWebService.getUserInfo()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<YRUserResponse>() {
#Override
public void onError(Throwable e) {
Toast.makeText(YarraApplication.this, "Error on server :" +e, Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete() {
}
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(YRUserResponse yrUserResponse) {
//progressDialog.dismiss();
if (yrUserResponse != null) {
if (yrUserResponse.getUser() != null) {
YRPreferenceManager.setString(PreferenceKeys.USER_PROFILE_RESPONSE,
new Gson().toJson(yrUserResponse));
YRUser yrUser = yrUserResponse.getUser();
YarraApplication.userId = yrUserResponse.getUser().getUser_id();
YarraApplication.access = yrUserResponse.getUser().getGoogle_access_token();
YarraApplication.email = yrUser.getEmail();
YarraApplication.fName = yrUser.getFirst_name();
YarraApplication.lName = yrUser.getLast_name();
YarraApplication.mobile = yrUser.getTelephone();
}else {
// YRUtils.showUnknownErrorDialog(YarraApplication.this);
}
}// else {
// YRUtils.showUnknownErrorDialog(UserProfileActivity.this);
// }
}
});
}
**Interface :::: **
The interface we are using here is this
public interface YRWebService {
#GET("/users")
Observable<YRUserResponse> getUserInfo();
}
public class YRUserResponse {
List<YRError> errors;
YRUser user;
public YRUser getUser() {
return user;
}
public void setUser(YRUser user) {
this.user = user;
}
**retrofit.RetrofitError**:
```
2019-05-06 15:26:49.506 30475-30475/com.rever.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rever.app, PID: 30475
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rever.app/com.rever.app.UserProfileActivity}: retrofit.RetrofitError
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: retrofit.RetrofitError
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:400)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
at java.lang.reflect.Proxy.invoke(Proxy.java:913)
at $Proxy0.getUserInfo(Unknown Source)
at com.rever.app.UserProfileActivity.fetchUserProfile(UserProfileActivity.java:220)
at com.rever.app.UserProfileActivity.onCreate(UserProfileActivity.java:132)
at android.app.Activity.performCreate(Activity.java:7084)
at android.app.Activity.performCreate(Activity.java:7075)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.squareup.okhttp.internal.Dns$1.getAllByName(Dns.java:29)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:231)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:317)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:241)
at com.squareup.okhttp.Call.getResponse(Call.java:198)
at com.squareup.okhttp.Call.execute(Call.java:80)
at retrofit.client.OkClient.execute(OkClient.java:53)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
at java.lang.reflect.Proxy.invoke(Proxy.java:913)
at $Proxy0.getUserInfo(Unknown Source)
at com.rever.app.UserProfileActivity.fetchUserProfile(UserProfileActivity.java:220)
at com.rever.app.UserProfileActivity.onCreate(UserProfileActivity.java:132)
at android.app.Activity.performCreate(Activity.java:7084)
at android.app.Activity.performCreate(Activity.java:7075)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
```
Is it possible to fire CDI events from within a interceptor ? (Using Jboss 7.1.1)
For example, if I have an interceptor PerformanceLogInterceptor
#Interceptors({PerformanceLogInterceptor.class})
public class ProcessHandler extends HandlerBase {
.
.
.
Could it fire an event as such:
public class PerformanceLogInterceptor {
private Logger LOG = LoggerFactory.getLogger("PerformanceLog");
#EJB
PerformanceMonitor performanceMonitor;
#Inject
Event<ExceptionEvent> exceptionEvent;
#AroundInvoke
#AroundTimeout
public Object performanceLog( InvocationContext invocationContext ) throws Exception {
String methodName = invocationContext.getMethod().toString();
long start = System.currentTimeMillis();
try {
return invocationContext.proceed();
} catch( Exception e ) {
LOG.warn( "During invocation of: {} exception occured: {}", methodName, Throwables.getRootCause(e).getMessage() );
performanceMonitor.addException( methodName, e );
Exception toSend;
if(e instanceof EfsobExceptionInformation ){
toSend = e;
} else {
LOG.debug("Wrapping exception");
EfsobExceptionWrapper wrapped = new EfsobExceptionWrapper(e);
toSend = wrapped;
}
if(exceptionEvent != null) {
LOG.debug("sending exceptionEvent");
exceptionEvent.fire(new ExceptionEventBuilder()
.setExceptionName(toSend)
.setEfsobExceptionType(toSend)
.setId(toSend)
.setStacktrace(toSend)
.build()
);
} else {
LOG.debug("exceptionEvent was null");
}
LOG.debug("rethrowing");
throw toSend;
} finally {
long total = System.currentTimeMillis() - start;
performanceMonitor.addPerformanceMetrics(methodName, total);
}
}
}
Note: exceptionEvent is null at runtime in the Above.
I moved it into an Async block of the PerformanceMonitor bean referenced above.... and then it works (WAT?)
#Singleton
#ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class PerformanceMonitor {
#Inject
Event<ExceptionEvent> exceptionEvent;
private Logger LOG = LoggerFactory.getLogger("PerformanceMonitor");
#Asynchronous
public void addException(String methodName, Exception e) {
if(exceptionEvent != null) {
LOG.debug("sending exceptionEvent");
exceptionEvent.fire(new ExceptionEventBuilder()
.setExceptionName(e)
.setEfsobExceptionType(e)
.setId(e)
.setStacktrace(e)
.build()
);
} else {
LOG.debug("exceptionEvent was null");
}
}
}
I am developing a JavaFX application used to sign pdf using eToken Pro. The sign methods run perfectly in a normal Java project. While when run in the JavaFX application, it keeps encountering exceptions like this:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NoClassDefFoundError: sun/security/pkcs11/SunPKCS11
at javafxapplication3.JavaFXApplication3.start(JavaFXApplication3.java:21)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
... 1 more
Caused by: java.lang.ClassNotFoundException: sun.security.pkcs11.SunPKCS11
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 12 more
Java Result: 1
the codes I used to sign pdf are as follows:
#Override
public void start(Stage primaryStage) {
Signer signer = new Signer(new File("C:/Users/Adam/Desktop/pdf/hello.pdf"));
signer.signWithToken(true);
}
the codes of class Signer are as follows:
public class Signer {
// define the file to be signed
private final File file;
private static String smartcardDllPath;
private static int level;
private static String reason;
private static String src;
private static String dest;
private static String location;
private static Collection<CrlClient> crlList;
private static OcspClient ocspClient;
private static TSAClient tsaClient;
private static final String DLL = "C:/Windows/System32/eTPKCS11.dll";
public Signer(File theFile) {
location = "HK SAR";
smartcardDllPath = null;
file = theFile;
}
public void signWithToken(boolean certified) {
try {
String config = "name=eToken\nlibrary=" + DLL + "\nslotListIndex=" + getSlotsWithTokens(DLL)[0];
ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
Provider providerPKCS11 = new SunPKCS11(bais);
Security.addProvider(providerPKCS11);
configureParameters(certified);
// create PdfSignatureAppearance
PdfSignatureAppearance appearance = getPdfSigAppearance();
// configure the keystore, alias, private key and certificate chain
char[] pin = "love4Sakura".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, pin);
String alias = (String) ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, null);
Certificate[] chain = ks.getCertificateChain(alias);
printChainInfo(chain);
// configure the CRL, OCSP and TSA
configCrlOcspTsa(chain);
// create the signature
ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "SunPKCS11-eToken");
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, digest, pks, chain, crlList, ocspClient,
tsaClient, 0, MakeSignature.CryptoStandard.CMS);
} catch (IOException | DocumentException | GeneralSecurityException ex) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static long[] getSlotsWithTokens(String libraryPath) {
CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();
String functionList = "C_GetFunctionList";
initArgs.flags = 0;
PKCS11 tmpPKCS11 = null;
long[] slotList = null;
try {
try {
tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, false);
System.out.println(tmpPKCS11.toString());
} catch (IOException ex) {
try {
throw ex;
} catch (IOException ex1) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex1);
}
}
} catch (PKCS11Exception e) {
try {
initArgs = null;
tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, true);
} catch (IOException | PKCS11Exception ex) {
}
}
try {
slotList = tmpPKCS11.C_GetSlotList(true);
for (long slot : slotList) {
CK_TOKEN_INFO tokenInfo = tmpPKCS11.C_GetTokenInfo(slot);
System.out.println("slot: " + slot + "\nmanufacturerID: "
+ String.valueOf(tokenInfo.manufacturerID) + "\nmodel: "
+ String.valueOf(tokenInfo.model));
}
} catch (PKCS11Exception ex) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex);
}
return slotList;
}
Before you guys answer: I want to emphasize that I reference the Signer class in a normal Java Project perfectly. So I donn't think it's a 32-bit or 64-bit problem. Plus, I am using the 32-bit JDK 1.7
This issue can be because unsupported version of java.Do one thing download particular jar file for that and include it on your project it'll work for you.
You can download the jar from this link -
http://www.docjar.com/jar/sunpkcs11.jar
I was also getting the same error -
java.lang.ClassNotFoundException: sun.security.pkcs11.SunPKCS11
Adding the following dependency in pom.xml helped me -
<dependency>
<groupId>sunpkcs11</groupId>
<artifactId>sunpkcs11</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>/Library/Java/JavaVirtualMachines/jdk1.8.0_341.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar</systemPath>
</dependency>
In <systemPath>...</systemPath>, give the appropriate path of sunpkcs11.jar from your system.