Skip to content

Commit 9f9ddea

Browse files
author
Eugen
committed
Merge pull request eugenp#203 from Doha2012/master
add reddit resubmit inactive post
2 parents ebc8333 + 2a54d9d commit 9f9ddea

File tree

7 files changed

+125
-4
lines changed

7 files changed

+125
-4
lines changed

spring-security-oauth/src/main/java/org/baeldung/config/SessionListener.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public class SessionListener implements HttpSessionListener {
1313
@Override
1414
public void sessionCreated(HttpSessionEvent event) {
1515
logger.info("==== Session is created ====");
16-
event.getSession().setMaxInactiveInterval(1 * 60);
16+
event.getSession().setMaxInactiveInterval(30 * 60);
1717
event.getSession().setAttribute("PREDICTION_FEATURE", MyFeatures.PREDICTION_FEATURE);
1818
}
1919

spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ public OAuth2ProtectedResourceDetails reddit() {
127127
details.setAccessTokenUri(accessTokenUri);
128128
details.setUserAuthorizationUri(userAuthorizationUri);
129129
details.setTokenName("oauth_token");
130-
details.setScope(Arrays.asList("identity", "read", "submit"));
130+
details.setScope(Arrays.asList("identity", "read", "submit", "edit"));
131131
details.setGrantType("authorization_code");
132132
details.setPreEstablishedRedirectUri("http://localhost:8080/spring-security-oauth/login");
133133
details.setUseCurrentUri(false);

spring-security-oauth/src/main/java/org/baeldung/persistence/dao/PostRepository.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,6 @@ public interface PostRepository extends JpaRepository<Post, Long> {
1212
List<Post> findBySubmissionDateBeforeAndIsSent(Date date, boolean isSent);
1313

1414
List<Post> findByUser(User user);
15+
16+
List<Post> findByRedditIDNotNullAndNoOfAttemptsGreaterThan(int attempts);
1517
}

spring-security-oauth/src/main/java/org/baeldung/persistence/model/Post.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ public class Post {
3535

3636
private String submissionResponse;
3737

38+
private String redditID;
39+
40+
private int noOfAttempts;
41+
42+
private int timeInterval;
43+
44+
private int minScoreRequired;
45+
3846
@ManyToOne
3947
@JoinColumn(name = "user_id", nullable = false)
4048
private User user;
@@ -115,6 +123,38 @@ public void setSubmissionResponse(String submissionResponse) {
115123
this.submissionResponse = submissionResponse;
116124
}
117125

126+
public String getRedditID() {
127+
return redditID;
128+
}
129+
130+
public void setRedditID(String redditID) {
131+
this.redditID = redditID;
132+
}
133+
134+
public int getNoOfAttempts() {
135+
return noOfAttempts;
136+
}
137+
138+
public void setNoOfAttempts(int noOfAttempts) {
139+
this.noOfAttempts = noOfAttempts;
140+
}
141+
142+
public int getTimeInterval() {
143+
return timeInterval;
144+
}
145+
146+
public void setTimeInterval(int timeInterval) {
147+
this.timeInterval = timeInterval;
148+
}
149+
150+
public int getMinScoreRequired() {
151+
return minScoreRequired;
152+
}
153+
154+
public void setMinScoreRequired(int minScoreRequired) {
155+
this.minScoreRequired = minScoreRequired;
156+
}
157+
118158
@Override
119159
public String toString() {
120160
return "Post [title=" + title + ", subreddit=" + subreddit + ", url=" + url + ", submissionDate=" + submissionDate + ", user=" + user + "]";

spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ public final String schedule(final Model model, @RequestParam final Map<String,
114114
post.setTitle(formParams.get("title"));
115115
post.setSubreddit(formParams.get("sr"));
116116
post.setUrl(formParams.get("url"));
117+
post.setNoOfAttempts(Integer.parseInt(formParams.get("attempt")));
118+
post.setTimeInterval(Integer.parseInt(formParams.get("interval")));
119+
post.setMinScoreRequired(Integer.parseInt(formParams.get("score")));
120+
117121
if (formParams.containsKey("sendreplies")) {
118122
post.setSendReplies(true);
119123
}

spring-security-oauth/src/main/java/org/baeldung/web/schedule/ScheduledTasks.java

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.Arrays;
44
import java.util.Date;
55
import java.util.List;
6+
import java.util.concurrent.TimeUnit;
67

78
import org.baeldung.persistence.dao.PostRepository;
89
import org.baeldung.persistence.model.Post;
@@ -38,6 +39,12 @@ public void reportCurrentTime() {
3839
for (final Post post : posts) {
3940
submitPost(post);
4041
}
42+
43+
final List<Post> submitted = postReopsitory.findByRedditIDNotNullAndNoOfAttemptsGreaterThan(0);
44+
logger.info(submitted.size() + " Posts to check their score");
45+
for (final Post post : submitted) {
46+
checkIfNeedResubmit(post);
47+
}
4148
}
4249

4350
private void submitPost(final Post post) {
@@ -72,10 +79,16 @@ private void submitPostInternal(final Post post) {
7279

7380
logger.info("Submit link with these parameters: " + param.entrySet());
7481
final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/submit", param, JsonNode.class);
82+
parseResponse(node, post);
83+
}
84+
85+
private void parseResponse(JsonNode node, Post post) {
7586
final JsonNode errorNode = node.get("json").get("errors").get(0);
7687
if (errorNode == null) {
7788
post.setSent(true);
7889
post.setSubmissionResponse("Successfully sent");
90+
post.setRedditID(node.get("json").get("data").get("id").asText());
91+
post.setNoOfAttempts(post.getNoOfAttempts() - 1);
7992
postReopsitory.save(post);
8093
logger.info("Successfully sent " + post.toString());
8194
} else {
@@ -85,7 +98,42 @@ private void submitPostInternal(final Post post) {
8598
}
8699
}
87100

101+
private int getPostScore(String redditId) {
102+
final JsonNode node = redditRestTemplate.getForObject("https://oauth.reddit.com/api/info?id=t3_" + redditId, JsonNode.class);
103+
logger.info(node.toString());
104+
final int score = node.get("data").get("children").get(0).get("data").get("score").asInt();
105+
logger.info("post score = " + score);
106+
return score;
107+
}
108+
109+
private void deletePost(String redditId) {
110+
final MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
111+
param.add("id", "t3_" + redditId);
112+
final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/del.json", param, JsonNode.class);
113+
logger.info(node.toString());
114+
}
115+
116+
private void checkIfNeedResubmit(Post post) {
117+
final long currentTime = new Date().getTime();
118+
final long interval = currentTime - post.getSubmissionDate().getTime();
119+
final long intervalInMinutes = TimeUnit.MINUTES.convert(interval, TimeUnit.MILLISECONDS);
120+
if (intervalInMinutes > post.getTimeInterval()) {
121+
final int score = getPostScore(post.getRedditID());
122+
if (score < post.getMinScoreRequired()) {
123+
deletePost(post.getRedditID());
124+
post.setRedditID(null);
125+
post.setSubmissionDate(new Date(currentTime + interval));
126+
post.setSent(false);
127+
post.setSubmissionResponse("Not sent yet");
128+
postReopsitory.save(post);
129+
} else {
130+
post.setNoOfAttempts(0);
131+
postReopsitory.save(post);
132+
}
133+
}
134+
}
135+
88136
public void setRedditRestTemplate(final OAuth2RestTemplate redditRestTemplate) {
89137
this.redditRestTemplate = redditRestTemplate;
90138
}
91-
}
139+
}

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
99
<link rel="stylesheet" href="<c:url value="/resources/datetime-picker.css" />">
1010
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
11+
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
1112
<script src="<c:url value="/resources/datetime-picker.js" />"></script>
1213
<script src="<c:url value="/resources/validator.js" />"></script>
1314
<style type="text/css">
@@ -44,6 +45,31 @@ border-color: #ddd;
4445
<span class="col-sm-9"><input name="sr" placeholder="Subreddit (e.g. kitten)" class="form-control" required data-minlength="3"/></span>
4546
</div>
4647
<br><br>
48+
<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>
58+
</span>
59+
<span class="col-sm-3">Time interval &nbsp;&nbsp;
60+
<select name="interval">
61+
<option value="0" selected>None</option>
62+
<option value="45">45 minutes</option>
63+
<option value="60">1 hour</option>
64+
<option value="120">2 hours</option>
65+
</select>
66+
</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+
</span>
71+
</div>
72+
<br><br>
4773
<div >
4874
<label class="col-sm-3">Send replies to my inbox</label> <span class="col-sm-9"><input type="checkbox" name="sendreplies" value="true"/></span>
4975
</div>
@@ -57,7 +83,8 @@ border-color: #ddd;
5783
});
5884
</script>
5985

60-
<br><br>
86+
<br><br>
87+
6188

6289
<button type="submit" class="btn btn-primary">Schedule</button>
6390
</div>

0 commit comments

Comments
 (0)