Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.github.jreddit.retrieval;
  
  import static com.github.jreddit.utils.restclient.JsonUtils.safeJsonToString;
  
  import java.util.List;
  
 
This class offers the following functionality: 1) Parsing the results of a request into Submission objects (see Submissions.parse()). 2) The ability to get submissions from a subreddit (see Submissions.ofSubreddit()). 3) The ability to search submissions on Reddit (see Submissions.search()). 4) The ability to get submissions of a user (see Submissions.ofUser()).

Author(s):
Omer Elnour
Simon Kassing
 
 public class Submissions implements ActorDriven {

Handle to REST client instance.
 
     private final RestClient restClient;
     private User user;

    
Constructor. Default general actor will be used.

Parameters:
restClient REST client handle
 
     public Submissions(RestClient restClient) {
         this. = restClient;
     }
    
    
Constructor. The actor is the user who will be used to perform the retrieval.

Parameters:
restClient REST Client instance
actor User instance
 
     public Submissions(RestClient restClientUser actor) {
     	this. = restClient;
         this. = actor;
     }
    
    
Switch the current user for the new user who will be used when invoking retrieval requests.

Parameters:
new_actor New user
 
     public void switchActor(User new_actor) {
     	this. = new_actor;
     }
    
    
Parses a JSON feed received from Reddit (URL) into a nice list of Submission objects.

Parameters:
url URL
Returns:
Listing of submissions
 
     public List<Submissionparse(String urlthrows RetrievalFailedExceptionRedditError {
     	
     	// Determine cookie
     	String cookie = ( == null) ? null : .getCookie();
     	
     	// List of submissions
         List<Submissionsubmissions = new LinkedList<Submission>();
         
         // Send request to reddit server via REST client
         Object response = .get(urlcookie).getResponseObject();
         
         if (response instanceof JSONObject) {
         	
 	        JSONObject object = (JSONObjectresponse;
 	        if (object.get("error") != null) {
	        	throw new RedditError("Response contained error code " + object.get("error") + ".");
	        }
	        JSONArray array = (JSONArray) ((JSONObjectobject.get("data")).get("children");
	        // Iterate over the submission results
	        JSONObject data;
	        Submission submission;
	        for (Object anArray : array) {
	            data = (JSONObjectanArray;
	            
	            // Make sure it is of the correct kind
	            String kind = safeJsonToString(data.get("kind"));
	            if (kind.equals(..value())) {
	            	
	            	// Create and add submission
		            data = ((JSONObjectdata.get("data"));
		            submission = new Submission(data);
		            submission.setUser();
		            submissions.add(submission);
	            
	            }
	            
	        }
        
        } else {
        	..println("Cannot cast to JSON Object: '" + response.toString() + "'");
        }
        // Finally return list of submissions 
        return submissions;
        
    }

    
Gets all the submissions of a particular subreddit using the given parameters. The parameters here are in Strings instead of wrapper objects, which allows users to manually adjust the parameters (if the API changes and jReddit is not updated in time yet).

Parameters:
subreddit Name of the reddit (e.g. "funny")
sort Sorting method
count Count at which the submissions are started being numbered
limit Maximum amount of submissions that can be returned (0-100, 25 default (see Reddit API))
after The submission after which needs to be retrieved
before The submission before which needs to be retrieved
show_all Show all (disables filters such as "hide links that I have voted on")
Returns:
The linked list containing submissions
    protected List<SubmissionofSubreddit(String subredditString sortString countString limitString afterString beforeString showthrows RetrievalFailedExceptionRedditError {
    	assert subreddit != null &&  != null;
    	
    	// Encode the reddit name for the URL:
    	try {
			subreddit = URLEncoder.encode(subreddit"ISO-8859-1");
		}
    	
    	// Format parameters
    	String params = "";
    	
    	params = ParamFormatter.addParameter(params"count"count);
    	params = ParamFormatter.addParameter(params"limit"limit);
    	params = ParamFormatter.addParameter(params"after"after);
    	params = ParamFormatter.addParameter(params"before"before);
    	params = ParamFormatter.addParameter(params"show"show);
    	
        // Retrieve submissions from the given URL
        return parse(String.format(.subredditsortparams));
        
    }
    
    
Gets all the submissions of a particular subreddit using the given parameters.

Parameters:
subreddit Name of the reddit (e.g. "funny")
sort Sorting method, hot default
count Count at which the submissions are started being numbered
limit Maximum amount of submissions that can be returned (0-100, 25 default (see Reddit API))
after The submission after which needs to be retrieved
before The submission before which needs to be retrieved
show_all Show all (disables filters such as "hide links that I have voted on")
Returns:
The linked list containing submissions
    public List<SubmissionofSubreddit(String subredditSubmissionSort sortint countint limitSubmission afterSubmission beforeboolean show_allthrows RetrievalFailedExceptionRedditError {
    	
    	if (subreddit == null || subreddit.isEmpty()) {
    		throw new IllegalArgumentException("The subreddit must be defined.");
    	}
    	
    	return ofSubreddit(
    			subreddit
    			(sort != null) ? sort.value() : "hot",
    			String.valueOf(count),
    			String.valueOf(limit),
    			(after != null) ? after.getFullName() : "",
    			(before != null) ? before.getFullName() : "",
    			(show_all) ? "all" : ""	
    	);
    }
    
    
Searches with the given query using the constraints given as parameters. The parameters here are in Strings instead of wrapper objects, which allows users to manually adjust the parameters (if the API changes and jReddit is not updated in time yet).

Parameters:
query The query
syntax The query syntax
sort Search sorting method
time Search time
count Count at which the submissions are started being numbered
limit Maximum amount of submissions that can be returned (0-100, 25 default (see Reddit API))
after The submission after which needs to be retrieved
before The submission before which needs to be retrieved
show_all Show all (disables filters such as "hide links that I have voted on")
Returns:
The linked list containing submissions
    protected List<Submissionsearch(String queryString syntaxString sortString timeString countString limitString afterString beforeString showthrows RetrievalFailedExceptionRedditError {
    	assert query != null &&  != null;
    	
    	// Format parameters
    	String params = "";
    	try {
			params = ParamFormatter.addParameter(params"q", URLEncoder.encode(query"ISO-8859-1"));
		}
    	params = ParamFormatter.addParameter(params"syntax"syntax);
    	params = ParamFormatter.addParameter(params"sort"sort);
    	params = ParamFormatter.addParameter(params"t"time);
    	params = ParamFormatter.addParameter(params"count"count);
    	params = ParamFormatter.addParameter(params"limit"limit);
    	params = ParamFormatter.addParameter(params"after"after);
    	params = ParamFormatter.addParameter(params"before"before);
    	params = ParamFormatter.addParameter(params"show"show);
    	
        // Retrieve submissions from the given URL
        return parse(String.format(.params));
        
    }
    
    
Searches with the given query using the constraints given as parameters.

Parameters:
query The query
syntax The query syntax
sort Search sorting method
time Search time
count Count at which the submissions are started being numbered
limit Maximum amount of submissions that can be returned (0-100, 25 default (see Reddit API))
after The submission after which needs to be retrieved
before The submission before which needs to be retrieved
show_all Show all (disables filters such as "hide links that I have voted on")
Returns:
The linked list containing submissions
    public List<Submissionsearch(String queryQuerySyntax syntaxSearchSort sortTimeSpan timeint countint limitSubmission afterSubmission beforeboolean show_allthrows RetrievalFailedExceptionIllegalArgumentException {
    	
    	if (query == null || query.isEmpty()) {
    		throw new IllegalArgumentException("The query must be defined.");
    	}
    	
    	if (limit < -1 || limit > .) {
    		throw new IllegalArgumentException("The limit needs to be between 0 and 100 (or -1 for default).");
    	}
    	
    	return search(
    			query
    			(syntax != null) ? syntax.value() : "",
    			(sort != null) ? sort.value() : "",
    			(time != null) ? time.value() : "",
    			String.valueOf(count),
    			String.valueOf(limit),
    			(after != null) ? after.getFullName() : "",
    			(before != null) ? before.getFullName() : "",
    			(show_all) ? "all" : ""		
    	);
    }
    
    
Get the submissions of a user. In this variant all parameters are Strings.

Parameters:
username Username of the user you want to retrieve from.
category (Optional, set null/empty if not used) Category in the user overview to retrieve submissions from
sort (Optional, set null/empty if not used) Sorting method.
time (Optional, set null/empty is not used) Time window
count (Optional, set null/empty if not used) Number at which the counter starts
limit (Optional, set null/empty if not used) Integer representing the maximum number of comments to return
after (Optional, set null/empty if not used) After which comment to retrieve
before (Optional, set null/empty if not used) Before which comment to retrieve
show (Optional, set null/empty if not used) Show parameter ('given' is only acceptable value)
Returns:
Comments of a user.
    protected List<SubmissionofUser(String usernameString categoryString sortString countString limitString afterString beforeString showthrows RetrievalFailedExceptionRedditError {
    	
    	// Format parameters
    	String params = "";
    	params = ParamFormatter.addParameter(params"sort"sort);
    	params = ParamFormatter.addParameter(params"count"count);
    	params = ParamFormatter.addParameter(params"limit"limit);
    	params = ParamFormatter.addParameter(params"after"after);
    	params = ParamFormatter.addParameter(params"before"before);
    	params = ParamFormatter.addParameter(params"show"show);
    	
        // Retrieve submissions from the given URL
        return parse(String.format(.usernamecategoryparams));
        
    }
    
    
Get the submissions of a user. In this variant all parameters are Strings.

Parameters:
username Username of the user you want to retrieve from.
category Category in the user overview to retrieve submissions from
sort (Optional, set null if not used) Sorting method.
time (Optional, set null is not used) Time window
count (Optional, set -1 if not used) Number at which the counter starts
limit (Optional, set -1 if not used) Integer representing the maximum number of comments to return
after (Optional, set null if not used) After which comment to retrieve
before (Optional, set null if not used) Before which comment to retrieve
show (Optional, set false if not used) Show parameter ('given' is only acceptable value)
Returns:
Submissions of a user.
    public List<SubmissionofUser(String usernameUserSubmissionsCategory categoryUserOverviewSort sortint countint limitSubmission afterSubmission beforeboolean show_giventhrows RetrievalFailedExceptionIllegalArgumentException {
    	
    	if (username == null || username.isEmpty()) {
    		throw new IllegalArgumentException("The username must be defined.");
    	}
    	if (category == null) {
    		throw new IllegalArgumentException("The category must be defined.");
    	}
    	
    	if (limit < -1 || limit > .) {
    		throw new IllegalArgumentException("The limit needs to be between 0 and 100 (or -1 for default).");
    	}
    	
    	return ofUser(
    			username,
    			(category != null) ? category.value() : "",
    			(sort != null) ? sort.value() : "",
    			String.valueOf(count),
    			String.valueOf(limit),
    			(after != null) ? after.getFullName() : "",
    			(before != null) ? before.getFullName() : "",
    			(show_given) ? "given" : ""		
    	);
    }
New to GrepCode? Check out our FAQ X