Skip to content
Browse files

initial commit

  • Loading branch information...
0 parents commit 37878731cc6864358264e849a2760c2fc251f25a @qrtt1 committed Sep 12, 2011
8 .classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" output="target/classes" path="src/main/java"/>
+ <classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+ <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
1 .gitignore
@@ -0,0 +1 @@
+target
23 .project
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>jplurk-oauth</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.maven.ide.eclipse.maven2Builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.maven.ide.eclipse.maven2Nature</nature>
+ </natures>
+</projectDescription>
6 .settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,6 @@
+#Sun Sep 11 22:46:20 CST 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
+org.eclipse.jdt.core.compiler.source=1.5
8 .settings/org.maven.ide.eclipse.prefs
@@ -0,0 +1,8 @@
+#Sun Sep 11 23:23:35 CST 2011
+activeProfiles=
+eclipse.preferences.version=1
+fullBuildGoals=process-test-resources
+resolveWorkspaceProjects=true
+resourceFilterGoals=process-resources resources\:testResources
+skipCompilerPlugin=true
+version=1
40 pom.xml
@@ -0,0 +1,40 @@
+<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/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>com.google.jplurk</groupId>
+ <artifactId>jplurk-oauth</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <packaging>jar</packaging>
+
+ <name>jplurk-oauth</name>
+ <url>http://maven.apache.org</url>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.scribe</groupId>
+ <artifactId>scribe</artifactId>
+ <version>1.2.2</version>
+ </dependency>
+ <dependency>
+ <groupId>org.json</groupId>
+ <artifactId>json</artifactId>
+ <version>20080701</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>1.1.1</version>
+ </dependency>
+ </dependencies>
+</project>
35 src/main/java/com/google/jplurk_oauth/Ids.java
@@ -0,0 +1,35 @@
+package com.google.jplurk_oauth;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Ids {
+
+ private List<Integer> idList = new ArrayList<Integer>();
+
+ public Ids() {
+ }
+
+ public Ids(List<Integer> idList) {
+ if(idList != null && !idList.isEmpty())
+ {
+ this.idList.addAll(idList);
+ }
+ }
+
+ public String formatted() {
+ if (!idList.isEmpty()) {
+ StringBuffer buffer = new StringBuffer();
+ for (Integer id : idList) {
+ buffer.append(id);
+ buffer.append(",");
+ }
+ if (buffer.length() > 0) {
+ buffer.setLength(buffer.length() - 1);
+ return buffer.toString();
+ }
+ }
+ return "[]";
+ }
+
+}
25 src/main/java/com/google/jplurk_oauth/Offset.java
@@ -0,0 +1,25 @@
+package com.google.jplurk_oauth;
+
+import java.util.Calendar;
+
+import com.google.jplurk_oauth.skeleton.DateTime;
+
+public class Offset {
+
+ private DateTime dateTime;
+
+ public Offset() {
+ dateTime = DateTime.create(Calendar.getInstance());
+ }
+
+ public Offset(long offsetInMs)
+ {
+ dateTime = DateTime.create(offsetInMs);
+ }
+
+ public String formatted() {
+ return dateTime.toTimeOffset();
+ }
+
+
+}
94 src/main/java/com/google/jplurk_oauth/Qualifier.java
@@ -0,0 +1,94 @@
+package com.google.jplurk_oauth;
+
+/**
+ * Handle Qualifier of Message
+ */
+public enum Qualifier {
+
+ // ":" 無. 同 "QUALIFIER_FREESTYLE".
+ NULL(":"),
+
+ // "wants" 想要
+ WANTS("wants"),
+
+ // "needs" 需要
+ NEEDS("needs"),
+
+ // "says" 說
+ SAYS("says"),
+
+ // "asks" 問
+ ASKS("asks"),
+
+ // "wonders" 好奇
+ WONDERS("wonders"),
+
+ // "freestyle" 自由發揮
+ FREESTYLE("freestyle"),
+
+ // "is" 正在
+ IS("is"),
+
+ // "shares" 推
+ SHARES("shares"),
+
+ // "will" 打算
+ WILL("will"),
+
+ // "feels" 覺得
+ FEELS("feels"),
+
+ // "wishes" 希望
+ WISHES("wishes"),
+
+ // "likes" 喜歡
+ LIKES("likes"),
+
+ // "loves" 愛
+ LOVES("loves"),
+
+ // "hopes" 希望
+ HOPES("hopes"),
+
+ // "has" 已經
+ HAS("has"),
+
+ // "was" 曾經
+ WAS("was"),
+
+ // "thinks" 想
+ THINKS("thinks"),
+
+ // "hates" 討厭
+ HATES("hates"),
+
+ // "gives" 給
+ GIVES("gives")
+ ;
+
+ private String qualifier;
+
+ Qualifier(String qualifier){
+ this.qualifier = qualifier;
+ }
+
+ /**
+ * Input Qualifier String, then it will select correct Qualifier.
+ * @param qualifier Qualifier String
+ * @return
+ */
+ public static Qualifier fromString(String qualifier){
+ for (Qualifier q : Qualifier.values()) {
+ if(q.toString().equals(qualifier)){
+ return q;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return qualifier;
+ }
+
+}
25 src/main/java/com/google/jplurk_oauth/example/Example.java
@@ -0,0 +1,25 @@
+package com.google.jplurk_oauth.example;
+
+import java.util.Properties;
+
+import org.json.JSONObject;
+
+import com.google.jplurk_oauth.Offset;
+import com.google.jplurk_oauth.Qualifier;
+import com.google.jplurk_oauth.module.Polling;
+import com.google.jplurk_oauth.module.Timeline;
+import com.google.jplurk_oauth.skeleton.PlurkOAuth;
+import com.google.jplurk_oauth.skeleton.RequestException;
+
+public class Example {
+ public static void main(String[] args) throws RequestException {
+ Properties prop = System.getProperties();
+
+ /* create oauth config */
+ PlurkOAuth auth = new PlurkOAuth(
+ prop.getProperty("apikey"), prop.getProperty("apisecret"),
+ prop.getProperty("token"), prop.getProperty("tokensecret"));
+
+ auth.using(Timeline.class).plurkAdd("Hello JPlurk-OAuth", Qualifier.SAYS);
+ }
+}
29 src/main/java/com/google/jplurk_oauth/module/Polling.java
@@ -0,0 +1,29 @@
+package com.google.jplurk_oauth.module;
+
+import org.json.JSONObject;
+
+import com.google.jplurk_oauth.Offset;
+import com.google.jplurk_oauth.skeleton.AbstractModule;
+import com.google.jplurk_oauth.skeleton.Args;
+import com.google.jplurk_oauth.skeleton.HttpMethod;
+import com.google.jplurk_oauth.skeleton.RequestException;
+
+public class Polling extends AbstractModule {
+
+ public JSONObject getPlurks(Offset offset) throws RequestException {
+ return requestBy("getPlurks")
+ .with(new Args().add("offset", offset.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject getUnreadCount() throws RequestException {
+ return requestBy("getUnreadCount")
+ .withoutArgs().in(HttpMethod.GET).thenJsonObject();
+ }
+
+ @Override
+ protected String getModulePath() {
+ return "/APP/Polling";
+ }
+
+}
39 src/main/java/com/google/jplurk_oauth/module/Responses.java
@@ -0,0 +1,39 @@
+package com.google.jplurk_oauth.module;
+
+import org.json.JSONObject;
+
+import com.google.jplurk_oauth.Qualifier;
+import com.google.jplurk_oauth.skeleton.AbstractModule;
+import com.google.jplurk_oauth.skeleton.Args;
+import com.google.jplurk_oauth.skeleton.HttpMethod;
+import com.google.jplurk_oauth.skeleton.RequestException;
+
+public class Responses extends AbstractModule {
+
+ public JSONObject get(Long plurkId) throws RequestException {
+ return requestBy("get")
+ .with(new Args().add("plurk_id", plurkId))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject responseAdd(Long plurkId, String content, Qualifier qualifier)
+ throws RequestException {
+ return requestBy("responseAdd")
+ .with(new Args().add("plurk_id", plurkId)
+ .add("content", content).add("qualifier", qualifier.toString()))
+ .in(HttpMethod.GET)
+ .thenJsonObject();
+ }
+
+ public JSONObject responseDelete(Long responseId, Long plurkId) throws RequestException {
+ return requestBy("responseDelete")
+ .with(new Args().add("response_id", responseId).add("plurk_id", plurkId))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ @Override
+ protected String getModulePath() {
+ return "/APP/Responses";
+ }
+
+}
121 src/main/java/com/google/jplurk_oauth/module/Timeline.java
@@ -0,0 +1,121 @@
+package com.google.jplurk_oauth.module;
+
+import java.io.File;
+
+import org.json.JSONObject;
+
+import com.google.jplurk_oauth.Ids;
+import com.google.jplurk_oauth.Qualifier;
+import com.google.jplurk_oauth.skeleton.AbstractModule;
+import com.google.jplurk_oauth.skeleton.Args;
+import com.google.jplurk_oauth.skeleton.HttpMethod;
+import com.google.jplurk_oauth.skeleton.RequestException;
+
+public class Timeline extends AbstractModule {
+
+ public JSONObject getPlurk(Long plurkId) throws RequestException {
+ return getPlurk(plurkId, null);
+ }
+
+ public JSONObject getPlurk(Long plurkId, Args optional) throws RequestException {
+ return requestBy("getPlurk")
+ .with(new Args().add("plurk_id", plurkId).add(optional))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject getUnreadPlurks() throws RequestException {
+ return getUnreadPlurks(null);
+ }
+
+ public JSONObject getUnreadPlurks(Args optional) throws RequestException {
+ return requestBy("getUnreadPlurks")
+ .with(new Args().add(optional)).in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject getPublicPlurks(Long userId) throws RequestException {
+ return getPublicPlurks(userId);
+ }
+
+ public JSONObject getPublicPlurks(Long userId, Args optional) throws RequestException {
+ return requestBy("getPublicPlurks")
+ .with(new Args().add("user_id", userId).add(optional))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject plurkAdd(String content, Qualifier qualifier) throws RequestException {
+ return plurkAdd(content, qualifier, null);
+ }
+
+ public JSONObject plurkAdd(String content, Qualifier qualifier, Args optional) throws RequestException {
+ return requestBy("plurkAdd")
+ .with(new Args().add("content", content)
+ .add("qualifier", qualifier.toString()).add(optional))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject plurkDelete(Long plurkId) throws RequestException {
+ return requestBy("plurkDelete")
+ .with(new Args().add("plurk_id", plurkId))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject plurkEdit(Long plurkId, String content) throws RequestException {
+ return requestBy("plurkEdit")
+ .with(new Args().add("plurk_id", plurkId).add("content", content))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject mutePlurks(Ids ids) throws RequestException {
+ return requestBy("mutePlurks")
+ .with(new Args().add("ids", ids.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject unmutePlurks(Ids ids) throws RequestException {
+ return requestBy("unmutePlurks")
+ .with(new Args().add("ids", ids.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject favoritePlurks(Ids ids) throws RequestException {
+ return requestBy("favoritePlurks")
+ .with(new Args().add("ids", ids.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject unfavoritePlurks(Ids ids) throws RequestException {
+ return requestBy("unfavoritePlurks")
+ .with(new Args().add("ids", ids.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject replurk(Ids ids) throws RequestException {
+ return requestBy("replurk")
+ .with(new Args().add("ids", ids.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject unreplurk(Ids ids) throws RequestException {
+ return requestBy("unreplurk")
+ .with(new Args().add("ids", ids.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject markAsRead(Ids ids) throws RequestException {
+ return requestBy("markAsRead")
+ .with(new Args().add("ids", ids.formatted()))
+ .in(HttpMethod.GET).thenJsonObject();
+ }
+
+ public JSONObject uploadPicture(File file) throws RequestException {
+ /* TODO ... */
+ throw new UnsupportedOperationException();
+ }
+
+
+ @Override
+ protected String getModulePath() {
+ return "/APP/Timeline";
+ }
+
+}
21 src/main/java/com/google/jplurk_oauth/module/Users.java
@@ -0,0 +1,21 @@
+package com.google.jplurk_oauth.module;
+
+import org.json.JSONObject;
+
+import com.google.jplurk_oauth.skeleton.AbstractModule;
+import com.google.jplurk_oauth.skeleton.HttpMethod;
+import com.google.jplurk_oauth.skeleton.RequestException;
+
+public class Users extends AbstractModule {
+
+ public JSONObject getKarmaStats() throws RequestException{
+ return requestBy("getKarmaStats")
+ .withoutArgs().in(HttpMethod.GET).thenJsonObject();
+ }
+
+ @Override
+ protected String getModulePath() {
+ return "/APP/Users";
+ }
+
+}
18 src/main/java/com/google/jplurk_oauth/skeleton/AbstractModule.java
@@ -0,0 +1,18 @@
+package com.google.jplurk_oauth.skeleton;
+
+public abstract class AbstractModule {
+
+ public static final String API_URL_PREFIX = "http://www.plurk.com";
+
+ private PlurkOAuth plurkOAuth;
+
+ public void setPlurkOAuth(PlurkOAuth auth) {
+ this.plurkOAuth = auth;
+ }
+
+ protected abstract String getModulePath();
+
+ protected RequestBuilder requestBy(String url) {
+ return new RequestBuilder(plurkOAuth, API_URL_PREFIX + getModulePath() + "/" + url);
+ }
+}
63 src/main/java/com/google/jplurk_oauth/skeleton/Args.java
@@ -0,0 +1,63 @@
+package com.google.jplurk_oauth.skeleton;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class Args {
+
+ Map<String, String> map;
+
+ private String key;
+ private String value;
+
+ public Args() {
+ this(new HashMap<String, String>());
+ }
+
+ public Args(Map<String, String> map) {
+ this.map = map;
+ }
+
+ public Args name(String key) {
+ this.key = key;
+ checkAndPush();
+ return this;
+ }
+
+ public Args value(int value) {
+ return value(Integer.toString(value));
+ }
+
+ public Args value(String value) {
+ this.value = value;
+ checkAndPush();
+ return this;
+ }
+
+ public Args add(String key, String value){
+ return name(key).value(value);
+ }
+
+ public Args add(String key, Object value){
+ return name(key).value("" + value);
+ }
+
+ private void checkAndPush() {
+ if (key != null && value != null) {
+ map.put(key, value);
+ this.key = null;
+ this.value = null;
+ }
+ }
+
+ public Map<String, String> getMap() {
+ return map;
+ }
+
+ public Args add(Args args) {
+ if (args != null) {
+ map.putAll(args.getMap());
+ }
+ return this;
+ }
+}
183 src/main/java/com/google/jplurk_oauth/skeleton/DateTime.java
@@ -0,0 +1,183 @@
+package com.google.jplurk_oauth.skeleton;
+
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class DateTime {
+
+ private static Log logger = LogFactory.getLog(DateTime.class);
+
+ public final static SimpleDateFormat OFFSET_OUTPUT_FORMAT = createFormat("yyyy-M-d'T'HH:mm:ss");
+ public final static SimpleDateFormat JS_INPUT_FORMAT = createFormat("E, dd MMM yyyy HH:mm:ss z");
+ public final static SimpleDateFormat BIRTHDAY_FORMAT = createFormat("yyyy-MM-dd");
+
+ private static SimpleDateFormat createFormat(String pattern){
+ SimpleDateFormat fmt = new SimpleDateFormat(pattern, Locale.US);
+ fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
+ return fmt;
+ }
+
+ protected static class TimeUtil {
+ public static void setYear(Calendar time, int year) {
+ time.set(Calendar.YEAR, year);
+ }
+
+ public static void setMonth(Calendar time, int month) {
+ time.set(Calendar.MONTH, month -1);
+ }
+
+ public static void setDate(Calendar time, int date) {
+ time.set(Calendar.DATE, date);
+ }
+
+ public static void setHour(Calendar time, int hour) {
+ time.set(Calendar.HOUR_OF_DAY, hour);
+ }
+
+ public static void setMinute(Calendar time, int minute) {
+ time.set(Calendar.MINUTE, minute);
+ }
+ public static void setSecond(Calendar time, int second) {
+ time.set(Calendar.SECOND, second);
+ }
+ }
+
+ private Calendar time = createGmtCalendar();
+
+ private static Calendar createGmtCalendar() {
+ return Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ }
+
+ private DateTime(int year, int month, int day) {
+ time.clear();
+ TimeUtil.setYear(time, year);
+ TimeUtil.setMonth(time, month);
+ TimeUtil.setDate(time, day);
+ }
+
+ private DateTime(int year, int month, int day, int hour, int minute, int second) {
+ this(year, month, day);
+ TimeUtil.setHour(time, hour);
+ TimeUtil.setMinute(time, minute);
+ TimeUtil.setSecond(time, second);
+ }
+
+ private DateTime(Calendar time){
+ this.time = time;
+ }
+
+ private DateTime(Date time){
+ this.time.setTime(time);
+ }
+
+ public static DateTime create(long offset) {
+ Calendar calendar = createGmtCalendar();
+ Date date = new Date(calendar.getTimeInMillis() + offset);
+ calendar.setTime(date);
+ return create(calendar);
+ }
+
+ public static DateTime create(Calendar calendar){
+ logger.info("create DateTime from Calendar: " + calendar.getTime());
+ return new DateTime(calendar);
+ }
+
+ public static DateTime create(String offset) {
+ DateTime dateTime = null;
+ Date date = null;
+
+ try {
+ date = OFFSET_OUTPUT_FORMAT.parse(offset);
+ logger.info("create date time from[" + offset + "] by: "
+ + OFFSET_OUTPUT_FORMAT);
+ logger.info("date is " + date);
+ } catch (Exception e) {
+ logger.debug(e.getMessage());
+ }
+
+ if (date == null) {
+ try {
+ date = JS_INPUT_FORMAT.parse(offset);
+ logger.info("create date time from[" + offset + "] by: "
+ + JS_INPUT_FORMAT);
+ logger.info("date is " + date);
+ } catch (Exception e) {
+ logger.debug(e.getMessage());
+ }
+ }
+
+ if (date == null) {
+ logger.warn("cannot parse date string: " + offset
+ + ". we will use now instead");
+ return DateTime.now();
+ }
+
+ try {
+ dateTime = new DateTime(date);
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ dateTime = now();
+ }
+
+ logger.info("create date time from string: " + dateTime.toTimeOffset());
+ return dateTime;
+ }
+
+ public static DateTime create(int year, int month, int day) {
+ return new DateTime(year, month, day);
+ }
+
+ public static DateTime create(int year, int month, int day, int hour,
+ int minute, int second) {
+ return new DateTime(year, month, day, hour, minute, second);
+ }
+
+ public static DateTime now() {
+ return create(createGmtCalendar());
+ }
+
+ protected String birthday() {
+ return BIRTHDAY_FORMAT.format(time.getTime());
+ }
+
+ public String toTimeOffset() {
+ return OFFSET_OUTPUT_FORMAT.format(toCalendar().getTime());
+ }
+
+ public Calendar toCalendar() {
+ return time;
+ }
+
+ public static boolean isValidTimeOffset(String offset) {
+ try {
+ OFFSET_OUTPUT_FORMAT.parse(offset);
+ } catch (Exception e) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return time.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == null) {
+ return false;
+ }
+ if (other instanceof DateTime) {
+ DateTime time = (DateTime) other;
+ return time.toCalendar().equals(((DateTime) other).toCalendar());
+ }
+ return false;
+ }
+
+}
5 src/main/java/com/google/jplurk_oauth/skeleton/HttpMethod.java
@@ -0,0 +1,5 @@
+package com.google.jplurk_oauth.skeleton;
+
+public enum HttpMethod {
+ GET, POST, PUT, DELETE
+}
93 src/main/java/com/google/jplurk_oauth/skeleton/PlurkOAuth.java
@@ -0,0 +1,93 @@
+package com.google.jplurk_oauth.skeleton;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+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;
+
+
+public class PlurkOAuth {
+
+ private static Log log = LogFactory.getLog(PlurkOAuth.class);
+
+ @SuppressWarnings("serial")
+ static Map<HttpMethod, Verb> actionMap = new HashMap<HttpMethod, Verb>() {
+ {
+ put(HttpMethod.DELETE, Verb.DELETE);
+ put(HttpMethod.GET, Verb.GET);
+ put(HttpMethod.POST, Verb.POST);
+ put(HttpMethod.PUT, Verb.PUT);
+ }
+ };
+
+ private OAuthService service;
+ private Token token;
+
+ public PlurkOAuth(String apiKey, String apiSecret, String token, String tokenSecret) {
+ super();
+ this.service = new ServiceBuilder()
+ .provider(PlurkOAuthConfig.class)
+ .apiKey(apiKey)
+ .apiSecret(apiSecret).build();
+ this.token = new Token(token, tokenSecret);
+ }
+
+ public String sendRequest(String url, Args args, HttpMethod method) throws RequestException {
+ OAuthRequest request = new OAuthRequest(actionMap.get(method), url);
+ log.info("args: " + args.map);
+ if(HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method))
+ {
+ addBodyParams(request, args);
+ }
+ else
+ {
+ addQueryStrings(request, args);
+ }
+
+ service.signRequest(token, request);
+ Response response = request.send();
+ if(response.getCode() != 200)
+ {
+ throw new RequestException(String.format("http status %d, body: %s", response.getCode(), response.getBody()));
+ }
+ return response.getBody();
+ }
+
+ private void addBodyParams(OAuthRequest request, Args args) {
+ for (Entry<String, String> e : args.map.entrySet()) {
+ request.addBodyParameter(e.getKey(), e.getValue());
+ }
+ }
+
+ private void addQueryStrings(OAuthRequest request, Args args) {
+
+ for (Entry<String, String> e : args.map.entrySet()) {
+ request.addQuerystringParameter(e.getKey(), e.getValue());
+ }
+ }
+
+ public <T> T using(Class<T> clazz) {
+ try {
+ T instance = clazz.newInstance();
+ if (instance instanceof AbstractModule) {
+ AbstractModule module = (AbstractModule) instance;
+ module.setPlurkOAuth(this);
+ return instance;
+ }
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+}
27 src/main/java/com/google/jplurk_oauth/skeleton/PlurkOAuthConfig.java
@@ -0,0 +1,27 @@
+package com.google.jplurk_oauth.skeleton;
+
+import org.scribe.builder.api.DefaultApi10a;
+import org.scribe.model.Token;
+
+public class PlurkOAuthConfig extends DefaultApi10a
+{
+
+ @Override
+ public String getRequestTokenEndpoint()
+ {
+ return "http://www.plurk.com/OAuth/request_token";
+ }
+
+ @Override
+ public String getAccessTokenEndpoint()
+ {
+ return "http://www.plurk.com/OAuth/access_token";
+ }
+
+ @Override
+ public String getAuthorizationUrl(Token requestToken)
+ {
+ return String.format("http://www.plurk.com/OAuth/authorize?oauth_token=%s", requestToken.getToken());
+ }
+
+}
54 src/main/java/com/google/jplurk_oauth/skeleton/RequestBuilder.java
@@ -0,0 +1,54 @@
+package com.google.jplurk_oauth.skeleton;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.json.JSONObject;
+
+public class RequestBuilder {
+
+ private static Log log = LogFactory.getLog(RequestBuilder.class);
+ private PlurkOAuth auth;
+ private String url;
+ private HttpMethod method;
+ private Args args;
+
+ public RequestBuilder(PlurkOAuth plurkOAuth, String url) {
+ this.auth = plurkOAuth;
+ this.url = url;
+ }
+
+ public RequestBuilder with(Args args) {
+ this.args = args;
+ return this;
+ }
+
+ protected String result() throws RequestException {
+ validate();
+ return auth.sendRequest(url, args, method);
+ }
+
+ public boolean validate() {
+ if(url != null && args != null && method != null)
+ return true;
+ throw new IllegalStateException("url, args, method should all have values.");
+ }
+
+ public RequestBuilder in(HttpMethod method) {
+ this.method = method;
+ return this;
+ }
+
+ public JSONObject thenJsonObject() throws RequestException {
+ try {
+ return new JSONObject(result());
+ } catch (Exception e) {
+ throw new RequestException(e);
+ }
+
+ }
+
+ public RequestBuilder withoutArgs() {
+ return with(new Args());
+ }
+
+}
14 src/main/java/com/google/jplurk_oauth/skeleton/RequestException.java
@@ -0,0 +1,14 @@
+package com.google.jplurk_oauth.skeleton;
+
+@SuppressWarnings("serial")
+public class RequestException extends Exception {
+
+ public RequestException(Exception e) {
+ super(e);
+ }
+
+ public RequestException(String message) {
+ super(message);
+ }
+
+}

0 comments on commit 3787873

Please sign in to comment.
Something went wrong with that request. Please try again.