My favorites
▼
|
Sign in
opensosuite
Example OpenSocial container with Blogs and Wikis
Project Home
Downloads
Wiki
Issues
Source
Checkout
Browse
Changes
Source path:
svn
/
trunk
/
components
/
apache_roller
/
src
/
org
/
rollerweblogger
/
SocialRollerTask.java
‹r2
r9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
* Copyright 2009 David M. Johnson.
*
* 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.
*/
package org.rollerweblogger;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.roller.weblogger.WebloggerException;
import org.apache.roller.weblogger.business.UserManager;
import org.apache.roller.weblogger.business.WeblogEntryManager;
import org.apache.roller.weblogger.business.WebloggerFactory;
import org.apache.roller.weblogger.business.runnable.RollerTaskWithLeasing;
import org.apache.roller.weblogger.config.WebloggerConfig;
import org.apache.roller.weblogger.config.WebloggerRuntimeConfig;
import org.apache.roller.weblogger.pojos.User;
import org.apache.roller.weblogger.pojos.WeblogEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.rollerweblogger.restclient.OAuthStrategy;
import org.rollerweblogger.restclient.RestClient;
import org.rollerweblogger.restclient.RestClientImpl;
/**
* Posts activity per blog post for each user who has installed the
* SocialRoller Gadget on some social network somewhere.
*/
public class SocialRollerTask extends RollerTaskWithLeasing {
private static Log log = LogFactory.getLog(SocialRollerTask.class);
class SocialSite {
String consumerKey;
String consumerSecret;
String requestTokenUri;
String authorizeUri;
String accessTokenUri;
String restUri;
}
Map<String, SocialSite> socialSites = new HashMap<String, SocialSite>();
public static class UserJob {
public String userName;
public String siteHandle;
public String profileUri;
public long lastUpdate;
}
// a unique id for this specific task instance
// this is meant to be unique for each client in a clustered environment
private String clientId = null;
// a String description of when to start this task
private String startTimeDesc = "immediate";
// interval at which the task is run, default is once per minute
private int interval = 1;
// lease time given to task lock, default is 30 minutes
private int leaseTime = 30;
public String getName() {
return "ScheduledEntriesTask";
}
public String getClientId() {
return clientId;
}
public Date getStartTime(Date currentTime) {
return getAdjustedTime(currentTime, startTimeDesc);
}
public String getStartTimeDesc() {
return startTimeDesc;
}
public int getInterval() {
return this.interval;
}
public int getLeaseTime() {
return this.leaseTime;
}
public void init() throws WebloggerException {
// get relevant props
Properties props = this.getTaskProperties();
// extract clientId
String client = props.getProperty("clientId");
if(client != null) {
this.clientId = client;
}
// extract start time
String startTimeStr = props.getProperty("startTime");
if(startTimeStr != null) {
this.startTimeDesc = startTimeStr;
}
// extract interval
String intervalStr = props.getProperty("interval");
if(intervalStr != null) {
try {
this.interval = Integer.parseInt(intervalStr);
} catch (NumberFormatException ex) {
log.warn("Invalid interval: "+intervalStr);
}
}
// extract lease time
String leaseTimeStr = props.getProperty("leaseTime");
if(leaseTimeStr != null) {
try {
this.leaseTime = Integer.parseInt(leaseTimeStr);
} catch (NumberFormatException ex) {
log.warn("Invalid leaseTime: "+leaseTimeStr);
}
}
log.debug(String.format(
"Setup with startTime=%s, interval=%d, leastTime=%d",
this.startTimeDesc, this.interval, this.leaseTime));
String sitesFile = WebloggerConfig.getProperty("socialroller.socialsites");
try {
BufferedReader br = new BufferedReader(new FileReader(sitesFile));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject sitesData = new JSONObject(sb.toString());
String[] names = JSONObject.getNames(sitesData);
for (int i=0; i<names.length; i++) {
JSONObject siteData = sitesData.getJSONObject(names[i]);
SocialSite site = new SocialSite();
site.consumerKey = siteData.getString("consumerKey");
site.consumerSecret = siteData.getString("consumerSecret");
site.requestTokenUri = siteData.getString("requestTokenUri");
site.authorizeUri = siteData.getString("authorizeUri");
site.accessTokenUri = siteData.getString("accessTokenUri");
site.restUri = siteData.getString("restUri");
this.socialSites.put(names[i], site);
}
} catch (FileNotFoundException ex) {
log.error("ERROR unable to read socialroller.socialsites file: " + sitesFile, ex);
} catch (IOException ex) {
log.error("ERROR error while reading socialroller.socialsites file: " + sitesFile, ex);
} catch (JSONException ex) {
log.error("ERROR error parsing JSON data in socialroller.socialsites file: " + sitesFile, ex);
}
}
/**
* Execute the task.
*/
public void runTask() {
log.debug("task started");
try {
UserManager umgr =
WebloggerFactory.getWeblogger().getUserManager();
WeblogEntryManager wmgr =
WebloggerFactory.getWeblogger().getWeblogEntryManager();
List<UserJob> jobs = loadUserJobs();
for (UserJob job : jobs) {
Date now = new Date();
Date lastUpdate = new Date(job.lastUpdate);
User user = umgr.getUserByUserName(job.userName);
List<WeblogEntry> latest = (List<WeblogEntry>)wmgr.getWeblogEntries(
null, // website
user, // user
lastUpdate, // startDate
now, // endDate
null, // catName
null, // tags
WeblogEntry.PUBLISHED, // status
null, // text
null, // sortBy
WeblogEntryManager.DESCENDING, // sortOrder
null, // locale
0, 5); // offset, length
postActivities(latest, job, user);
}
saveUserJobs(jobs);
} catch (WebloggerException e) {
log.error("Error getting scheduled entries", e);
} catch(Exception e) {
log.error("Unexpected exception running task", e);
} finally {
// always release
WebloggerFactory.getWeblogger().release();
}
log.debug("task completed");
}
private void postActivities(List<WeblogEntry> latest, UserJob job, User user) {
log.debug(String.format("Posting %d entries for user %s", latest.size(), job.userName));
// first, setup REST client for OAuth
SocialSite site = socialSites.get(job.siteHandle);
OAuthStrategy strategy = new OAuthStrategy(
job.userName, site.consumerKey, site.consumerSecret,
site.requestTokenUri, site.authorizeUri, site.accessTokenUri);
RestClient rest = new RestClientImpl(strategy);
try {
// second, do the OAuth dance
rest.get(site.requestTokenUri, null, null, null);
rest.get(site.authorizeUri, null, null, null);
rest.get(site.accessTokenUri, null, null, null);
} catch (Exception ex) {
log.error("ERROR authorizing for posting activities for user: "
+ job.userName, ex);
return;
}
// finally, loop through user's latest entries and post activity for each
long lastUpdate = job.lastUpdate;
for (WeblogEntry entry : latest) {
JSONObject activityData = new JSONObject();
try {
activityData.put("title", entry.getDisplayTitle());
activityData.put("body", String.format(
"<img src=\"%s/images/feed-icon-12x12.gif\" alt=\"feedicon\" />"
+ " <a href=\"%s\">%s</a> posted <b><a href=\"%s\">%s</a></b>"
+ " on weblog <b>%s</b>",
WebloggerRuntimeConfig.getAbsoluteContextURL(),
job.profileUri,
user.getFullName(),
entry.getPermalink(),
entry.getDisplayTitle(),
entry.getWebsite().getName()));
if (entry.getPubTime().getTime() > lastUpdate) {
// make sure last update is > than most recent pubTime and
// unfortunately MySQL has a 1 second timestamp resolution
lastUpdate = entry.getPubTime().getTime() + 1000;
}
} catch (JSONException ex) {
log.error("ERROR creating JSON data for activity", ex);
}
try {
rest.post(site.restUri + "/activities/" + job.userName + "/@self",
null, null, activityData.toString(), "application/json");
} catch (Exception ex) {
log.error("ERROR posting activity", ex);
}
}
job.lastUpdate = lastUpdate;
}
public static List<UserJob> loadUserJobs() {
List<UserJob> jobs = new ArrayList<UserJob>();
String jobsFile = WebloggerConfig.getProperty("socialroller.userjobs");
try {
BufferedReader br = new BufferedReader(new FileReader(jobsFile));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
JSONObject jobsData = new JSONObject(sb.toString());
JSONArray jobsArray = jobsData.getJSONArray("jobs");
for (int i=0; i<jobsArray.length(); i++) {
JSONObject jobData = jobsArray.getJSONObject(i);
UserJob job = new UserJob();
job.userName = jobData.getString("userName");
job.siteHandle = jobData.getString("siteHandle");
job.profileUri = jobData.getString("profileUri");
job.lastUpdate = jobData.getLong("lastUpdate");
jobs.add(job);
}
log.debug(String.format("Loaded %d user jobs from file %s", jobs.size(), jobsFile));
} catch (FileNotFoundException ex) {
log.info("File socialroller.userjobs not found: " + jobsFile, ex);
} catch (IOException ex) {
log.error("ERROR while reading socialroller.userjobs file: " + jobsFile, ex);
} catch (JSONException ex) {
log.error("ERROR parsing JSON data in socialroller.userjobs file: " + jobsFile, ex);
}
return jobs;
}
public static void saveUserJobs(List<UserJob> jobs) {
String jobsFile = WebloggerConfig.getProperty("socialroller.userjobs");
BufferedWriter bw = null;
try {
JSONObject jobsData = new JSONObject();
JSONArray jobsArray = new JSONArray();
jobsData.put("jobs", jobsArray);
for (UserJob job : jobs) {
JSONObject jobData = new JSONObject();
jobData.put("userName", job.userName);
jobData.put("siteHandle", job.siteHandle);
jobData.put("profileUri", job.profileUri);
jobData.put("lastUpdate", job.lastUpdate);
jobsArray.put(jobData);
}
File file = new File(jobsFile);
if (!file.exists()) file.createNewFile();
bw = new BufferedWriter(new FileWriter(file));
bw.write(jobsData.toString(4));
log.debug(String.format("Saved %d user jobs to file %s", jobs.size(), jobsFile));
} catch (IOException ex) {
log.error("ERROR creating JSON data for socialroller.userjobs file: " + jobsFile, ex);
} catch (JSONException ex) {
log.error("ERROR creating JSON data for socialroller.userjobs file: " + jobsFile, ex);
} finally {
try {
if (bw != null) bw.close();
} catch (IOException ex) {
log.error("ERROR saving socialroller.userjobs file: " + jobsFile, ex);
}
}
}
}
Show details
Hide details
Change log
r6
by snoopdave on Mar 17, 2009
Diff
Correct license header
Go to:
...rweblogger/SocialRollerTask.java
Project members,
sign in
to write a code review
Older revisions
r2
by snoopdave on Mar 17, 2009
Diff
initial commit
All revisions of this file
File info
Size: 13824 bytes, 370 lines
View raw file
Powered by
Google Project Hosting