Why do I get ClassCastException using HttpURLConnection in AppEngine? - google-app-engine

I try to call an external web service (not mine) from my GWT application working with App Engine.
I know it's impossible to do it from the client due to the SOP (Same Origin Policy) and RequestBuilder is not a solution on the server. I followed the tutorial on the web site and using java.net as well
Here is the client
AsyncCallback<CustomObject> callback = new AsyncCallback<CustomObjectCustomObject>() {
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(CustomObject result) {
// code omitted
}
};
service.callMethod(aString, callback);
And this is the server
try {
String xmlRequest = "xmlToSend";
URL url = new URL("https://www.externalWebService.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setAllowUserInteraction(false);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type","application/soap+xml");
conn.setRequestProperty( "Content-length", Integer.toString(xmlRequest.length()));
conn.setRequestProperty("charset", "utf-8");
conn.setConnectTimeout(10000);
OutputStream rawOutStream = conn.getOutputStream();
PrintWriter pw = new PrintWriter(rawOutStream);
pw.print(xmlRequest);
pw.flush();
pw.close();
if(conn.getResponseCode() != 200){
// Something...
}
I keep having the same error at conn.getResponseCode() :
java.lang.ClassCastException: com.google.appengine.repackaged.org.apache.http.message.BasicHttpRequest cannot be cast to com.google.appengine.repackaged.org.apache.http.client.methods.HttpUriRequest
Without making a real request, the remote service works well : it's able to serialize and return objects to the client. The issue is not linked to the communication between the client and the server, it's more like AppEngine doesn't support HttpURLConnection. But it should on the server (isn't it?)
Any thoughts would be hightly appreciated! Thanks in advance

Your problem has nothing to do with GWT: as long as you are running on the server, you can use any 'normal' Java and it will work unless AppEngine has restrictions.
It seems you have imported the repackaged version of Apache HttpClient in your class. You should not do that: download your own HttpClient .jar, add it to the dependencies and use that one.
AppEngine also has some issues with HttpClient. There's an adapter available here that fixes most of the issues.

Thanks #Marcelo, you were right!
Here is the solution I found.
I added httpcore.jar and httpclient.jar to my build path and wrote the code below for the server (the client is the same) :
String xmlRequest = "xmlToSend";
CloseableHttpClient httpclient = HttpClients.custom().build();
//RequestConfig requestConfig = RequestConfig.custom()
// .setConnectionRequestTimeout(10000)
// .build();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out);
writer.write(xmlToSend);
writer.flush();
writer.close();
HttpPost request = new HttpPost("https://www.externalWebService.com/path");
request.setEntity(new ByteArrayEntity(out.toByteArray()));
//request.setConfig(requestConfig);
CloseableHttpResponse response = httpclient.execute(request);
if(response.getStatusLine().getStatusCode() == 200){
// retrieve content with a BufferReader
// from response.getEntity().getContent()
...
}
The code works and is up to date.
Edit
Here is the rest of the solution when using a proxy. Mine only deals with NTCredentials but otherwise UsernamePasswordCredentials can be used instead.
HttpHost proxy = new HttpHost("addresse.proxy.com", port);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxy),
new NTCredentials(System.getProperty("user.name") + ":" + password));
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(proxy)
.build();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultRequestConfig(requestConfig)
.build();
Thanks again for your help, I really appreciated!

Related

Unable to get IAM security credentials from EC2 Instance Metadata Service error when using Aws Sdk in UWP

I'm working with Aws Sdk and I'm trying to implement a login UI using UWP. I followed this online tutorial (which is for WPF) and I tried to make it works for the Universal Windows Platform as well.
The core part of the source code is the following (please note that is 90% similar to the one posted in the tutorial. The "only difference" is that I used
InitiateAuthAsync
instead of
AdminInitiateAuthAsync
<!-- language: lang-cs -->
private readonly AmazonCognitoIdentityProviderClient _client;
private readonly string _clientId = "32fsoifj93fjsiispat";
public MainPage()
{
this.InitializeComponent();
var amazonCognitoIdentityProviderConfig = new AmazonCognitoIdentityProviderConfig();
amazonCognitoIdentityProviderConfig.ServiceURL = "https://cognito-idp.eu-central-1.amazonaws.com/";
_client = new AmazonCognitoIdentityProviderClient(amazonCognitoIdentityProviderConfig);
}
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
List<HttpHeader> httpHeaders = new List<HttpHeader>();
HttpHeader httpHeader = new HttpHeader
{
HeaderName = "X-Amz-Target",
HeaderValue = "AWSCognitoIdentityProviderService.InitiateAuth"
};
httpHeaders.Add(httpHeader);
httpHeader = new HttpHeader
{
HeaderName = "Content-Type",
HeaderValue = "application/x-amz-json-1.1"
};
httpHeaders.Add(httpHeader);
var authReq = new InitiateAuthRequest()
{
ClientId = _clientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
var authResp = await _client.InitiateAuthAsync(authReq);
return true;
}
catch (Exception ex)
{
return false;
}
}
Please consider that it is working properly with WPF framework. I'm able to get the TokenId and RefreshToken.
But if I try to copy and paste the same code in UWP I get the exception:
'Unable to get IAM security credentials from EC2 Instance Metadata Service.'
And if I try to investigate with Fiddler I get the following error:
[Fiddler] The connection to '169.254.169.254' failed. Error: NetworkUnreachable (0x2743). System.Net.Sockets.SocketException A socket operation was attempted to an unreachable network 169.254.169.254:80
I really can't understand why it tries to connect to the '169.254.169.254' address. Googling around I found other people experiencing the same issue (for example here). Do you have any idea?

How to use REST API for sending messages to Azure Notification Hub from Java/GAE

I have successfully implemented calling GAE -> Azure Mobile Services -> Azure Notification HUB.
But I want to skip the Mobile Services step and call the notification HUB directly and I can't figure out how to send the authorization token. The returned error is:
Returned response: <Error><Code>401</Code><Detail>MissingAudience: The provided token does not
specify the 'Audience'..TrackingId:6a9a452d-c3bf-4fed-b0b0-975210f7a13c_G14,TimeStamp:11/26/2013 12:47:40 PM</Detail></Error>
Here is my code:
URL url = new URL("https://myapp-ns.servicebus.windows.net/myhubbie/messages/?api-version=2013-08");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(60000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestProperty("Authorization","WRAP access_token=\"mytoken_taken_from_azure_portal=\"");
connection.setRequestProperty("ServiceBusNotification-Tags", tag);
byte[] notificationMessage = new byte[0];
try
{
notificationMessage = json.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
log.warning("Error encoding toast message to UTF8! Error=" + e.getMessage());
}
connection.setRequestProperty("Content-Length", String.valueOf(notificationMessage.length));
OutputStream ostream = connection.getOutputStream();
ostream.write(notificationMessage);
ostream.flush();
ostream.close();
int responseCode = connection.getResponseCode();
The authorization header has to contain a token specially crafted for each individual request. The data you are using is the key you have to use to generate such a token.
Please follow the instructions on : http://msdn.microsoft.com/en-us/library/dn495627.aspx to create a token for your requests.
Final note, if you are using Java, you can use the code in this public repo https://github.com/fsautomata/notificationhubs-rest-java. It contains a fully functional REST wrapper for Notification Hubs. It is not Microsoft official but works and implements the above specs.

NoClassDefFoundError: javax.naming.directory.InitialDirContext is a restricted class. Using CCS (GCM) in Google App Engine

Im trying to implement google's Cloud Connection Server with Google App Engine following this tutorial -
Implementing an XMPP-based App Server. I copied latest smack jars from http://www.igniterealtime.org/projects/smack/ (smack.jar and smackx.jar), put them in WEB-INF/lib and added them to the classpath (im using eclipse).
In the code sample in the first link i posted, the XMPPConnection is initiated in a 'main' method. Since this is not really suitable to GAE i created a ServletContextListener and added it to web.xml.
public class GCMContextListener implements ServletContextListener {
private static final String GCM_SENDER_ID = "*GCM_SENDER_ID*";
private static final String API_KEY = "*API_KEY*";
private SmackCcsClient ccsClient;
public GCMContextListener() {
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
final String userName = GCM_SENDER_ID + "#gcm.googleapis.com";
final String password = API_KEY;
ccsClient = new SmackCcsClient();
try {
ccsClient.connect(userName, password);
} catch (XMPPException e) {
e.printStackTrace();
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
try {
ccsClient.disconnect();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
web.xml
<web-app>
<listener>
<listener-class>com.myserver.bootstrap.GCMContextListener</listener-class>
</listener>
</web-app>
Now, when i start the GAE server i get the following exception :
java.lang.NoClassDefFoundError: javax.naming.directory.InitialDirContext is a restricted class. Please see the Google App Engine developer's guide for more details.
i searched the "Google App Engine developer's guide for more details" but couldnt find anything about this. can you please help me ?
Google App Engine restricts access to certain JRE classes. In fact they published a whitelist that shows you which classes are useable. It seems to me that the Smack library might require some reference to a directory context (maybe to create the XMPP messages?) and that is why your servlet causes this exception. The javax.naming.directory is not in the whitelist.
I'm currently working on setting up a GCM Server as well. It seems to me that you need to read through the example and see what that main method is doing. What I see is a connection to the GCM server:
try {
ccsClient.connect(userName, password);
} catch (XMPPException e) {
e.printStackTrace();
}
Then a downstream message being sent to a device:
// Send a sample hello downstream message to a device.
String toRegId = "RegistrationIdOfTheTargetDevice";
String messageId = ccsClient.getRandomMessageId();
Map<String, String> payload = new HashMap<String, String>();
payload.put("Hello", "World");
payload.put("CCS", "Dummy Message");
payload.put("EmbeddedMessageId", messageId);
String collapseKey = "sample";
Long timeToLive = 10000L;
Boolean delayWhileIdle = true;
ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey,
timeToLive, delayWhileIdle));
}
These operations would be completed at some point during your application's lifecycle, so your servlet should support them by providing the methods the example is implementing, such as the connect method that appears in the first piece of code that I pasted here. It's implementation is in the example at line 235 if I'm not mistaken.
As the documentation says, the 3rd party application server, which is what you're trying to implement using GAE, should be:
Able to communicate with your client.
Able to fire off properly formatted requests to the GCM server.
Able to handle requests and resend them as needed, using exponential back-off.
Able to store the API key and client registration IDs. The API key is included in the header of POST requests that send messages.
Able to store the API key and client registration IDs.
Able to generate message IDs to uniquely identify each message it sends.

jackrabbit start repository slow

In my current Tomcat Project, I integrated JackRabbit. Its functionality works well. However, the start of the repository is very slow. It took around 5 seconds. I think this is not bearable. Anyone has some ideas about how to integrate the Jackrabbit to the web project?
Currently, I have my own Session factory in the web project. Code is as following:
public class TMPSessionFactory {
public static Session getSession() throws RepositoryException, NamingException {
String configFile = "C:\\workspaces\\repository.xml";
String repHomeDir = "C:\\JackRabbitDemo\\repository";
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
hashTable.put(Context.INITIAL_CONTEXT_FACTORY, DummyInitialContextFactory.class.getName());
hashTable.put(Context.PROVIDER_URL, "127.0.0.1");
InitialContext ctx = new InitialContext(hashTable);
RegistryHelper.registerRepository(ctx, "repo", configFile, repHomeDir, true);
Repository r = (Repository) ctx.lookup("repo");
SimpleCredentials cred = new SimpleCredentials("admin", "admin".toCharArray());
Session session = r.login(cred, null);
return session;}}
Each time if I need a jackrabbit session, I will call this static function.
I don't know whether my way is appropriate or not since it works but not well enough (each time, the start of the repository is slow).
Do you mean you create a new repository and bind it to JNDI before doing a look up each time you want to access your repository ?
All this code:
String configFile = "C:\\workspaces\\repository.xml";
String repHomeDir = "C:\\JackRabbitDemo\\repository";
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
hashTable.put(Context.INITIAL_CONTEXT_FACTORY, DummyInitialContextFactory.class.getName());
hashTable.put(Context.PROVIDER_URL, "127.0.0.1");
InitialContext ctx = new InitialContext(hashTable);
RegistryHelper.registerRepository(ctx, "repo", configFile, repHomeDir, true);
should be only called once.
Maybe you should declared your jackrabbit repository as a Tomcat resource as it is documented here : https://jackrabbit.apache.org/shared-j2ee-resource-howto.html

Exporting data to Google Spreadsheet from Google App Engine (Java version)

I am getting no where now. When I Google around to find a sample of "Exporting data to Google Spreadsheet from Google App Engine", I see a lot of Google Conversion API, Google Conversion API, Google Spreadsheet API and Google Docs API tutorials. But then they all deprecated from Google when I check at the Google site??? So, what is the most updated right now so I can make use of it?
=====
Okay now I use the Google Drive SDK via OAuth2 to create text file. But I have problem with this:
this is the error:
java.lang.NullPointerException at
java.net.URI$Parser.parse(URI.java:3004) at
java.net.URI.(URI.java:577) at
com.google.api.client.http.GenericUrl.(GenericUrl.java:100) at
com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:269)
at
com.google.api.services.drive.Drive$Files$Insert.executeUnparsed(Drive.java:309)
at
com.google.api.services.drive.Drive$Files$Insert.execute(Drive.java:331)
at
com.company.dashboard.service.DriveService.initDoc(DriveService.java:84)
this is the code:
private GoogleCredential buildGoogleCredential(Credential credential) {
try {
logger.warning(oauth2Service.getClientCredential().toString());
GoogleCredential googleCredential = new GoogleCredential.Builder()
.setClientSecrets(oauth2Service.getClientCredential())
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory()).build();
googleCredential.setAccessToken(credential.getAccessToken());
googleCredential.setRefreshToken(credential.getRefreshToken());
return googleCredential;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private Drive buildService(GoogleCredential credential) {
return new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), credential).build();
}
public void initDoc(HttpServletRequest req)
throws Exception {
User user = UserServiceFactory.getUserService().getCurrentUser();
Credential credential = oauth2Service.getStoredCredential(
user.getUserId(),
(CredentialStore)req.getSession().getServletContext().getAttribute(OAuth2Constant.GOOG_CREDENTIAL_STORE));
if (credential != null) {
logger.warning("Using access token: " + credential.getAccessToken());
try {
GoogleCredential googleCredential = buildGoogleCredential(credential);
Drive service = buildService(googleCredential);
if (service == null) {
logger.warning("very bad!");
}
File body = new File();
body.setTitle("My document");
body.setDescription("A test document");
body.setMimeType("text/plain");
java.io.File fileContent = new java.io.File("document.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);
service.files().insert(body, mediaContent).execute();
//File file = service.files().insert(body, mediaContent).execute();
//System.out.println("File ID: " + file.getId());
} catch (HttpResponseException e) {
if (e.getStatusCode() == 401) {
logger.warning(e.getMessage());
// Credentials have been revoked.
// TODO: Redirect the user to the authorization URL.
throw new UnsupportedOperationException();
}
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
}
oauth2Service.getClientCredential() returns (xxx = client id and client secret code, not shown in here)
{"web":{"client_id":"xxx.apps.googleusercontent.com","client_secret":"xxx"}}
This is my scope:
final static List<String> SCOPES = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/docs",
"https://www.googleapis.com/auth/drive.file");
final static String AUTH_RESOURCE_LOC = "/client_secrets.json";
final static String OATH_CALLBACK = "http://localhost:8888/oauth2callback";
This line
service.files().insert(body, mediaContent).execute();
throws NullPointerException. Any idea what had gone wrong???
P/S: Credential = com.google.api.client.auth.oauth2.Credential. I have my OAuth2 everything works good. I can retrieve user info without problem but not the Drive API. service is not null as you see I put it the log as "very bad" and it is not shown. No 401 exception is thrown means my Oauth2 is good with the scopes.
=======
DARN!!!! Finally solved the issue!!! My code was totally correct! Just I enabled the wrong API! It should be Drive API instead of Drive SDK API :/
You can generate a csv file from GAE and upload it using the Drive API with ?convert=true to have it automatically converted to a Google spreadsheet:
https://developers.google.com/drive/v2/reference/files/insert

Resources