Skip to content

Instantly share code, notes, and snippets.

@arschles
Created July 5, 2012 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arschles/3055748 to your computer and use it in GitHub Desktop.
Save arschles/3055748 to your computer and use it in GitHub Desktop.
OAuth Signing with StackMob Custom Code's HttpService
//goes in src/main/java/com/stackmob/oauthhttpservice
package com.stackmob.oauthhttpservice;
import org.scribe.services.TimestampService;
import org.scribe.services.TimestampServiceImpl;
import org.scribe.model.Token;
import org.scribe.builder.api.DefaultApi10a;
class HttpRequestSignerAPI extends DefaultApi10a {
public static class TimeService extends TimestampServiceImpl {
@Override
public String getTimestampInSeconds() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
}
@Override
public String getRequestTokenEndpoint() {
return null;
}
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
public String getAuthorizationUrl(Token token) {
return null;
}
@Override
public TimestampService getTimestampService()
{
return new TimeService();
}
}
//goes in src/main/java/com/stackmob/oauthhttpservice
package com.stackmob.oauthhttpservice;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
import com.stackmob.sdkapi.http.*;
import com.stackmob.sdkapi.http.request.*;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.net.MalformedURLException;
class HttpRequestSigner {
private String apiKey;
private String apiSecret;
private String appName;
private int apiVersionNum;
private OAuthService oAuthService;
private static final String userAgentName = "Custom Code HttpService";
//pass the API key, secret, and version here for the stackmob app that you want to call
public HttpRequestSigner(String apiKey, String apiSecret, String appName, int apiVersionNum) {
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.appName = appName;
this.apiVersionNum = apiVersionNum;
this.oAuthService = new ServiceBuilder().provider(HttpRequestSignerAPI.class).apiKey(apiKey).apiSecret(apiSecret).build();
}
private String getUserAgentString() {
return String.format("StackMob (%s; %d)%s", userAgentName, apiVersionNum, "/"+appName);
}
private String getAcceptString() {
return "application/vnd.stackmob+json; version="+apiVersionNum;
}
private static Verb calculateVerb(HttpRequest req) {
if(req instanceof GetRequest) return Verb.GET;
else if(req instanceof PostRequest) return Verb.POST;
else if(req instanceof PutRequest) return Verb.PUT;
else return Verb.DELETE;
}
private static Set<Header> convertToHeaderSet(Map<String, String> map) {
Set<Header> ret = new HashSet<Header>();
for(Map.Entry<String, String> entry: map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
ret.add(new Header(key, value));
}
return ret;
}
private OAuthRequest createAndSignOAuthRequest(HttpRequest inputRequest) {
String url = inputRequest.getUrl().toString();
Verb verb = calculateVerb(inputRequest);
OAuthRequest oReq = new OAuthRequest(verb, url);
//construct complete header list
List<Header> headerList = new ArrayList<Header>();
if(!verb.equals(Verb.GET) && !verb.equals(Verb.DELETE)) {
headerList.add(new Header("Content-Type", "application/json"));
}
headerList.add(new Header("Accept", getAcceptString()));
headerList.add(new Header("User-Agent", getUserAgentString()));
headerList.addAll(inputRequest.getHeaders());
//add headers to request
for(Header header: headerList) {
oReq.addHeader(header.getName(), header.getValue());
}
//sign and return request
oAuthService.signRequest(new Token("", ""), oReq);
return oReq;
}
public HttpRequestWithoutBody sign(HttpRequestWithoutBody unsigned) throws MalformedURLException {
OAuthRequest req = createAndSignOAuthRequest(unsigned);
String url = unsigned.getUrl().toString();
Set<Header> completeHeaders = convertToHeaderSet(req.getHeaders());
if(unsigned instanceof GetRequest) return new GetRequest(url, completeHeaders);
else return new DeleteRequest(url, completeHeaders);
}
public HttpRequestWithBody sign(HttpRequestWithBody unsigned) throws MalformedURLException {
OAuthRequest req = createAndSignOAuthRequest(unsigned);
String url = unsigned.getUrl().toString();
Set<Header> completeHeaders = convertToHeaderSet(req.getHeaders());
String body = unsigned.getBody();
if(unsigned instanceof PostRequest) return new PostRequest(url, completeHeaders, body);
else return new PutRequest(url, completeHeaders, body);
}
}
//goes in /
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<!--
Copyright 2012 StackMob
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<modelVersion>4.0.0</modelVersion>
<groupId>com.stackmob</groupId>
<artifactId>oauth-httpservice-example</artifactId>
<packaging>jar</packaging>
<version>0.1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<customcode.version>0.4.4</customcode.version>
</properties>
<dependencies>
<dependency>
<groupId>com.stackmob</groupId>
<artifactId>customcode</artifactId>
<version>${customcode.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.scribe</groupId>
<artifactId>scribe</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
@arschles
Copy link
Author

arschles commented Jul 6, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment