Refactored and reformatted code to use less static variables

This commit is contained in:
CrushedPixel
2015-04-23 14:09:54 +02:00
parent f22416be2c
commit 0003f040ed
109 changed files with 9037 additions and 10229 deletions

View File

@@ -1,5 +1,12 @@
package eu.crushedpixel.replaymod.api.client;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import eu.crushedpixel.replaymod.api.client.holders.*;
import eu.crushedpixel.replaymod.utils.StreamTools;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -9,143 +16,129 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import eu.crushedpixel.replaymod.api.client.holders.ApiError;
import eu.crushedpixel.replaymod.api.client.holders.AuthKey;
import eu.crushedpixel.replaymod.api.client.holders.Donated;
import eu.crushedpixel.replaymod.api.client.holders.FileInfo;
import eu.crushedpixel.replaymod.api.client.holders.SearchResult;
import eu.crushedpixel.replaymod.api.client.holders.Success;
import eu.crushedpixel.replaymod.api.client.holders.UserFiles;
import eu.crushedpixel.replaymod.utils.StreamTools;
public class ApiClient {
private static Gson gson = new Gson();
private static JsonParser jsonParser = new JsonParser();
private static final Gson gson = new Gson();
private static final JsonParser jsonParser = new JsonParser();
public AuthKey getLogin(String username, String password) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.login);
builder.put("user", username);
builder.put("pw", password);
AuthKey auth = invokeAndReturn(builder, AuthKey.class);
return auth;
}
public AuthKey getLogin(String username, String password) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.login);
builder.put("user", username);
builder.put("pw", password);
AuthKey auth = invokeAndReturn(builder, AuthKey.class);
return auth;
}
public boolean logout(String auth) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.logout);
builder.put("auth", auth);
Success succ = invokeAndReturn(builder, Success.class);
return succ.isSuccess();
}
public boolean logout(String auth) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.logout);
builder.put("auth", auth);
Success succ = invokeAndReturn(builder, Success.class);
return succ.isSuccess();
}
public boolean hasDonated(String uuid) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.check_auth);
builder.put("uuid", uuid);
Donated succ = invokeAndReturn(builder, Donated.class);
return succ.hasDonated();
}
public UserFiles getUserFiles(String auth, String user) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files);
builder.put("auth", auth);
builder.put("user", user);
UserFiles files = invokeAndReturn(builder, UserFiles.class);
return files;
}
public boolean hasDonated(String uuid) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.check_auth);
builder.put("uuid", uuid);
Donated succ = invokeAndReturn(builder, Donated.class);
return succ.hasDonated();
}
public FileInfo[] getFileInfo(String auth, List<Integer> ids) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files);
builder.put("auth", auth);
builder.put("ids", buildListString(ids));
FileInfo[] info = invokeAndReturn(builder, FileInfo[].class);
return info;
}
public FileInfo[] searchFiles(SearchQuery query) throws IOException, ApiException {
StringBuilder sb = new StringBuilder();
public UserFiles getUserFiles(String auth, String user) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files);
builder.put("auth", auth);
builder.put("user", user);
UserFiles files = invokeAndReturn(builder, UserFiles.class);
return files;
}
// build base url
sb.append(QueryBuilder.API_BASE_URL);
sb.append("search");
sb.append(query.buildQuery());
FileInfo[] info = invokeAndReturn(sb.toString(), SearchResult.class).getResults();
return info;
}
public void downloadThumbnail(int file, File target) throws IOException {
QueryBuilder builder = new QueryBuilder(ApiMethods.get_thumbnail);
builder.put("id", file);
URL url = new URL(builder.toString());
FileUtils.copyURLToFile(url, target);
}
public FileInfo[] getFileInfo(String auth, List<Integer> ids) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files);
builder.put("auth", auth);
builder.put("ids", buildListString(ids));
FileInfo[] info = invokeAndReturn(builder, FileInfo[].class);
return info;
}
public void downloadFile(String auth, int file, File target) throws IOException {
QueryBuilder builder = new QueryBuilder(ApiMethods.download_file);
builder.put("auth", auth);
builder.put("id", file);
String url = builder.toString();
URL website = new URL(url);
HttpURLConnection con = (HttpURLConnection)website.openConnection();
InputStream is = con.getInputStream();
public FileInfo[] searchFiles(SearchQuery query) throws IOException, ApiException {
StringBuilder sb = new StringBuilder();
if(con.getResponseCode() == 200) {
Files.copy(is, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
JsonElement element = jsonParser.parse(StreamTools.readStreamtoString(is));
try {
ApiError err = gson.fromJson(element, ApiError.class);
if(err.getDesc() != null) {
throw new ApiException(err);
}
} catch(Exception e) {}
}
}
// build base url
sb.append(QueryBuilder.API_BASE_URL);
sb.append("search");
sb.append(query.buildQuery());
public void rateFile(String auth, int file, boolean like) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.rate_file);
builder.put("auth", auth);
builder.put("id", file);
builder.put("like", like);
invokeAndReturn(builder, Success.class);
}
FileInfo[] info = invokeAndReturn(sb.toString(), SearchResult.class).getResults();
return info;
}
public void removeFile(String auth, int file) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.remove_file);
builder.put("auth", auth);
builder.put("id", file);
invokeAndReturn(builder, Success.class);
}
public void downloadThumbnail(int file, File target) throws IOException {
QueryBuilder builder = new QueryBuilder(ApiMethods.get_thumbnail);
builder.put("id", file);
URL url = new URL(builder.toString());
FileUtils.copyURLToFile(url, target);
}
private <T> T invokeAndReturn(QueryBuilder builder, Class<T> classOfT) throws IOException, ApiException {
return invokeAndReturn(builder.toString(), classOfT);
}
private <T> T invokeAndReturn(String url, Class<T> classOfT) throws IOException, ApiException {
JsonElement ele = GsonApiClient.invokeJson(url);
return gson.fromJson(ele, classOfT);
}
public void downloadFile(String auth, int file, File target) throws IOException {
QueryBuilder builder = new QueryBuilder(ApiMethods.download_file);
builder.put("auth", auth);
builder.put("id", file);
String url = builder.toString();
URL website = new URL(url);
HttpURLConnection con = (HttpURLConnection) website.openConnection();
InputStream is = con.getInputStream();
@SuppressWarnings("rawtypes")
private String buildListString(List idList) {
if(idList == null) return null;
if(con.getResponseCode() == 200) {
Files.copy(is, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
JsonElement element = jsonParser.parse(StreamTools.readStreamtoString(is));
try {
ApiError err = gson.fromJson(element, ApiError.class);
if(err.getDesc() != null) {
throw new ApiException(err);
}
} catch(Exception e) {
}
}
}
String ids = "";
Integer x=0;
for(Object id : idList) {
x++;
ids += id.toString();
if(x != idList.size()) {
ids += ",";
}
}
public void rateFile(String auth, int file, boolean like) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.rate_file);
builder.put("auth", auth);
builder.put("id", file);
builder.put("like", like);
invokeAndReturn(builder, Success.class);
}
return ids;
}
public void removeFile(String auth, int file) throws IOException, ApiException {
QueryBuilder builder = new QueryBuilder(ApiMethods.remove_file);
builder.put("auth", auth);
builder.put("id", file);
invokeAndReturn(builder, Success.class);
}
private <T> T invokeAndReturn(QueryBuilder builder, Class<T> classOfT) throws IOException, ApiException {
return invokeAndReturn(builder.toString(), classOfT);
}
private <T> T invokeAndReturn(String url, Class<T> classOfT) throws IOException, ApiException {
JsonElement ele = GsonApiClient.invokeJson(url);
return gson.fromJson(ele, classOfT);
}
@SuppressWarnings("rawtypes")
private String buildListString(List idList) {
if(idList == null) return null;
String ids = "";
Integer x = 0;
for(Object id : idList) {
x++;
ids += id.toString();
if(x != idList.size()) {
ids += ",";
}
}
return ids;
}
}

View File

@@ -4,17 +4,17 @@ import eu.crushedpixel.replaymod.api.client.holders.ApiError;
public class ApiException extends Exception {
private static final long serialVersionUID = 349073390504232810L;
private static final long serialVersionUID = 349073390504232810L;
private ApiError error;
public ApiException(ApiError error) {
super(error.getDesc());
this.error = error;
}
public ApiError getError() {
return error;
}
private ApiError error;
public ApiException(ApiError error) {
super(error.getDesc());
this.error = error;
}
public ApiError getError() {
return error;
}
}

View File

@@ -1,16 +1,16 @@
package eu.crushedpixel.replaymod.api.client;
public class ApiMethods {
public static final String login = "login";
public static final String logout = "logout";
public static final String replay_files = "replay_files";
public static final String file_details = "file_details";
public static final String upload_file = "upload_file";
public static final String download_file = "download_file";
public static final String get_thumbnail = "get_thumbnail";
public static final String remove_file = "remove_file";
public static final String rate_file = "rate_file";
public static final String check_auth = "check_auth";
public static final String login = "login";
public static final String logout = "logout";
public static final String replay_files = "replay_files";
public static final String file_details = "file_details";
public static final String upload_file = "upload_file";
public static final String download_file = "download_file";
public static final String get_thumbnail = "get_thumbnail";
public static final String remove_file = "remove_file";
public static final String rate_file = "rate_file";
public static final String check_auth = "check_auth";
}

View File

@@ -1,160 +1,149 @@
package eu.crushedpixel.replaymod.api.client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.gson.Gson;
import eu.crushedpixel.replaymod.api.client.holders.ApiError;
import eu.crushedpixel.replaymod.api.client.holders.Category;
import eu.crushedpixel.replaymod.gui.online.GuiUploadFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import eu.crushedpixel.replaymod.api.client.holders.ApiError;
import eu.crushedpixel.replaymod.api.client.holders.Category;
import eu.crushedpixel.replaymod.gui.online.GuiUploadFile;
public class FileUploader {
private static Gson gson = new Gson();
private static JsonParser jsonParser = new JsonParser();
private static final Gson gson = new Gson();
private boolean uploading = false;
private long filesize;
private long current;
private boolean uploading = false;
private long filesize;
private long current;
private String attachmentName = "file";
private String attachmentFileName = "file.mcpr";
private String crlf = "\r\n";
private String twoHyphens = "--";
private String attachmentName = "file";
private String attachmentFileName = "file.mcpr";
private String crlf = "\r\n";
private String twoHyphens = "--";
private boolean cancel = false;
private boolean cancel = false;
private String boundary = "*****";
private GuiUploadFile parent;
//private CountingHttpEntity counter;
private String boundary = "*****";
private GuiUploadFile parent;
public void uploadFile(GuiUploadFile gui, String auth, String filename, List<String> tags, File file, Category category) throws IOException, ApiException, RuntimeException {
parent = gui;
gui.onStartUploading();
filesize = 0;
public void uploadFile(GuiUploadFile gui, String auth, String filename, List<String> tags, File file, Category category) throws IOException, ApiException, RuntimeException {
parent = gui;
gui.onStartUploading();
filesize = 0;
if(uploading) throw new RuntimeException("FileUploader is already uploading");
uploading = true;
if(uploading) throw new RuntimeException("FileUploader is already uploading");
uploading = true;
String postData = "?auth="+auth+"&category="+category.getId();
String postData = "?auth=" + auth + "&category=" + category.getId();
if(tags.size() > 0) {
postData += "&tags=";
for(String tag : tags) {
postData += tag;
if(!tag.equals(tags.get(tags.size()-1))) {
postData += ",";
}
}
}
if(tags.size() > 0) {
postData += "&tags=";
for(String tag : tags) {
postData += tag;
if(!tag.equals(tags.get(tags.size() - 1))) {
postData += ",";
}
}
}
postData +="&name="+URLEncoder.encode(filename, "UTF-8");
System.out.println(postData);
postData += "&name=" + URLEncoder.encode(filename, "UTF-8");
System.out.println(postData);
String url = "http://ReplayMod.com/api/upload_file"+postData;
HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setChunkedStreamingMode(1024);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary);
String url = "http://ReplayMod.com/api/upload_file" + postData;
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setChunkedStreamingMode(1024);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary);
HashMap<String, String> params = new HashMap<String, String>();
params.put("auth", auth);
params.put("name", filename);
params.put("category", category.getId()+"");
HashMap<String, String> params = new HashMap<String, String>();
params.put("auth", auth);
params.put("name", filename);
params.put("category", category.getId() + "");
DataOutputStream request = new DataOutputStream(con.getOutputStream());
DataOutputStream request = new DataOutputStream(con.getOutputStream());
request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf);
request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf);
request.writeBytes(this.crlf);
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(file);
filesize = fis.getChannel().size();
current = 0;
int len;
while((len = fis.read(buf)) != -1) {
request.write(buf);
current += len;
if(cancel) {
uploading = false;
current = 0;
cancel = false;
parent.onFinishUploading(false, "Upload has been canceled");
fis.close();
return;
}
}
fis.close();
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(file);
filesize = fis.getChannel().size();
current = 0;
int len;
while((len = fis.read(buf)) != -1) {
request.write(buf);
current += len;
if(cancel) {
uploading = false;
current = 0;
cancel = false;
parent.onFinishUploading(false, "Upload has been canceled");
fis.close();
return;
}
}
fis.close();
request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf);
request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf);
request.flush();
request.close();
request.flush();
request.close();
boolean success = false;
int responseCode = con.getResponseCode();
InputStream is = null;
if(responseCode == 200) {
success = true;
is = con.getInputStream();
} else {
is = con.getErrorStream();
}
boolean success = false;
int responseCode = con.getResponseCode();
InputStream is = null;
if(responseCode == 200) {
success = true;
is = con.getInputStream();
} else {
is = con.getErrorStream();
}
String info = null;
if(is != null) {
BufferedReader r = new BufferedReader(new InputStreamReader(is));
info = null;
if(responseCode != 200) {
ApiError error = new ApiError(-1, "An unknown error occured");
String json = "";
while(r.ready()) {
json += r.readLine();
}
error = gson.fromJson(json, ApiError.class);
info = error.getDesc();
System.out.println(info);
}
}
String info = null;
if(is != null) {
BufferedReader r = new BufferedReader(new InputStreamReader(is));
info = null;
if(responseCode != 200) {
String json = "";
while(r.ready()) {
json += r.readLine();
}
ApiError error = gson.fromJson(json, ApiError.class);
info = error.getDesc();
System.out.println(info);
}
}
con.disconnect();
con.disconnect();
if(info == null) info = "An unknown error occured";
parent.onFinishUploading(success, info);
if(info == null) info = "An unknown error occured";
uploading = false;
}
parent.onFinishUploading(success, info);
public float getUploadProgress() {
if(!uploading || filesize == 0) return 0;
return (float)((double)current/(double)filesize);
}
uploading = false;
}
public boolean isUploading() {
return uploading;
}
public float getUploadProgress() {
if(!uploading || filesize == 0) return 0;
return (float) ((double) current / (double) filesize);
}
public void cancelUploading() {
cancel = true;
}
public boolean isUploading() {
return uploading;
}
public void cancelUploading() {
cancel = true;
}
}

View File

@@ -1,38 +1,37 @@
package eu.crushedpixel.replaymod.api.client;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.Map;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonApiClient {
public class GsonApiClient {
private static final JsonParser parser = new JsonParser();
private static final JsonParser parser = new JsonParser();
public static JsonElement invoke(QueryBuilder query) throws IOException, ApiException {
String apiResult = SimpleApiClient.invoke(query);
return wrapWithJson(apiResult);
}
public static JsonElement invoke(QueryBuilder query) throws IOException, ApiException {
String apiResult = SimpleApiClient.invoke(query);
return wrapWithJson(apiResult);
}
public static JsonElement invokeJson(String url) throws IOException, ApiException {
String apiResult = SimpleApiClient.invokeUrl(url);
return wrapWithJson(apiResult);
}
public static JsonElement invokeJson(String url) throws IOException, ApiException {
String apiResult = SimpleApiClient.invokeUrl(url);
return wrapWithJson(apiResult);
}
public static JsonElement invokeJson(String apiKey, String method, Map<String,Object> paramMap) throws IOException, ApiException {
String apiResult = SimpleApiClient.invoke(method, paramMap);
return wrapWithJson(apiResult);
}
public static JsonElement invokeJson(String apiKey, String method, Map<String, Object> paramMap) throws IOException, ApiException {
String apiResult = SimpleApiClient.invoke(method, paramMap);
return wrapWithJson(apiResult);
}
public static JsonElement invokeJson(String apiKey, String method) throws IOException, ApiException {
String apiResult = SimpleApiClient.invoke(method, null);
return wrapWithJson(apiResult);
}
private static JsonElement wrapWithJson(String apiResult) {
JsonElement element = parser.parse(apiResult);
return element;
}
public static JsonElement invokeJson(String apiKey, String method) throws IOException, ApiException {
String apiResult = SimpleApiClient.invoke(method, null);
return wrapWithJson(apiResult);
}
private static JsonElement wrapWithJson(String apiResult) {
JsonElement element = parser.parse(apiResult);
return element;
}
}

View File

@@ -7,160 +7,90 @@ import java.util.Map;
public class QueryBuilder {
public static final String API_BASE_URL = "http://ReplayMod.com/api/";
public static final String API_BASE_URL = "http://ReplayMod.com/api/";
public String apiMethod;
public Map<String,String> paramMap;
public String apiMethod;
public Map<String, String> paramMap;
/**
* Creates an empty QueryBuilder from a given apikey.
* <br>Note that in order to use the QueryBuilder an apiMethod String has to be set.
* @param apiKey The apikey to use
*/
public QueryBuilder() {
this(null);
}
public QueryBuilder() {
this(null);
}
/**
* Creates an empty QueryBuilder from a given apikey and apiMethod.
*
* @param apiKey The apikey to use
* @param apiMethod The apiMethod to use
*/
public QueryBuilder(String apiMethod) {
this.apiMethod = apiMethod;
}
public QueryBuilder(String apiMethod) {
this.apiMethod = apiMethod;
}
/**
* Creates a QueryBuilder from a given apikey and apiMethod containing a single key/value parameter.
*
* @param apiKey The apikey to use
* @param apiMethod The apiMethod to use
* @param key The parameter key
* @param value The parameter value
*/
public QueryBuilder(String apiMethod, String key, String value) {
this(apiMethod);
put(key, value);
}
public QueryBuilder(String apiMethod, String key, String value) {
this(apiMethod);
put(key, value);
}
/**
* Creates a QueryBuilder from a given apikey and apiMethod containing two key/value parameters.
*
* @param apiKey The apikey to use
* @param apiMethod The apiMethod to use
* @param key1 The first parameter key
* @param value1 The first parameter value
* @param key2 The second parameter key
* @param value2 The second parameter value
*/
public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2) {
this(apiMethod);
put(key1, value1);
put(key2, value2);
}
public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2) {
this(apiMethod);
put(key1, value1);
put(key2, value2);
}
/**
* Creates a QueryBuilder from a given apikey and apiMethod containing three key/value parameters.
*
* @param apiKey The apikey to use
* @param apiMethod The apiMethod to use
* @param key1 The first parameter key
* @param value1 The first parameter value
* @param key2 The second parameter key
* @param value2 The second parameter value
* @param key3 The third parameter key
* @param value3 The third parameter value
*/
public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2, String key3, String value3) {
this(apiMethod);
put(key1, value1);
put(key2, value2);
put(key3, value3);
}
public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2, String key3, String value3) {
this(apiMethod);
put(key1, value1);
put(key2, value2);
put(key3, value3);
}
/**
* Adds a key/value parameter to the QueryBuilder.
* @param key The parameter key
* @param value The parameter value
*/
public void put(String key, Object value) {
if(key != null && value != null) {
if(paramMap == null) {
paramMap = new HashMap<String,String>();
}
paramMap.put(key, value.toString());
}
}
public void put(String key, Object value) {
if(key != null && value != null) {
if(paramMap == null) {
paramMap = new HashMap<String, String>();
}
paramMap.put(key, value.toString());
}
}
/**
* Adds two key/value parameters to the QueryBuilder.
* @param key1 The first parameter key
* @param value1 The first parameter value
* @param key2 The second parameter key
* @param value2 The second parameter value
*/
public void put(String key1, Object value1, String key2, Object value2) {
put(key1, value1);
put(key2, value2);
}
public void put(String key1, Object value1, String key2, Object value2) {
put(key1, value1);
put(key2, value2);
}
/**
* Adds three key/value parameters to the QueryBuilder.
* @param key1 The first parameter key
* @param value1 The first parameter value
* @param key2 The second parameter key
* @param value2 The second parameter value
* @param key3 The third parameter key
* @param value3 The third parameter value
*/
public void put(String key1, Object value1, String key2, Object value2, String key3, Object value3) {
put(key1, value1);
put(key2, value2);
put(key3, value3);
}
public void put(String key1, Object value1, String key2, Object value2, String key3, Object value3) {
put(key1, value1);
put(key2, value2);
put(key3, value3);
}
/**
* Adds a map of key/value parameters to the QueryBuilder.
* @param paraMap The map to add
*/
public void put(Map<String,Object> paraMap) {
if(paraMap == null) return;
for(String key: paraMap.keySet()) {
put(key,paraMap.get(key));
}
}
public void put(Map<String, Object> paraMap) {
if(paraMap == null) return;
for(String key : paraMap.keySet()) {
put(key, paraMap.get(key));
}
}
/**
* Creates an URL from the QueryBuilder using the given apikey and apiMethod and applies all
* parameters to it.
*/
public String toString() {
if(apiMethod == null) throw new IllegalArgumentException("apiMethod may not be null");
public String toString() {
if(apiMethod == null) throw new IllegalArgumentException("apiMethod may not be null");
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
// build base url
sb.append(API_BASE_URL);
sb.append(apiMethod);
// build base url
sb.append(API_BASE_URL);
sb.append(apiMethod);
// process parameters
try {
if(paramMap != null) {
boolean first = true;
for(String paramName: paramMap.keySet()) {
if(first) sb.append("?");
if(!first) sb.append("&");
first = false;
sb.append(paramName);
sb.append("=");
String value = paramMap.get(paramName);
sb.append(URLEncoder.encode(value, "UTF-8"));
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
// process parameters
try {
if(paramMap != null) {
boolean first = true;
for(String paramName : paramMap.keySet()) {
if(first) sb.append("?");
if(!first) sb.append("&");
first = false;
sb.append(paramName);
sb.append("=");
String value = paramMap.get(paramName);
sb.append(URLEncoder.encode(value, "UTF-8"));
}
}
return sb.toString();
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -1,50 +1,49 @@
package eu.crushedpixel.replaymod.api.client;
import eu.crushedpixel.replaymod.ReplayMod;
import eu.crushedpixel.replaymod.api.client.holders.FileInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import eu.crushedpixel.replaymod.ReplayMod;
import eu.crushedpixel.replaymod.api.client.holders.FileInfo;
public class SearchPagination {
private int page;
private List<FileInfo> files = new ArrayList<FileInfo>();
private final SearchQuery searchQuery;
private int page;
private List<FileInfo> files = new ArrayList<FileInfo>();
private final SearchQuery searchQuery;
public SearchPagination(SearchQuery searchQuery) {
this.page = -1;
this.searchQuery = searchQuery;
}
public SearchPagination(SearchQuery searchQuery) {
this.page = -1;
this.searchQuery = searchQuery;
}
public List<FileInfo> getFiles() {
return new ArrayList<FileInfo>(files);
}
public List<FileInfo> getFiles() {
return new ArrayList<FileInfo>(files);
}
public int getLoadedPages() {
return page;
}
public int getLoadedPages() {
return page;
}
public boolean fetchPage() {
page++;
searchQuery.offset = page;
public boolean fetchPage() {
page++;
searchQuery.offset = page;
try {
FileInfo[] fis = ReplayMod.apiClient.searchFiles(searchQuery);
if(fis.length <= 1) {
page--;
return false;
}
try {
FileInfo[] fis = ReplayMod.apiClient.searchFiles(searchQuery);
if(fis.length <= 1) {
page--;
return false;
}
files.addAll(Arrays.asList(fis));
return true;
} catch(Exception e) {
e.printStackTrace();
}
page--;
return false;
}
files.addAll(Arrays.asList(fis));
return true;
} catch(Exception e) {
e.printStackTrace();
}
page--;
return false;
}
}

View File

@@ -5,51 +5,52 @@ import java.net.URLEncoder;
public class SearchQuery {
public Boolean order, singleplayer;
public String player, tag, version, server, name, auth;
public Integer category, offset;
public Boolean order, singleplayer;
public String player, tag, version, server, name, auth;
public Integer category, offset;
public SearchQuery() {}
public SearchQuery() {
}
public SearchQuery(Boolean order, Boolean singleplayer, String player,
String tag, String version, String server, String name,
String auth, Integer category, Integer offset) {
this.order = order;
this.singleplayer = singleplayer;
this.player = player;
this.tag = tag;
this.version = version;
this.server = server;
this.name = name;
this.auth = auth;
this.category = category;
this.offset = offset;
}
public SearchQuery(Boolean order, Boolean singleplayer, String player,
String tag, String version, String server, String name,
String auth, Integer category, Integer offset) {
this.order = order;
this.singleplayer = singleplayer;
this.player = player;
this.tag = tag;
this.version = version;
this.server = server;
this.name = name;
this.auth = auth;
this.category = category;
this.offset = offset;
}
public String buildQuery() {
String query = "";
boolean first = true;
public String buildQuery() {
String query = "";
boolean first = true;
//Please don't slaughter me for this code,
//even if I deserve it, which I certainly do.
for(Field f : this.getClass().getDeclaredFields()) {
try {
Object value = f.get(this);
if(value == null) continue;
query += first ? "?" : "&";
first = false;
query += f.getName()+"=";
query += URLEncoder.encode(String.valueOf(value), "UTF-8");
} catch(Exception e) {
e.printStackTrace();
}
}
//Please don't slaughter me for this code,
//even if I deserve it, which I certainly do.
for(Field f : this.getClass().getDeclaredFields()) {
try {
Object value = f.get(this);
if(value == null) continue;
query += first ? "?" : "&";
first = false;
query += f.getName() + "=";
query += URLEncoder.encode(String.valueOf(value), "UTF-8");
} catch(Exception e) {
e.printStackTrace();
}
}
return query;
}
return query;
}
@Override
public String toString() {
return buildQuery();
}
@Override
public String toString() {
return buildQuery();
}
}

View File

@@ -1,120 +1,123 @@
package eu.crushedpixel.replaymod.api.client;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import eu.crushedpixel.replaymod.api.client.holders.ApiError;
import eu.crushedpixel.replaymod.utils.StreamTools;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import eu.crushedpixel.replaymod.api.client.holders.ApiError;
import eu.crushedpixel.replaymod.utils.StreamTools;
public class SimpleApiClient {
private static final JsonParser jsonParser = new JsonParser();
private static final Gson gson = new Gson();
/**
* Returns a Json String from the given QueryBuilder
* @param query The QueryBuilder to use
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invoke(QueryBuilder query) throws IOException, ApiException {
return invokeImpl(query.toString());
}
private static final JsonParser jsonParser = new JsonParser();
private static final Gson gson = new Gson();
/**
* Returns a Json String from the given URL
* @param url The URL to parse the Json from
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invokeUrl(String url) throws IOException, ApiException {
return invokeImpl(url);
}
/**
* Returns a Json String from the given QueryBuilder
*
* @param query The QueryBuilder to use
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invoke(QueryBuilder query) throws IOException, ApiException {
return invokeImpl(query.toString());
}
/**
* Returns a Json String from the API
* @param apiKey The apikey to use
* @param method The apiMethod to be called
* @param paramMap The parameters to apply
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invoke(String method, Map<String,Object> paramMap) throws IOException, ApiException {
return invokeImpl(method, paramMap);
}
/**
* Returns a Json String from the given URL
*
* @param url The URL to parse the Json from
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invokeUrl(String url) throws IOException, ApiException {
return invokeImpl(url);
}
/**
* Returns a Json String from the API
* @param apiKey The apikey to use
* @param method The apiMethod to be called
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invoke(String method) throws IOException, ApiException {
return invokeImpl(method, null);
}
/**
* Returns a Json String from the API
*
* @param apiKey The apikey to use
* @param method The apiMethod to be called
* @param paramMap The parameters to apply
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invoke(String method, Map<String, Object> paramMap) throws IOException, ApiException {
return invokeImpl(method, paramMap);
}
private static String invokeImpl(String urlString) throws IOException, ApiException {
/**
* Returns a Json String from the API
*
* @param apiKey The apikey to use
* @param method The apiMethod to be called
* @return A Json String from the API
* @throws IOException
* @throws ApiException
*/
public static String invoke(String method) throws IOException, ApiException {
return invokeImpl(method, null);
}
// read response
String responseContent = null;
InputStream is = null;
HttpURLConnection httpUrlConnection = null;
HttpURLConnection.setFollowRedirects(false);
try {
URL url = new URL(urlString);
httpUrlConnection = (HttpURLConnection)url.openConnection();
private static String invokeImpl(String urlString) throws IOException, ApiException {
httpUrlConnection.setRequestMethod("GET");
// read response
String responseContent = null;
InputStream is = null;
HttpURLConnection httpUrlConnection = null;
HttpURLConnection.setFollowRedirects(false);
try {
URL url = new URL(urlString);
httpUrlConnection = (HttpURLConnection) url.openConnection();
// give it 15 seconds to respond
httpUrlConnection.setReadTimeout(15*1000);
httpUrlConnection.connect();
httpUrlConnection.setRequestMethod("GET");
int responseCode = httpUrlConnection.getResponseCode();
// give it 15 seconds to respond
httpUrlConnection.setReadTimeout(15 * 1000);
httpUrlConnection.connect();
if(responseCode != 200) {
is = httpUrlConnection.getErrorStream();
if(is != null) {
responseContent = StreamTools.readStreamtoString(is,"UTF-8");
} else {
responseContent = "";
}
JsonObject response = jsonParser.parse(responseContent).getAsJsonObject();
throw new ApiException(gson.fromJson(response, ApiError.class));
}
int responseCode = httpUrlConnection.getResponseCode();
is = httpUrlConnection.getInputStream();
if(responseCode != 200) {
is = httpUrlConnection.getErrorStream();
if(is != null) {
responseContent = StreamTools.readStreamtoString(is, "UTF-8");
} else {
responseContent = "";
}
JsonObject response = jsonParser.parse(responseContent).getAsJsonObject();
throw new ApiException(gson.fromJson(response, ApiError.class));
}
responseContent = StreamTools.readStreamtoString(is,"UTF-8");
is = httpUrlConnection.getInputStream();
} catch(IOException e) {
throw e;
} finally {
if(is != null) {
is.close();
}
if(httpUrlConnection != null) {
httpUrlConnection.disconnect();
}
}
return responseContent;
}
responseContent = StreamTools.readStreamtoString(is, "UTF-8");
private static String invokeImpl(String method, Map<String,Object> paramMap) throws IOException, ApiException {
QueryBuilder queryBuilder = new QueryBuilder(method);
queryBuilder.put(paramMap);
return invokeImpl(queryBuilder.toString());
}
} catch(IOException e) {
throw e;
} finally {
if(is != null) {
is.close();
}
if(httpUrlConnection != null) {
httpUrlConnection.disconnect();
}
}
return responseContent;
}
private static String invokeImpl(String method, Map<String, Object> paramMap) throws IOException, ApiException {
QueryBuilder queryBuilder = new QueryBuilder(method);
queryBuilder.put(paramMap);
return invokeImpl(queryBuilder.toString());
}
}

View File

@@ -2,26 +2,28 @@ package eu.crushedpixel.replaymod.api.client.holders;
public class ApiError {
public ApiError(int id, String desc) {
this.id = id;
this.desc = desc;
}
private int id;
private String desc;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private int id;
private String desc;
public ApiError(int id, String desc) {
this.id = id;
this.desc = desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}

View File

@@ -1,14 +1,14 @@
package eu.crushedpixel.replaymod.api.client.holders;
public class AuthKey {
private String auth;
public AuthKey(String authkey) {
this.auth = authkey;
}
public String getAuthkey() {
return auth;
}
private String auth;
public AuthKey(String authkey) {
this.auth = authkey;
}
public String getAuthkey() {
return auth;
}
}

View File

@@ -2,38 +2,38 @@ package eu.crushedpixel.replaymod.api.client.holders;
public enum Category {
SURVIVAL(0), MINIGAME(1), BUILD(2);
private int id;
Category(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public Category fromId(int id) {
for(Category c : values()) {
if(c.id == id) return c;
}
return null;
}
public String toNiceString() {
return (""+this).charAt(0)+(""+this).substring(1).toLowerCase();
}
public Category next() {
for(int i=0; i<values().length; i++) {
if(values()[i] == this) {
if(i == values().length-1) {
i=-1;
}
return values()[i+1];
}
}
return this;
}
SURVIVAL(0), MINIGAME(1), BUILD(2);
private int id;
Category(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public Category fromId(int id) {
for(Category c : values()) {
if(c.id == id) return c;
}
return null;
}
public String toNiceString() {
return ("" + this).charAt(0) + ("" + this).substring(1).toLowerCase();
}
public Category next() {
for(int i = 0; i < values().length; i++) {
if(values()[i] == this) {
if(i == values().length - 1) {
i = -1;
}
return values()[i + 1];
}
}
return this;
}
}

View File

@@ -2,9 +2,9 @@ package eu.crushedpixel.replaymod.api.client.holders;
public class Donated {
private boolean donated = false;
public boolean hasDonated() {
return donated;
}
private boolean donated = false;
public boolean hasDonated() {
return donated;
}
}

View File

@@ -4,61 +4,70 @@ import eu.crushedpixel.replaymod.recording.ReplayMetaData;
public class FileInfo {
private int id;
private ReplayMetaData metadata;
private String owner;
private Rating ratings;
private int size;
private int category;
private int downloads;
private String name;
private boolean thumbnail;
private int id;
private ReplayMetaData metadata;
private String owner;
private Rating ratings;
private int size;
private int category;
private int downloads;
private String name;
private boolean thumbnail;
public FileInfo(int id, ReplayMetaData metadata, String owner,
Rating ratings, int size, int category, int downloads, String name,
boolean thumbnail) {
this.id = id;
this.metadata = metadata;
this.owner = owner;
this.ratings = ratings;
this.size = size;
this.category = category;
this.downloads = downloads;
this.name = name;
this.thumbnail = thumbnail;
}
public int getId() {
return id;
}
public ReplayMetaData getMetadata() {
return metadata;
}
public String getOwner() {
return owner;
}
public Rating getRatings() {
return ratings;
}
public int getSize() {
return size;
}
public int getCategory() {
return category;
}
public int getDownloads() {
return downloads;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean hasThumbnail() {
return thumbnail;
}
public FileInfo(int id, ReplayMetaData metadata, String owner,
Rating ratings, int size, int category, int downloads, String name,
boolean thumbnail) {
this.id = id;
this.metadata = metadata;
this.owner = owner;
this.ratings = ratings;
this.size = size;
this.category = category;
this.downloads = downloads;
this.name = name;
this.thumbnail = thumbnail;
}
public int getId() {
return id;
}
public ReplayMetaData getMetadata() {
return metadata;
}
public String getOwner() {
return owner;
}
public Rating getRatings() {
return ratings;
}
public int getSize() {
return size;
}
public int getCategory() {
return category;
}
public int getDownloads() {
return downloads;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean hasThumbnail() {
return thumbnail;
}
}

View File

@@ -2,13 +2,13 @@ package eu.crushedpixel.replaymod.api.client.holders;
public class Rating {
private int negative, positive;
private int negative, positive;
public int getNegative() {
return negative;
}
public int getNegative() {
return negative;
}
public int getPositive() {
return positive;
}
public int getPositive() {
return positive;
}
}

View File

@@ -2,9 +2,9 @@ package eu.crushedpixel.replaymod.api.client.holders;
public class SearchResult {
private FileInfo[] results;
private FileInfo[] results;
public FileInfo[] getResults() {
return results;
}
public FileInfo[] getResults() {
return results;
}
}

View File

@@ -2,9 +2,9 @@ package eu.crushedpixel.replaymod.api.client.holders;
public class Success {
private boolean success = false;
public boolean isSuccess() {
return success;
}
private boolean success = false;
public boolean isSuccess() {
return success;
}
}

View File

@@ -2,19 +2,21 @@ package eu.crushedpixel.replaymod.api.client.holders;
public class UserFiles {
private String user;
private FileInfo[] files;
private int total_size;
public String getUser() {
return user;
}
public FileInfo[] getFiles() {
return files;
}
public int getTotal_size() {
return total_size;
}
private String user;
private FileInfo[] files;
private int total_size;
public String getUser() {
return user;
}
public FileInfo[] getFiles() {
return files;
}
public int getTotal_size() {
return total_size;
}
}