how to run actual java in the backend of gwt web application - java

For a specific requirement in my project, I want to retrieve JSON response from a web service api.
I am tried a java code in a simple Java project which is running fine.
String message = null;
HttpClient httpclient = new DefaultHttpClient();
JSONParser parser = new JSONParser();
String url = "working - url";
HttpResponse response = null;
response = httpclient.execute(new HttpGet(url));
JSONObject json_data = null;
json_data = (JSONObject)parser.parse(EntityUtils.toString(response.getEntity()));
JSONArray results = (JSONArray)json_data.get("result");
for (Object queid : results) {
message = message.concat((String) ((JSONObject)queid).get("id"));
message = message.concat("\t");
message = message.concat((String) ((JSONObject)queid).get("owner"));
message = message.concat("\n");
}
If I try to run this code in a GWT application servlet, I am getting several errors om compilation.
[ERROR] Line 16: No source code is available for type org.apache.http.client.ClientProtocolException; did you forget to inherit a required module?
[ERROR] Line 16: No source code is available for type org.apache.http.ParseException; did you forget to inherit a required module?
[ERROR] Line 16: No source code is available for type org.json.simple.parser.ParseException; did you forget to inherit a required module?
I have added the required jars using the project build path ->add external jars.
But still I am facing the same problem.
I have tried attaching the source to the jars but still the problem is same.
What possibly could be done in this case?
Can I run actual java in the backend of my GWT application
Edit #1:
This code is written in my GWT servlet. I have tried using adding throws clause to the method in my servlet and applying try/catch block as well. But I am still getting these errors.
Edit #2:
I have got following errors in my console log after applying try/catch block.
Mar 10, 2012 1:16:28 PM com.google.appengine.tools.development.ApiProxyLocalImpl log
SEVERE: javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String com.google.detracker.client.DeService.getJSONRespnse()' threw an unexpected exception: java.lang.NoClassDefFoundError: javax.net.ssl.KeyManagerFactory is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:385)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:588)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:35)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:58)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:70)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:351)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: java.lang.NoClassDefFoundError: javax.net.ssl.KeyManagerFactory is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
at org.apache.http.conn.ssl.SSLSocketFactory.createSSLContext(SSLSocketFactory.java:184)
at org.apache.http.conn.ssl.SSLSocketFactory.createDefaultSSLContext(SSLSocketFactory.java:209)
at org.apache.http.conn.ssl.SSLSocketFactory.<init>(SSLSocketFactory.java:333)
at org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(SSLSocketFactory.java:165)
at org.apache.http.impl.conn.SchemeRegistryFactory.createDefault(SchemeRegistryFactory.java:45)
at org.apache.http.impl.client.AbstractHttpClient.createClientConnectionManager(AbstractHttpClient.java:294)
at org.apache.http.impl.client.AbstractHttpClient.getConnectionManager(AbstractHttpClient.java:445)
at org.apache.http.impl.client.AbstractHttpClient.createHttpContext(AbstractHttpClient.java:274)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:797)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at com.google.detracker.server.DeServiceImpl.getJSONRespnse(DeServiceImpl.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:100)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
... 34 more
Mar 10, 2012 1:16:28 PM com.google.appengine.tools.development.LocalResourceFileServlet doGet

If you pay attention, The error is about an Exception class. This means your code is returning an exception which you are not handling. type org.apache.http.client.ClientProtocolException
Try surronding your code with try catch block and see what you get in the dev console.
Try {
String message = null;
HttpClient httpclient = new DefaultHttpClient();
JSONParser parser = new JSONParser();
String url = "working - url";
HttpResponse response = null;
response = httpclient.execute(new HttpGet(url));
JSONObject json_data = null;
json_data = (JSONObject)parser.parse(EntityUtils.toString(response.getEntity()));
JSONArray results = (JSONArray)json_data.get("result");
for (Object queid : results) {
message = message.concat((String) ((JSONObject)queid).get("id"));
message = message.concat("\t");
message = message.concat((String) ((JSONObject)queid).get("owner"));
message = message.concat("\n");
}
} catch (Exception e) {
e.printStack();
}
Explanation:
Some more explanation for all those who want it. In your code, you do not handle the exceptions with try catch blocks. Thus, when an exception is raised, the server will send it back to the client but most of the exceptions are NOT serializable, so they cannot be transported back to the client and this is why you get the mentioned error.

use RequestBuilder
http://code.google.com/webtoolkit/doc/latest/tutorial/JSON.html

Yes you can, but the error message suggest you have somewhere in your client side code imported a class that uses those server side external jars.
Edit: Based the answer of Adel Boutros I guess you have added throws to your GWT service interfaces for the classes that generate these errors? You can only throw exceptions that are also available to the client, so catch them on the server and rethrow a new exception that is available in the client.

If those librabries can actually be used in GWT, you have to add lines in your application.gwt.xml file to inherit the modules.
Example with library smartgwt:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Other module inherits -->
<inherits name="com.smartgwt.SmartGwt"/>
<!-- Specify the app entry point class. -->
<entry-point class='blablabla'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>

Related

java.io.EOFException GDrive API authorization

I am currently following https://developers.google.com/drive/v3/web/quickstart/java tutorial to get the list of files from the doogle drive. In am getting the following exception
Caused by:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at com.google.api.client.util.IOUtils.deserialize(IOUtils.java:171)
at com.google.api.client.util.store.FileDataStoreFactory$FileDataStore.<init>(FileDataStoreFactory.java:102)
at com.google.api.client.util.store.FileDataStoreFactory.createDataStore(FileDataStoreFactory.java:73)
at com.google.api.client.util.store.AbstractDataStoreFactory.getDataStore(AbstractDataStoreFactory.java:55)
at com.google.api.client.auth.oauth2.StoredCredential.getDefaultDataStore(StoredCredential.java:171)
at com.google.api.client.auth.oauth2.AuthorizationCodeFlow$Builder.setDataStoreFactory(AuthorizationCodeFlow.java:736)
at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder.setDataStoreFactory(GoogleAuthorizationCodeFlow.java:209)
at com.demo.gapps.server.FetchNewFilesCron.authorize(FetchNewFilesCron.java:233)
at com.demo.gapps.server.FetchNewFilesCron.getDriveService(FetchNewFilesCron.java:244)
at com.demo.gapps.server.FetchNewFilesCron.doGet(FetchNewFilesCron.java:97)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:128)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:50)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:511)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
The code from the tutorial that I am using to authorize that generated teh potential exception is as follows:
* #return an authorized Credential object.
* #throws IOException
*/
public static Credential authorize() throws IOException {
System.out.println("file path is "+DATA_STORE_DIR.getPath());
// Load client secrets.
InputStream in =
FetchNewFilesCron.class.getResourceAsStream("/client_secrets.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
The error is probably at .setDataStoreFactory(DATA_STORE_FACTORY)
Can anybody please guide me with this error.
Thanks,
The exception indicates the the end of file (EOF), or the end of stream has been reached unexpectedly. Also, this exception is mainly used by DataInputStreams, in order to signal the end of stream. However, notice that other input operations may return a special value upon the end of a stream, instead of throwing an EOFException.
The EOFException class extends the IOException class, which is the general class of exceptions produced by failed or interrupted I/O operations. Moreover, it implements the Serializable interface. Also, it is defined as a checked exception and thus, it must be declared in a method or a constructor’s throws clause.
DataInputStreams provide methods that can read primitive Java data types from an underlying input stream in a machine-independent way. An application writes data, by using the methods provided by the OutputStream class or the DataOutputStream class.
For more information, check this related SO ticket which discuss about EOFException and DataInputStream: java.io.EOFException when try to read from a socket
I know that this is an old post, but I had almost the exact same stacktrace and the only answer wasn't very helpful. So, I'm posting in hopes that it will help those that come after me.
The issue appears to be related to file/directory permissions. As soon as I changed the filepath being used by the FileDataStoreFactory to a directory that my application had read/write permissions to, OAuth2 worked correctly. So, make sure that you are using a non-restricted filepath and that all of the directories have the correct ownership and permissions.

Tapestry 5.4 exception in ExceptionReport.tml

I've got a question regarding tapestry 5.4. I try to integrate it with tynamo tapestry security and Google App Engine and after some development I started to get these exception when "something" in application is not working. I have written "something" because problem concerns ExceptionPage (as you can see on stacktrace attached below).
Has anybody faced such a problem?
Of course I can post some configuration files, but since I have no idea what can cause this exception of error page, I not posing any at the moment.
HTTP ERROR 500
Problem accessing /. Reason:
org.apache.tapestry5.internal.services.RenderQueueException: Render queue error in SetupRender[core/ExceptionReport:loop_0]: Failure reading parameter 'source' of component core/ExceptionReport:loop_0: access denied ("java.lang.RuntimePermission" "modifyThreadGroup") [at classpath:org/apache/tapestry5/corelib/pages/ExceptionReport.tml, line 110]
Caused by:
org.apache.shiro.subject.ExecutionException: org.apache.tapestry5.internal.services.RenderQueueException: Render queue error in SetupRender[core/ExceptionReport:loop_0]: Failure reading parameter 'source' of component core/ExceptionReport:loop_0: access denied ("java.lang.RuntimePermission" "modifyThreadGroup") [at classpath:org/apache/tapestry5/corelib/pages/ExceptionReport.tml, line 110]
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:385)
at org.tynamo.security.services.impl.SecurityConfiguration.service(SecurityConfiguration.java:54)
at $HttpServletRequestFilter_12a67d391b5c.service(Unknown Source)
at $HttpServletRequestHandler_12a67d391b5f.service(Unknown Source)
at org.apache.tapestry5.internal.gzip.GZipFilter.service(GZipFilter.java:59)
at $HttpServletRequestHandler_12a67d391b5f.service(Unknown Source)
at org.apache.tapestry5.internal.services.IgnoredPathsFilter.service(IgnoredPathsFilter.java:62)
at $HttpServletRequestFilter_12a67d391b59.service(Unknown Source)
at $HttpServletRequestHandler_12a67d391b5f.service(Unknown Source)
at org.apache.tapestry5.modules.TapestryModule$1.service(TapestryModule.java:804)
at $HttpServletRequestHandler_12a67d391b5f.service(Unknown Source)
at $HttpServletRequestHandler_12a67d391b58.service(Unknown Source)
at org.apache.tapestry5.TapestryFilter.doFilter(TapestryFilter.java:166)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:503)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
The problem is not the exceptionpage but the way Google App Engine (GAE) implements its security policy to restrict spawning new threads. The line:
access denied ("java.lang.RuntimePermission" "modifyThreadGroup")
in your stack trace originates from Java Security Manager for a violation of the policy. While Tynamo's tapestry-security does not invoke new threads, apparently it's not allowed to invoke Callable.call() in GAE. See how the SecurityConfiguration invokes the filter chain after binding the currently executing subject.
Callable is just an interface so it's unnecessary for GAE to prohibit an invocation to it but I suspect it was easier for them to do that than try to block executions of various Executor services that may or may not spawn threads.
However, SecurityConfiguration does not need to use Callable at all. SecurityConfiguration was implemented following Shiro's original AbstractShiroFilter, but one could also manually bind the subject to the currently executing thread, like so:
ThreadContext.bind(securityManager);
WebSubject subject = new WebSubject.Builder(securityManager, originalRequest, response).buildWebSubject();
ThreadContext.bind(subject);
try {
// return subject.execute(new Callable<Boolean>() {
// public Boolean call() throws Exception {
if (chain == null) return handler.service(request, response);
else {
boolean handled = chain.getHandler().service(request, response);
return handled || handler.service(request, response);
}
// }
// });
}
finally {
ThreadContext.remove(subject);
ThreadContext.remove();
}
You could override SecurityConfiguration yourself with a version that operates in the same manner as above. If you want to help, try it and let me know if everything else works. You may run into other issues since GAE can be a fairly restrictive environment for full-fledged Java applications.

Error with GoogleCredentials and Directory in google-admin-sdk

I'm trying to access google admin-directory API to create, delete or remove users as administrator.
I'm trying to develop an application that allows to update or delete a user.
I tried to take two paths.
In the first way, I used the code shown: Google Admin Directory API is returning 400 bad request
But adapting the code is like follows:
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential;
SCOPES.add("https://www.googleapis.com/auth/admin.directory.user");
GoogleCredential credential;
try {
credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(
"XXXXXXXXXX#developer.gserviceaccount.com")
.setServiceAccountUser("XXX#subdomain.domain.com")//(The administrator account)
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(
new File("WEB-INF/KeY.p12")).build();
credential.setAccessToken(oauthToken);
resp.getWriter().println(credential.getServiceAccountId());
Directory directory = new Directory.Builder(httpTransport, jsonFactory, credential).setApplicationName("User Sync Service")
.setHttpRequestInitializer(credential).setApplicationName("Example APP").build();
resp.getWriter().println();
Directory.Users.List list = directory.users().list();
list.setDomain("subdomain.domain.com");
Users users = list.execute();
In this case, the problem is when the Directory object (Directory directory = new Directory.Builder(...) ) instanciate's or executes, and this is the error:
Uncaught exception from servlet
com.google.api.client.auth.oauth2.TokenResponseException: 400 OK
{
"error" : "invalid_grant"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:332)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:352)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:454)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:215)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:854)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at com.ejemploprueba.Inbox.doGet(Inbox.java:85)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:266)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:146)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:439)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:435)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:442)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:186)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:306)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:298)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:439)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
at java.lang.Thread.run(Thread.java:722)
The second way is to create a servlet that call to the api with SCOPE = "https://www.googleapis.com/auth/admin.directory.user", to
get the acces_token and the user in a second servlet.
In this way I find the problem to create a GoogleCredential and connect to with the services server with the acces_token and the user, and then instantiate the object "Directory" to show in step 1.
Where:
acces_token: ya29.AHES6ZREQdCcm7FqZGg3Do0jYxN-XXXXXXXXXXX-YYYYYYYYYYYYYy
and
User: user#subdomain.domain.com
I enabled the "Admin SDK" option into the Google Api Console / Services
How can I fix the error that occurs in the first case?
What is the solution to the second way?
What it's the better solution, the first way or the second?
Thank you very much in advance and greetings.
For case 1 when you call:
credential.setAccessToken(oauthToken);
You are replacing the access token obtained from the Google Authorization Server with the content of oauthToken, which looks like is not a valid access token for that service account.
Not sure if this will help you, but I've done something similar in C#.
Had some serious authorization-issues at first, but finally made it.
Check this stackoverflow
Trying to Create users in Google Apps domain in Windows Forms code

App Engine URLFetch service called from Clojure gives AccessControlException

I'm trying to build a simple web widget in Clojure which should fetch a Picasa feed, retrieve the thumbnail URLs from there, and return HTML which will be inserted into a page (using JQuery AJAX call). The Picasa feed has a https://... url.
Everything works when I run it in a local Jetty instance using mvn jetty:run ; however when I try to run in a local GAE instance (mvn gae:run) it fails with an AccessControlException.
I've read the GAE documentation, but this states that for URLFetch from Java one should just use the normal Java URLConnection class where Google will provide their own implementation. As far as I can see I'm following their example to the letter, only using Clojure/Java interop.
Google example code looks like this:
import java.net.URL;
// (other imports omitted)
try {
URL url = new URL("http://www.example.com/atom.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
// ...
}
Interestingly this is calling openStream directly on the URL although elsewhere the documentation mentions to use UrlConnection. I've tried both, but the result is the same.
My corresponding Clojure code, using openConnection:
(if (.startsWith str-url "https://picasaweb.google.com")
(let [feed-url (java.net.URL. str-url)
connection (.openConnection feed-url)
xmltags (xml-seq (parse (.openStream connection)))]
; ...
When I run this in GAE I get the following stack trace (truncated)
java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.mortbay.jetty.servlet.Holder.newInstance(Holder.java:153)
at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:428)
at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:339)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:35)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:60)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122)
And finally at the bottom:
Caused by: java.security.AccessControlException: access denied (java.security.SecurityPermission getProperty.ssl.KeyManagerFactory.algorithm)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:252)
at java.security.Security.getProperty(Security.java:725)
at org.eclipse.jetty.util.ssl.SslContextFactory.<clinit>(SslContextFactory.java:92)
... 74 more
I have been Googling to see if there is any setting I should add in appengine-web.xml or somewhere else, but I see nothing. Everything I read tells me this should "just work", but it doesn't.
Any advice is most welcome; I can post full source or a full stacktrace if desired, although I think the above is pretty much the pertinent bits.
openStream() is shorthand for openConnection().getInputStream(), where openConnection() returns URLConnection.

Integrate openid4java to GWT Project

I created an GWT project in eclipse. Now I tried to implement openId with using the openid4java library.
I imported the .jar files via properties-->java build path:
openid4java-0.9.5.jar
lib/*.jar
In addition I copied the .jar files into the war/WEB-INF/lib directory.
The problem at hand comes up when I call the authenticate() method.
Then I get a:
HTTP ERROR 500
Problem accessing /openid/openid. Reason:
access denied (java.lang.RuntimePermission modifyThreadGroup)Caused by:java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:166)
at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkAccess(DevAppServerFactory.java:191)
at java.lang.ThreadGroup.checkAccess(Unknown Source)
at java.lang.Thread.init(Unknown Source)
at java.lang.Thread.<init>(Unknown Source)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$ReferenceQueueThread.<init>(MultiThreadedHttpConnectionManager.java:1039)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.storeReferenceToConnection(MultiThreadedHttpConnectionManager.java:164)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.access$900(MultiThreadedHttpConnectionManager.java:64)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$ConnectionPool.createConnection(MultiThreadedHttpConnectionManager.java:750)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.doGetConnection(MultiThreadedHttpConnectionManager.java:469)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getConnectionWithTimeout(MultiThreadedHttpConnectionManager.java:394)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:152)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
at org.openid4java.util.HttpCache.head(HttpCache.java:296)
at org.openid4java.discovery.yadis.YadisResolver.retrieveXrdsLocation(YadisResolver.java:360)
at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:229)
at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:221)
at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:179)
at org.openid4java.discovery.Discovery.discover(Discovery.java:134)
at org.openid4java.discovery.Discovery.discover(Discovery.java:114)
at org.openid4java.consumer.ConsumerManager.discover(ConsumerManager.java:527)
at auth.openid.server.OpenIDServlet.authenticate(OpenIDServlet.java:138)
at auth.openid.server.OpenIDServlet.doGet(OpenIDServlet.java:101)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:693)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:51)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:70)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:349)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Here my servlet source:
import com.google.gwt.user.client.rpc.RemoteService;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.ParameterList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
public final class OpenIDServlet extends HttpServlet implements RemoteService {
private final ConsumerManager manager;
public OpenIDServlet() {
try {
manager = new ConsumerManager();
} catch (ConsumerException e) {
throw new RuntimeException("Error creating consumer manager", e);
}
}
...
private void authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
final String loginString = request.getParameter(nameParameter);
try {
// perform discovery on the user-supplied identifier
List discoveries = manager.discover(loginString);
// attempt to associate with the OpenID provider
// and retrieve one service endpoint for authentication
DiscoveryInformation discovered = manager.associate(discoveries);
// obtain a AuthRequest message to be sent to the OpenID provider
AuthRequest authReq = manager.authenticate(discovered, "openid", null);
// redirect to OpenID for authentication
response.sendRedirect(authReq.getDestinationUrl(true));
}
catch (OpenIDException e) {
throw new ServletException("Login string probably caused an error. loginString = " + loginString, e);
}
}
My question now is:
What could be my fault? Did I make any mistakes in importing the openid4java library? (which?)
All other methods in the servlet which do not use the openid4java implementation work fine.
Thanks,
Andreas
You are using Google App Engine. GAE restricts the libraries that can be used in an application. In particular, creating threads or accessing the network are prohibited.
The stack trace you pasted shows openid creating a java, and GAE blocking it.
If you don't care about GAE, just disable it in eclipse settings. Once you do that, you should be able to use the library.
If you also want to use GAE, then you will have to find an alternative to OpenId4Java. Somebody else may have an alternative to that.
Due to the restrictions of GAE you can't use openid4java directly.
You can try this modified version: http://github.com/WdWeaver/openid4java-gae-hacks
I think you're missing the servlet entry in web.xml
<servlet>
<servlet-name>OpenIdServlet</servlet-name>
<servlet-class>path.to.your.servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OpenIdServlet</servlet-name>
<url-pattern>/openid/openid</url-pattern>
</servlet-mapping>

Categories