NPE during concurrent thread access of a single tess4j instance - tesseract

I am working with Tesseract 3.0.2 and using 1.4.1 tess4j..this is not working in a thread-safe manner, I get a NPE. I am using Grizzly/Jesery/Spring.
#Service("textExtractorService")
public class TextExtractorServiceImpl implements TextExtractorService {
Logger LOGGER = Logger.getLogger(TextExtractorServiceImpl.class);
private final Tesseract instance = Tesseract.getInstance(); // JNA Interface
...
..
}
...
...
public ExtractedInfo extract(BufferedImage bufferedImage)
throws IOException {
ExtractedInfo extractedInfo = new ExtractedInfo();
try {
BufferedImage preProcessed = preProcess(bufferedImage);
String result = null;
//the below gives me the NPE, when multiple threads calls this method.
result = instance.doOCR(preProcessed);
String[] r = StringUtils.split(result, "\n");
extractedInfo.setRawText(r);
} catch (TesseractException e) {
throw new IOException(e);
}
return extractedInfo;
}
...
...
Full stack Trace:
SEVERE: service exception:
javax.servlet.ServletException: java.lang.Error: Invalid memory access
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.doFilter(ServletAdapter.java:1059)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.invokeFilterChain(ServletAdapter.java:999)
at com.sun.grizzly.http.servlet.ServletAdapter.doService(ServletAdapter.java:434)
at com.sun.grizzly.http.servlet.ServletAdapter.service(ServletAdapter.java:379)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.grizzly.tcp.http11.GrizzlyAdapterChain.service(GrizzlyAdapterChain.java:196)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:850)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:747)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1032)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:231)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeVoid(Native Method)
at com.sun.jna.Function.invoke(Function.java:367)
at com.sun.jna.Function.invoke(Function.java:315)
at com.sun.jna.Library$Handler.invoke(Library.java:212)
at com.sun.proxy.$Proxy55.TessBaseAPIDelete(Unknown Source)
at net.sourceforge.tess4j.Tesseract.dispose(Tesseract.java:346)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:242)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:200)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:184)
at com.vanitysoft.thirdeye.service.impl.TextExtractorServiceImpl.extract(TextExtractorServiceImpl.java:69)
at com.vanitysoft.thirdeye.web.TextExtractorResource.extract(TextExtractorResource.java:49)

I'm not sure if this is the exact same issue, but I found this answer on a similar question.
https://stackoverflow.com/a/24806132/2596497
In short, it appears that the underlying engine in Tesseract does not support multi-threading.

Related

JAX-RS with Kotlin MessageBodyWriter not found

I've implemented a JAX-RS resource (a) with Kotlin and (b) with Java. While the Java flavor works as expected, the Kotlin flavor fails with a
MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<? extends ....Entry>.|#] exception.
This is my resource
#Path("demokotlin")
class DemoKotlinResource {
#GET
#Path("responseGenericEntityWithArrayList")
fun arrayList(): Response {
val list = arrayListOf(Entry("responseGenericEntityWithArrayList"))
val entity = object : GenericEntity<List<Entry>>(list) {}
return Response
.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build()
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
open class Entry(val fieldName: String)
The integration test is essentially
private val client = ClientBuilder.newClient()
private val target = client.target("http://localhost:8080/xyz/resources/demokotlin")
#Test
fun responseGenericEntityWithArrayList() {
val response = target.path("responseGenericEntityWithArrayList").request(MediaType.APPLICATION_JSON).get()
assertThat("no ok status", response.status, equalTo(200))
val entity = response.readEntity(JsonArray::class.java)
assertThat(entity.getJsonObject(0).getString("fieldName"), equalTo("responseGenericEntityWithArrayList"))
assertThat(entity.toString(), equalTo("[{\"fieldName\":\"responseGenericEntityWithArrayList\"}]"))
}
The equivalent code in Java works fine while the shown code in Kotlin throws MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<? extends ....Entry>.|#].
I am using Payara 4.1.2.172. Digging through some JAX-RS classes I found that the Java Code leads to
genericType=java.util.List<....Entry>
(without the ? extends) while the generic type info with Kotlin is
genericType=java.util.List<? extends ....Entry>
could that be the cause? If so, how can I fix this?
edit 2017-07-25 Here is the stack trace
#|2017-07-25T12:33:16.932+0000|INFO|Payara 4.1||_ThreadID=32;_ThreadName=http-thread-pool::http-listener-1(1);_TimeMillis=1500985996932;_LevelValue=800;|
javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:90)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1606)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:338)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:654)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:593)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<? extends com.github.reproducer.boundary.Entry>.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
... 52 more
|#]
edit #2: working Java Code - should be quite similar to Kotlin variant
#Path("demojava")
public class DemoJavaResource {
#GET
#Path("responseGenericEntityWithArrayList")
public Response arrayList() {
final List<JEntry> list = new ArrayList<>();
list.add(new JEntry("responseGenericEntityWithArrayList"));
final GenericEntity<List<JEntry>> entity = new GenericEntity<List<JEntry>>(list) {};
return Response
.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build();
}
}
and JEntry
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
class JEntry {
private String fieldName;
JEntry() { this(""); }
JEntry(final String responseGenericEntityWithArrayList) {
fieldName = responseGenericEntityWithArrayList;
}
public String getFieldName() { return fieldName; }
}
Because JAX-RS cannot encode ArrayList to JSON Array.
MessageBodyWriter is a handler to convert Java data type to output format, e.g. XML, JSON. JAX-RS has built-in MessageBodyWriter for major data type (include JAXB), however those does not include for ArrayList. Thus you need to create a custom MessageBodyWriter to accept ArrayList and encode to JSON.
But in this case, any custom MessageBodyWriter is not need. Instead of, you need to re-create Entry class. I'm sorry that I can't write Kotlin sample, but if it write using Java, it's following;
#Path("demokotlin")
public class DemoKotlinResource {
#GET
#Path("responseGenericEntityWithArrayList")
public Response arrayList() {
Entry entity = new Entry();
entity.fieldName.add("responseGenericEntityWithArrayList");
return Response
.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build();
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Entry {
public List<String> fieldName = new ArrayList<>();
}
And it translate to Kotlin, then it's maybe completed.

JBoss 6 AS with AOP throws StackOverflowError

I am using JBoss 6 AS and trying to add via AOP an interceptor to the classes in some package from a deployed application. This is the scenario:
I have an app.jar that contains the classes to which I want to add advices. This JAR also has some EJBs (ejb-jar.xml, jboss.xml).
I created my on JBoss interceptor like this :
package util;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aop.joinpoint.MethodInvocation;
public class MyInterceptor implements org.jboss.aop.advice.Interceptor {
#Override
public Object invoke(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.invokeNext();
} finally {
long endTime = System.currentTimeMillis() - startTime;
System.out.println("MyInterceptor : " + endTime);
if (invocation instanceof MethodInvocation) {
MethodInvocation mi = (MethodInvocation) invocation;
String clazz = "";
String method = "";
try {
clazz = mi.getTargetObject().getClass().toString();
method = mi.getMethod().getName();
} catch (Throwable e) {
System.out.println("Error when trying to get target info");
}
System.out.println("MyInterceptor : " + endTime);
}
}
}
#Override
public String getName() {
return "MyInterceptor";
}
}
I created a jboss-aop.xml file that contains:
<?xml version="1.0" encoding="UTF-8"?>
<aop xmlns="urn:jboss:aop-beans:1.0">
<interceptor name="MyInterceptor" class="util.MyInterceptor"/>
<bind pointcut="execution(* my.app.*->*(..))">
<interceptor-ref name="MyInterceptor"/>
</bind>
</aop>
I have set enableLoadTimeWeaving (bootstrap/aop.xml)
I have pluggable-instrumentor.jar in the right place (JBOSS/bin)
I have started the server with the option -javaagent:pluggable-instrumentor.jar
I have created a JAR file interceptor.jar where I put MyInterceptor.class and in its META-INF I've placed the jboss-aop.xml file
Now, that being said, the problem is that when I run my application and some method from any class from my.app package is being called the interceptor seems to intercept the call but it throws a nasty StackOverflowError. This is a part of my error stack:
java.lang.StackOverflowError
at org.jboss.resteasy.core.SynchronousDispatcher.unwrapException(SynchronousDispatcher.java:345) [:6.1.0.Final]
at org.jboss.resteasy.core.SynchronousDispatcher.handleApplicationException(SynchronousDispatcher.java:321) [:6.1.0.Final]
at org.jboss.resteasy.core.SynchronousDispatcher.handleException(SynchronousDispatcher.java:214) [:6.1.0.Final]
at org.jboss.resteasy.core.SynchronousDispatcher.handleInvokerException(SynchronousDispatcher.java:190) [:6.1.0.Final]
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:534) [:6.1.0.Final]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:496) [:6.1.0.Final]
at org.jboss.resteasy.core.SynchronousDispatcher.invokePropagateNotFound(SynchronousDispatcher.java:155) [:6.1.0.Final]
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:212) [:6.1.0.Final]
at org.jboss.resteasy.plugins.server.servlet.FilterDispatcher.doFilter(FilterDispatcher.java:59) [:6.1.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:274) [:6.1.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242) [:6.1.0.Final]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [:6.1.0.Final]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [:6.1.0.Final]
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:181) [:6.1.0.Final]
at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.event(CatalinaContext.java:285) [:1.1.0.Final]
at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.invoke(CatalinaContext.java:261) [:1.1.0.Final]
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:88) [:6.1.0.Final]
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:100) [:6.1.0.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159) [:6.1.0.Final]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [:6.1.0.Final]
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) [:6.1.0.Final]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [:6.1.0.Final]
at org.jboss.web.tomcat.service.request.ActiveRequestResponseCacheValve.invoke(ActiveRequestResponseCacheValve.java:53) [:6.1.0.Final]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [:6.1.0.Final]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [:6.1.0.Final]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:654) [:6.1.0.Final]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:951) [:6.1.0.Final]
at java.lang.Thread.run(Thread.java:745) [:1.7.0_79]
Caused by: java.lang.StackOverflowError
at my.app.JoinPoint_invoke_N_5164114663869737738_3.invokeJoinpoint(JoinPoint_invoke_N_5164114663869737738_3.java) [:]
at my.app.MyInterceptor$MyInterceptorAdvisor.invoke_N_5164114663869737738(MyInterceptor$MyInterceptorAdvisor.java) [:]
at my.app.MyInterceptor.invoke(MyInterceptor.java) [:]
at my.app.JoinPoint_invoke_N_5164114663869737738_3.invokeNext(JoinPoint_invoke_N_5164114663869737738_3.java) [:]
at my.app.JoinPoint_invoke_N_5164114663869737738_3.invokeJoinpoint(JoinPoint_invoke_N_5164114663869737738_3.java) [:]
at my.app.MyInterceptor$MyInterceptorAdvisor.invoke_N_5164114663869737738(MyInterceptor$MyInterceptorAdvisor.java) [:]
at my.app.MyInterceptor.invoke(MyInterceptor.java) [:]
Basically what happens is that these four lines are being thrown until StackOverflowError gets raised:
at my.app.JoinPoint_invoke_N_5164114663869737738_3.invokeNext(JoinPoint_invoke_N_5164114663869737738_3.java) [:]
at my.app.JoinPoint_invoke_N_5164114663869737738_3.invokeJoinpoint(JoinPoint_invoke_N_5164114663869737738_3.java) [:]
at my.app.MyInterceptor$MyInterceptorAdvisor.invoke_N_5164114663869737738(MyInterceptor$MyInterceptorAdvisor.java) [:]
at my.app.MyInterceptor.invoke(MyInterceptor.java) [:]
If anyone had some similar problem any help would be appeciated!
Well i found the problem ... i put the interceptor on the same package my.app and not in util ... so eventually it was calling itself endlessly until the stack was full . So ... my bad

How to use OAuth2RestTemplate + Spring 4?

I'm trying to understand how to use a OAuth2RestTemplate object to consume my OAuth2 secured REST service (which is running under a different project and let's assume also on a different server etc...)
f.e. my rest service is:
https://localhost:8443/rest/api/user
-> Accessing this URL generates an error as I am not authenticated
To request a token I would go to:
https://localhost:8443/rest/oauth/token?grant_type=password&client_id=test&client_secret=test&username=USERNAME&password=PASSWORD
After I receive the token I can then connect to the REST API by using the following URL (example token inserted)
https://localhost:8443/rest/api/user?access_token=06
I currently tried something with the following objects:
#EnableOAuth2Client
#Configuration
class MyConfig {
#Value("${oauth.resource:https://localhost:8443}")
private String baseUrl;
#Value("${oauth.authorize:https://localhost:8443/rest/oauth/authorize}")
private String authorizeUrl;
#Value("${oauth.token:https://localhost:8443/rest/oauth/token}")
private String tokenUrl;
#Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("test");
resource.setClientSecret("test");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("test");
resource.setPassword("test");
return resource;
}
#Bean
public OAuth2RestOperations restTemplate() {
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
AccessTokenRequest atr = new DefaultAccessTokenRequest();
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
provider.setRequestFactory(requestFactory);
restTemplate.setAccessTokenProvider(provider);
return restTemplate;
}
}
I am tried to get token in controller like below.
#Controller
public class TestController {
#Autowired
private OAuth2RestOperations restTemplate;
#RequestMapping(value="/", method= RequestMethod.GET)
public String TestForm() {
System.out.println("Token : " + restTemplate.getAccessToken().getValue());
}
}
But i got below exception
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails] with root cause
java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails
at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:190)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
at com.divyshivglobalinvestor.web.controller.PersonalLoanController.PersonalLoanForm(PersonalLoanController.java:37)
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:601)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
at org.apache.coyote.AreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)bstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.Th
From some blog I found that, if we need to grant password then, instead of ResourceOwnerPasswordResourceDetails, it should be used AccessTokenRequest (which is a Map and is ephemeral). It would be great if someone can help me in getting accessToken. :)
Thanks in advance !
You should use ResourceOwnerPasswordAccessTokenProvider instead of AuthorizationCodeAccessTokenProvider in restTemplate bean

Scala 2.10.1 and JaxB

Been upgrading our Glassfish app from scala 2.9 to 2.10 and I'm seeing JAXB trying to export private[this] methods as part of the web service.
For instance, here is a method signature, it's not even annotated.
private[this] def createFreeSubscription(user: User, plan: Plan): Option[UpdateResponseDO] = {}
Is there a change in 2.10 that would allow JAXB to think this should not be hidden?
Here is the error.
[#|2013-04-22T20:46:39.186-0600|SEVERE|glassfish3.1.2|javax.enterprise.webservices.org.glassfish.webservices|_ThreadID=112;_ThreadName=Thread-7;|Cannot initialize endpoint : error is :
com.sun.xml.ws.spi.db.DatabindingException: java.lang.RuntimeException: This version of JAXB might not be supported: proxy object creation failed, probably due to failing constructor method
at com.sun.xml.ws.db.glassfish.JAXBRIContextFactory.newContext(JAXBRIContextFactory.java:101)
at com.sun.xml.ws.spi.db.BindingContextFactory.create(BindingContextFactory.java:182)
at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:213)
at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:186)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:186)
at com.sun.xml.ws.model.AbstractSEIModelImpl.postProcess(AbstractSEIModelImpl.java:111)
at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:318)
at com.sun.xml.ws.db.DatabindingImpl.<init>(DatabindingImpl.java:99)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:74)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:58)
at com.sun.xml.ws.db.DatabindingFactoryImpl.createRuntime(DatabindingFactoryImpl.java:130)
at com.sun.xml.ws.server.EndpointFactory.createSEIModel(EndpointFactory.java:433)
at com.sun.xml.ws.server.EndpointFactory.create(EndpointFactory.java:268)
at com.sun.xml.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:145)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:569)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:552)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:623)
at org.glassfish.webservices.EjbRuntimeEndpointInfo.prepareInvocation(EjbRuntimeEndpointInfo.java:271)
at org.glassfish.webservices.Ejb3MessageDispatcher.handlePost(Ejb3MessageDispatcher.java:116)
at org.glassfish.webservices.Ejb3MessageDispatcher.invoke(Ejb3MessageDispatcher.java:91)
at org.glassfish.webservices.EjbWebServiceServlet.dispatchToEjbEndpoint(EjbWebServiceServlet.java:200)
at org.glassfish.webservices.EjbWebServiceServlet.service(EjbWebServiceServlet.java:131)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.doFilter(ServletAdapter.java:1059)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.invokeFilterChain(ServletAdapter.java:999)
at com.sun.grizzly.http.servlet.ServletAdapter.doService(ServletAdapter.java:434)
at com.sun.grizzly.http.servlet.ServletAdapter.service(ServletAdapter.java:384)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.RuntimeException: This version of JAXB might not be supported: proxy object creation failed, probably due to failing constructor method
at org.zeroturnaround.jrebel.jaxb.proxy.JaxbContextProxy.createProxy(JaxbContextProxy.java:55)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1163)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:188)
at com.sun.xml.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:111)
at com.sun.xml.ws.developer.JAXBContextFactory$1.createJAXBContext(JAXBContextFactory.java:113)
at com.sun.xml.ws.db.glassfish.JAXBRIContextFactory.newContext(JAXBRIContextFactory.java:89)
... 45 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedConstructorAccessor120.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.zeroturnaround.jrebel.jaxb.proxy.JaxbContextFactory.buildContext(JaxbContextFactory.java:31)
at org.zeroturnaround.jrebel.jaxb.proxy.JaxbContextProxyHandler.buildContext(JaxbContextProxyHandler.java:133)
at org.zeroturnaround.jrebel.jaxb.proxy.JaxbContextProxyHandler.<init>(JaxbContextProxyHandler.java:103)
at org.zeroturnaround.jrebel.jaxb.proxy.JaxbContextProxy.createProxy(JaxbContextProxy.java:46)
... 50 more
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 4 counts of IllegalAnnotationExceptions
scala.collection.Seq is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at scala.collection.Seq
at public final scala.collection.Seq scala.util.matching.Regex.scala$util$matching$Regex$$groupNames
at scala.util.matching.Regex
at public scala.util.matching.Regex com.gaiam.gcsi.ws.jaxws.CouponRegexResponse._return
at com.gaiam.gcsi.ws.jaxws.CouponRegexResponse
com.gaiam.gcsis.system.AuthorizationSystem$ServiceStatus is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at com.gaiam.gcsis.system.AuthorizationSystem$ServiceStatus
at public com.gaiam.gcsis.system.AuthorizationSystem$ServiceStatus com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$statusToAuthCode.arg0
at com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$statusToAuthCode
Two classes have the same XML type name "{http://gaiam.com/gcsi}option". Use #XmlType.name and #XmlType.namespace to assign different names to them.
this problem is related to the following location:
at scala.Option
at public scala.Option com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$getPurchasingOptionsResponse._return
at com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$getPurchasingOptionsResponse
this problem is related to the following location:
at fj.data.Option
at public fj.data.Option com.gaiam.gcsi.entities.user.User.getEmail()
at com.gaiam.gcsi.entities.user.User
at public com.gaiam.gcsi.entities.user.User com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$createFreeSubscription.arg0
at com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$createFreeSubscription
Two classes have the same XML type name "{http://gaiam.com/gcsi}state". Use #XmlType.name and #XmlType.namespace to assign different names to them.
this problem is related to the following location:
at com.gaiam.gcsi.entities.order.Order$State
at public com.gaiam.gcsi.entities.order.Order$State com.gaiam.gcsis.ws.dto.OrderInfoDO.getOrderState()
at com.gaiam.gcsis.ws.dto.OrderInfoDO
at public com.gaiam.gcsis.ws.dto.OrderInfoDO com.gaiam.gcsi.ws.jaxws.GetOrderInfoResponse.orderInfo
at com.gaiam.gcsi.ws.jaxws.GetOrderInfoResponse
this problem is related to the following location:
at com.gaiam.gcsi.entities.user.PaymentSource$State
at public com.gaiam.gcsi.entities.user.PaymentSource$State com.gaiam.gcsi.entities.user.PaymentSource.getState()
at com.gaiam.gcsi.entities.user.PaymentSource
at com.gaiam.gcsi.entities.user.CreditCard
at public com.gaiam.gcsi.entities.user.CreditCard com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$guessBillingAddress.arg0
at com.gaiam.gcsi.ws.jaxws.Com$gaiam$gcsi$ws$ClubSiteGateway$$guessBillingAddress
at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:106)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:466)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:298)
... 57 more
Use #XmlTransient to exclude fields, methods or classes from mapping.

EJB3 Stateless Bean is always null in REST-WebService (Glassfish3, EJB3, Stateless Bean,)

I hope you can help me with this:
I have a WebProject created with Eclipse as a dynamic web project, running on a Glassfish3 Server. I’m using EJB 3.0 to create a stateless Façade(#stateless Annotation) that implements my business logic:
#Stateless
public class Facade {
public void test(){
System.out.println("test hat geklappt!!");
}
}
Additionally I’m using a RESTRessource to offer my REST WS that uses my EJB with (#EJB Annotation) the business logic:
#RequestScoped
#Path("/prescriptions")
public class Ressource {
#EJB
private Facade facade;
public Ressource() {
super();
}
#GET
#Path("/user/{userid}")
#Produces(MediaType.APPLICATION_JSON)
public void getUser(#PathParam("userid") String userid) {
facade.test();
}
}
Although I can get into the REST WS and call it, my EJB is always null and I cant find a reason why.
I would really appreciate it if you could help me. In case you need more information about the code or something just ask.
Thanks in advance,
Florian
PS: I always get the following error in my log:
INFO: Portable JNDI names for EJB Facade : [java:global/TestProject/Facade,java:global/TestProject/Facade!webservices.Facade]
INFO: Portable JNDI names for EJB Facade : [java:global/TestProject/Facade, java:global/TestProject/Facade!webservices.Facade]
INFO: Scanning for root resource and provider classes in the packages:
webservices
INFO: Root resource classes found:
class webservices.Ressource
INFO: No provider classes found.
INFO: Initiating Jersey application, version 'Jersey: 1.5 01/14/2011 12:36 PM'
SCHWERWIEGEND: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at webservices.Ressource.getUser(Ressource.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$VoidOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:150)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:70)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:279)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:136)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:86)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:136)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:74)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1347)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1279)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1229)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1219)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:419)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Ideally RESTFul class design should be stateless, as explained in this article:
A stateless service not only performs better, it shifts most of the
responsibility of maintaining state to the client application
If you add the Stateless annotation to your Ressource class, you can inject your Facade session bean, and the container will care of the lifecycle of your session bean.
This will make your code run smoothly without the exception.
Don't forget to make your getUser method return a value!
public String getUser(#PathParam("userid") String userid) {
facade.test();
return "{" + userid + "}";
}