Skip to content

Commit 57585f9

Browse files
author
Eugen
committed
Merge pull request eugenp#206 from Doha2012/master
organise code
2 parents 5913b4a + 57bfaae commit 57585f9

File tree

3 files changed

+175
-133
lines changed

3 files changed

+175
-133
lines changed
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
package org.baeldung.persistence.service;
2+
3+
import java.util.Arrays;
4+
import java.util.Date;
5+
import java.util.concurrent.TimeUnit;
6+
7+
import org.baeldung.persistence.dao.PostRepository;
8+
import org.baeldung.persistence.model.Post;
9+
import org.baeldung.persistence.model.User;
10+
import org.baeldung.reddit.util.RedditApiConstants;
11+
import org.slf4j.Logger;
12+
import org.slf4j.LoggerFactory;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.beans.factory.annotation.Qualifier;
15+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
16+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
17+
import org.springframework.security.core.context.SecurityContextHolder;
18+
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
19+
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
20+
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
21+
import org.springframework.stereotype.Service;
22+
import org.springframework.util.LinkedMultiValueMap;
23+
import org.springframework.util.MultiValueMap;
24+
25+
import com.fasterxml.jackson.databind.JsonNode;
26+
27+
@Service
28+
public class RedditService {
29+
30+
@Autowired
31+
@Qualifier("schedulerRedditTemplate")
32+
private OAuth2RestTemplate redditRestTemplate;
33+
34+
@Autowired
35+
private PostRepository postReopsitory;
36+
37+
private final Logger logger = LoggerFactory.getLogger(getClass());
38+
39+
public void submitPost(final Post post) {
40+
try {
41+
submitPostInternal(post);
42+
} catch (final Exception e) {
43+
logger.error("Error occurred while submitting post " + post.toString(), e);
44+
}
45+
}
46+
47+
public int getPostScore(String redditId) {
48+
final JsonNode node = redditRestTemplate.getForObject("https://oauth.reddit.com/api/info?id=t3_" + redditId, JsonNode.class);
49+
logger.info(node.toString());
50+
final int score = node.get("data").get("children").get(0).get("data").get("score").asInt();
51+
logger.info("post score = " + score);
52+
return score;
53+
}
54+
55+
public void deletePost(String redditId) {
56+
final MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
57+
param.add("id", "t3_" + redditId);
58+
final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/del.json", param, JsonNode.class);
59+
logger.info(node.toString());
60+
}
61+
62+
public void checkAndReSubmit(Post post) {
63+
try {
64+
checkAndReSubmitInternal(post);
65+
} catch (final Exception e) {
66+
logger.error("Error occurred while check post " + post.toString(), e);
67+
}
68+
}
69+
70+
// === private methods
71+
72+
private void submitPostInternal(final Post post) {
73+
final User user = post.getUser();
74+
final DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(user.getAccessToken());
75+
token.setRefreshToken(new DefaultOAuth2RefreshToken((user.getRefreshToken())));
76+
token.setExpiration(user.getTokenExpiration());
77+
redditRestTemplate.getOAuth2ClientContext().setAccessToken(token);
78+
//
79+
final UsernamePasswordAuthenticationToken userAuthToken = new UsernamePasswordAuthenticationToken(user.getUsername(), token.getValue(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
80+
SecurityContextHolder.getContext().setAuthentication(userAuthToken);
81+
//
82+
final MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
83+
param.add(RedditApiConstants.TITLE, post.getTitle());
84+
param.add(RedditApiConstants.SR, post.getSubreddit());
85+
param.add(RedditApiConstants.URL, post.getUrl());
86+
param.add(RedditApiConstants.API_TYPE, "json");
87+
param.add(RedditApiConstants.KIND, "link");
88+
param.add(RedditApiConstants.RESUBMIT, "true");
89+
param.add(RedditApiConstants.THEN, "comments");
90+
if (post.isSendReplies()) {
91+
param.add(RedditApiConstants.SENDREPLIES, "true");
92+
}
93+
94+
logger.info("Submit link with these parameters: " + param.entrySet());
95+
final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/submit", param, JsonNode.class);
96+
parseResponse(node, post);
97+
}
98+
99+
private void parseResponse(JsonNode node, Post post) {
100+
final JsonNode errorNode = node.get("json").get("errors").get(0);
101+
if (errorNode == null) {
102+
post.setSent(true);
103+
post.setSubmissionResponse("Successfully sent");
104+
post.setRedditID(node.get("json").get("data").get("id").asText());
105+
post.setNoOfAttempts(post.getNoOfAttempts() - 1);
106+
postReopsitory.save(post);
107+
logger.info("Successfully sent " + post.toString());
108+
} else {
109+
post.setSubmissionResponse(errorNode.toString());
110+
postReopsitory.save(post);
111+
logger.info("Error occurred: " + errorNode.toString() + "while submitting post " + post.toString());
112+
}
113+
}
114+
115+
private void checkAndReSubmitInternal(Post post) {
116+
if (didIntervalPassed(post.getSubmissionDate(), post.getTimeInterval())) {
117+
final int score = getPostScore(post.getRedditID());
118+
if (score < post.getMinScoreRequired()) {
119+
deletePost(post.getRedditID());
120+
resetPost(post);
121+
} else {
122+
post.setNoOfAttempts(0);
123+
postReopsitory.save(post);
124+
}
125+
}
126+
}
127+
128+
private boolean didIntervalPassed(Date submissonDate, int postInterval) {
129+
final long currentTime = new Date().getTime();
130+
final long interval = currentTime - submissonDate.getTime();
131+
final long intervalInMinutes = TimeUnit.MINUTES.convert(interval, TimeUnit.MILLISECONDS);
132+
return intervalInMinutes > postInterval;
133+
}
134+
135+
private void resetPost(Post post) {
136+
long time = new Date().getTime();
137+
time += TimeUnit.MILLISECONDS.convert(post.getTimeInterval(), TimeUnit.MINUTES);
138+
post.setRedditID(null);
139+
post.setSubmissionDate(new Date(time));
140+
post.setSent(false);
141+
post.setSubmissionResponse("Not sent yet");
142+
postReopsitory.save(post);
143+
}
144+
145+
}
Lines changed: 4 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,22 @@
11
package org.baeldung.web.schedule;
22

3-
import java.util.Arrays;
43
import java.util.Date;
54
import java.util.List;
6-
import java.util.concurrent.TimeUnit;
75

86
import org.baeldung.persistence.dao.PostRepository;
97
import org.baeldung.persistence.model.Post;
10-
import org.baeldung.persistence.model.User;
11-
import org.baeldung.reddit.util.RedditApiConstants;
8+
import org.baeldung.persistence.service.RedditService;
129
import org.slf4j.Logger;
1310
import org.slf4j.LoggerFactory;
1411
import org.springframework.beans.factory.annotation.Autowired;
15-
import org.springframework.beans.factory.annotation.Qualifier;
1612
import org.springframework.scheduling.annotation.Scheduled;
17-
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
18-
import org.springframework.security.core.authority.SimpleGrantedAuthority;
19-
import org.springframework.security.core.context.SecurityContextHolder;
20-
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
21-
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
22-
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
2313
import org.springframework.stereotype.Component;
24-
import org.springframework.util.LinkedMultiValueMap;
25-
import org.springframework.util.MultiValueMap;
26-
27-
import com.fasterxml.jackson.databind.JsonNode;
2814

2915
@Component
3016
public class RedditScheduler {
3117

3218
@Autowired
33-
@Qualifier("schedulerRedditTemplate")
34-
private OAuth2RestTemplate redditRestTemplate;
19+
private RedditService service;
3520

3621
@Autowired
3722
private PostRepository postReopsitory;
@@ -43,7 +28,7 @@ public void schedulePosts() {
4328
final List<Post> posts = postReopsitory.findBySubmissionDateBeforeAndIsSent(new Date(), false);
4429
logger.info(posts.size() + " Posts in the queue.");
4530
for (final Post post : posts) {
46-
submitPost(post);
31+
service.submitPost(post);
4732
}
4833
}
4934

@@ -52,105 +37,8 @@ public void checkAndReSubmitPosts() {
5237
final List<Post> submitted = postReopsitory.findByRedditIDNotNullAndNoOfAttemptsGreaterThan(0);
5338
logger.info(submitted.size() + " Posts to check their score");
5439
for (final Post post : submitted) {
55-
checkAndReSubmit(post);
56-
}
57-
}
58-
59-
private void submitPost(final Post post) {
60-
try {
61-
submitPostInternal(post);
62-
} catch (final Exception e) {
63-
logger.error("Error occurred while submitting post " + post.toString(), e);
64-
}
65-
}
66-
67-
private void submitPostInternal(final Post post) {
68-
final User user = post.getUser();
69-
final DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(user.getAccessToken());
70-
token.setRefreshToken(new DefaultOAuth2RefreshToken((user.getRefreshToken())));
71-
token.setExpiration(user.getTokenExpiration());
72-
redditRestTemplate.getOAuth2ClientContext().setAccessToken(token);
73-
//
74-
final UsernamePasswordAuthenticationToken userAuthToken = new UsernamePasswordAuthenticationToken(user.getUsername(), token.getValue(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
75-
SecurityContextHolder.getContext().setAuthentication(userAuthToken);
76-
//
77-
final MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
78-
param.add(RedditApiConstants.TITLE, post.getTitle());
79-
param.add(RedditApiConstants.SR, post.getSubreddit());
80-
param.add(RedditApiConstants.URL, post.getUrl());
81-
param.add(RedditApiConstants.API_TYPE, "json");
82-
param.add(RedditApiConstants.KIND, "link");
83-
param.add(RedditApiConstants.RESUBMIT, "true");
84-
param.add(RedditApiConstants.THEN, "comments");
85-
if (post.isSendReplies()) {
86-
param.add(RedditApiConstants.SENDREPLIES, "true");
87-
}
88-
89-
logger.info("Submit link with these parameters: " + param.entrySet());
90-
final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/submit", param, JsonNode.class);
91-
parseResponse(node, post);
92-
}
93-
94-
private void parseResponse(JsonNode node, Post post) {
95-
final JsonNode errorNode = node.get("json").get("errors").get(0);
96-
if (errorNode == null) {
97-
post.setSent(true);
98-
post.setSubmissionResponse("Successfully sent");
99-
post.setRedditID(node.get("json").get("data").get("id").asText());
100-
post.setNoOfAttempts(post.getNoOfAttempts() - 1);
101-
postReopsitory.save(post);
102-
logger.info("Successfully sent " + post.toString());
103-
} else {
104-
post.setSubmissionResponse(errorNode.toString());
105-
postReopsitory.save(post);
106-
logger.info("Error occurred: " + errorNode.toString() + "while submitting post " + post.toString());
40+
service.checkAndReSubmit(post);
10741
}
10842
}
10943

110-
private int getPostScore(String redditId) {
111-
final JsonNode node = redditRestTemplate.getForObject("https://oauth.reddit.com/api/info?id=t3_" + redditId, JsonNode.class);
112-
logger.info(node.toString());
113-
final int score = node.get("data").get("children").get(0).get("data").get("score").asInt();
114-
logger.info("post score = " + score);
115-
return score;
116-
}
117-
118-
private void deletePost(String redditId) {
119-
final MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
120-
param.add("id", "t3_" + redditId);
121-
final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/del.json", param, JsonNode.class);
122-
logger.info(node.toString());
123-
}
124-
125-
private void checkAndReSubmit(Post post) {
126-
try {
127-
checkAndReSubmitInternal(post);
128-
} catch (final Exception e) {
129-
logger.error("Error occurred while check post " + post.toString(), e);
130-
}
131-
}
132-
133-
private void checkAndReSubmitInternal(Post post) {
134-
final long currentTime = new Date().getTime();
135-
final long interval = currentTime - post.getSubmissionDate().getTime();
136-
final long intervalInMinutes = TimeUnit.MINUTES.convert(interval, TimeUnit.MILLISECONDS);
137-
if (intervalInMinutes > post.getTimeInterval()) {
138-
final int score = getPostScore(post.getRedditID());
139-
if (score < post.getMinScoreRequired()) {
140-
deletePost(post.getRedditID());
141-
post.setRedditID(null);
142-
post.setSubmissionDate(new Date(currentTime + interval));
143-
post.setSent(false);
144-
post.setSubmissionResponse("Not sent yet");
145-
postReopsitory.save(post);
146-
} else {
147-
post.setNoOfAttempts(0);
148-
postReopsitory.save(post);
149-
}
150-
}
151-
}
152-
153-
public void setRedditRestTemplate(final OAuth2RestTemplate redditRestTemplate) {
154-
this.redditRestTemplate = redditRestTemplate;
155-
}
15644
}

spring-security-oauth/src/main/webapp/WEB-INF/jsp/schedulePostForm.jsp

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -45,35 +45,44 @@ border-color: #ddd;
4545
<span class="col-sm-9"><input name="sr" placeholder="Subreddit (e.g. kitten)" class="form-control" required data-minlength="3"/></span>
4646
</div>
4747
<br><br>
48+
<div>
49+
<label class="col-sm-3">Send replies to my inbox</label> <span class="col-sm-9"><input type="checkbox" name="sendreplies" value="true"/></span>
50+
</div>
51+
<br>
52+
<hr/>
53+
<br>
4854
<div class="form-group">
49-
<label class="col-sm-3">Resubmit Settings</label>
50-
<span class="col-sm-3">Number of Attempts &nbsp;&nbsp;
51-
<select name="attempt">
52-
<option value="0" selected>None</option>
53-
<option value="2">2</option>
54-
<option value="3">3</option>
55-
<option value="4">4</option>
56-
<option value="5">5</option>
57-
</select>
55+
<label class="col-sm-3">Resubmit If:</label>
56+
57+
<span class="col-sm-2">Votes didn't exceed </span>
58+
<span class="col-sm-1">
59+
<input type="number" class="form-control input-sm" value="0" name="score" required/>
5860
</span>
59-
<span class="col-sm-3">Time interval &nbsp;&nbsp;
61+
62+
<span class="col-sm-3">within &nbsp;&nbsp;
6063
<select name="interval">
6164
<option value="0" selected>None</option>
6265
<option value="45">45 minutes</option>
6366
<option value="60">1 hour</option>
6467
<option value="120">2 hours</option>
6568
</select>
6669
</span>
67-
<span class="col-sm-1">Min score</span>
68-
<span class="col-sm-2">
69-
<input type="number" class="form-control" value="0" name="score" required/>
70+
71+
<span class="col-sm-3">try resubmitting &nbsp;&nbsp;
72+
<select name="attempt">
73+
<option value="0" selected>No</option>
74+
<option value="2">2</option>
75+
<option value="3">3</option>
76+
<option value="4">4</option>
77+
<option value="5">5</option>
78+
</select>
79+
&nbsp;&nbsp; times.
7080
</span>
81+
82+
7183
</div>
7284
<br><br>
73-
<div >
74-
<label class="col-sm-3">Send replies to my inbox</label> <span class="col-sm-9"><input type="checkbox" name="sendreplies" value="true"/></span>
75-
</div>
76-
<br><br>
85+
7786

7887
<label class="col-sm-3">Submission Date</label>
7988
<span class="col-sm-9"><input type="text" name="date" class="form-control" readonly></span>

0 commit comments

Comments
 (0)