Removal of Lombok

Lombok implementation removal.

I have also gone through and replaced things with inline methods and variables, lambdas, and simplified loops down, removed unnecessary guard clauses, and overall cleaned up every single class. This took a long time, please do remember to follow proper naming conventions, don't include unnecessary guard clauses, follow exception rules and comment rules, and please PLEASE remember to use the DIAMOND OPERATOR rather than just inferring RAW TYPES!!!

Thank you!!
This commit is contained in:
Paldiu
2020-12-25 14:46:43 -05:00
parent 210b0f8b43
commit 5c0f77c7c5
170 changed files with 3302 additions and 2383 deletions

View File

@ -1,7 +1,6 @@
package me.totalfreedom.totalfreedommod.httpd;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
@ -23,10 +22,8 @@ public class HTMLGenerationTools
output.append("<ul>\r\n");
Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();
while (it.hasNext())
for (Map.Entry<K, V> entry : map.entrySet())
{
Map.Entry<K, V> entry = it.next();
output.append("<li>").append(escapeHtml4(entry.getKey().toString() + " = " + entry.getValue().toString())).append("</li>\r\n");
}

View File

@ -12,6 +12,7 @@ import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Response;
import me.totalfreedom.totalfreedommod.httpd.module.HTTPDModule;
import me.totalfreedom.totalfreedommod.httpd.module.Module_activitylog;
import me.totalfreedom.totalfreedommod.httpd.module.Module_admins;
import me.totalfreedom.totalfreedommod.httpd.module.Module_bans;
import me.totalfreedom.totalfreedommod.httpd.module.Module_file;
import me.totalfreedom.totalfreedommod.httpd.module.Module_help;
@ -23,7 +24,6 @@ import me.totalfreedom.totalfreedommod.httpd.module.Module_logs;
import me.totalfreedom.totalfreedommod.httpd.module.Module_players;
import me.totalfreedom.totalfreedommod.httpd.module.Module_punishments;
import me.totalfreedom.totalfreedommod.httpd.module.Module_schematic;
import me.totalfreedom.totalfreedommod.httpd.module.Module_admins;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
@ -32,12 +32,50 @@ import org.apache.commons.lang.exception.ExceptionUtils;
public class HTTPDaemon extends FreedomService
{
private static final Pattern EXT_REGEX = Pattern.compile("\\.([^.\\s]+)$");
public static String MIME_DEFAULT_BINARY = "application/octet-stream";
private static final Pattern EXT_REGEX = Pattern.compile("\\.([^\\.\\s]+)$");
//
public int port;
private HTTPD httpd;
public Map<String, ModuleExecutable> modules = new HashMap<>();
private HTTPD httpd;
public static Response serveFileBasic(File file)
{
Response response = null;
if (file != null && file.exists())
{
try
{
String mimetype = null;
Matcher matcher = EXT_REGEX.matcher(file.getCanonicalPath());
if (matcher.find())
{
mimetype = Module_file.MIME_TYPES.get(matcher.group(1));
}
if (mimetype == null || mimetype.trim().isEmpty())
{
mimetype = MIME_DEFAULT_BINARY;
}
// Some browsers like firefox download the file for text/yaml mime types
if (FilenameUtils.getExtension(file.getName()).equals("yml"))
{
mimetype = NanoHTTPD.MIME_PLAINTEXT;
}
response = new Response(Response.Status.OK, mimetype, new FileInputStream(file));
response.addHeader("Content-Length", "" + file.length());
}
catch (IOException ex)
{
FLog.severe(ex);
}
}
return response;
}
@Override
public void onStart()
@ -141,42 +179,4 @@ public class HTTPDaemon extends FreedomService
}
}
}
public static Response serveFileBasic(File file)
{
Response response = null;
if (file != null && file.exists())
{
try
{
String mimetype = null;
Matcher matcher = EXT_REGEX.matcher(file.getCanonicalPath());
if (matcher.find())
{
mimetype = Module_file.MIME_TYPES.get(matcher.group(1));
}
if (mimetype == null || mimetype.trim().isEmpty())
{
mimetype = MIME_DEFAULT_BINARY;
}
// Some browsers like firefox download the file for text/yaml mime types
if (FilenameUtils.getExtension(file.getName()).equals("yml"))
{
mimetype = NanoHTTPD.MIME_PLAINTEXT;
}
response = new Response(Response.Status.OK, mimetype, new FileInputStream(file));
response.addHeader("Content-Length", "" + file.length());
}
catch (IOException ex)
{
FLog.severe(ex);
}
}
return response;
}
}

View File

@ -1,7 +1,7 @@
package me.totalfreedom.totalfreedommod.httpd;
import java.lang.reflect.Constructor;
import java.util.concurrent.Callable;
import java.util.Objects;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.httpd.module.HTTPDModule;
@ -19,35 +19,6 @@ public abstract class ModuleExecutable
this.async = async;
}
public NanoHTTPD.Response execute(final NanoHTTPD.HTTPSession session)
{
try
{
if (async)
{
return getResponse(session);
}
// Sync to server thread
return Bukkit.getScheduler().callSyncMethod(TotalFreedomMod.plugin(), new Callable<NanoHTTPD.Response>()
{
@Override
public NanoHTTPD.Response call() throws Exception
{
return getResponse(session);
}
}).get();
}
catch (Exception ex)
{
FLog.severe(ex);
}
return null;
}
public abstract NanoHTTPD.Response getResponse(NanoHTTPD.HTTPSession session);
public static ModuleExecutable forClass(final TotalFreedomMod plugin, Class<? extends HTTPDModule> clazz, boolean async)
{
final Constructor<? extends HTTPDModule> cons;
@ -78,4 +49,26 @@ public abstract class ModuleExecutable
};
}
public NanoHTTPD.Response execute(final NanoHTTPD.HTTPSession session)
{
try
{
if (async)
{
return getResponse(session);
}
// Sync to server thread
return Bukkit.getScheduler().callSyncMethod(Objects.requireNonNull(TotalFreedomMod.plugin()), () -> getResponse(session)).get();
}
catch (Exception ex)
{
FLog.severe(ex);
}
return null;
}
public abstract NanoHTTPD.Response getResponse(NanoHTTPD.HTTPSession session);
}

View File

@ -21,6 +21,7 @@ import java.net.SocketException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
@ -33,6 +34,7 @@ import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.jetbrains.annotations.NotNull;
/**
* A simple, tiny, nicely embeddable HTTP server in Java
@ -133,7 +135,7 @@ public abstract class NanoHTTPD
setAsyncRunner(new DefaultAsyncRunner());
}
private static final void safeClose(ServerSocket serverSocket)
private static void safeClose(ServerSocket serverSocket)
{
if (serverSocket != null)
{
@ -141,13 +143,13 @@ public abstract class NanoHTTPD
{
serverSocket.close();
}
catch (IOException e)
catch (IOException ignored)
{
}
}
}
private static final void safeClose(Socket socket)
private static void safeClose(Socket socket)
{
if (socket != null)
{
@ -155,13 +157,13 @@ public abstract class NanoHTTPD
{
socket.close();
}
catch (IOException e)
catch (IOException ignored)
{
}
}
}
private static final void safeClose(Closeable closeable)
private static void safeClose(Closeable closeable)
{
if (closeable != null)
{
@ -169,7 +171,7 @@ public abstract class NanoHTTPD
{
closeable.close();
}
catch (IOException e)
catch (IOException ignored)
{
}
}
@ -185,64 +187,56 @@ public abstract class NanoHTTPD
myServerSocket = new ServerSocket();
myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
myThread = new Thread(new Runnable()
myThread = new Thread(() ->
{
@Override
public void run()
do
{
do
try
{
try
final Socket finalAccept = myServerSocket.accept();
final InputStream inputStream = finalAccept.getInputStream();
if (inputStream == null)
{
final Socket finalAccept = myServerSocket.accept();
final InputStream inputStream = finalAccept.getInputStream();
if (inputStream == null)
{
safeClose(finalAccept);
}
else
{
asyncRunner.exec(new Runnable()
{
@Override
public void run()
{
OutputStream outputStream = null;
try
{
outputStream = finalAccept.getOutputStream();
TempFileManager tempFileManager = tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept);
while (!finalAccept.isClosed())
{
session.execute();
}
}
catch (Exception e)
{
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())))
{
FLog.severe(e);
}
}
finally
{
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
}
}
});
}
safeClose(finalAccept);
}
catch (IOException e)
else
{
asyncRunner.exec(() ->
{
OutputStream outputStream = null;
try
{
outputStream = finalAccept.getOutputStream();
TempFileManager tempFileManager = tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept);
while (!finalAccept.isClosed())
{
session.execute();
}
}
catch (Exception e)
{
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())))
{
FLog.severe(e);
}
}
finally
{
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
}
});
}
}
while (!myServerSocket.isClosed());
catch (IOException ignored)
{
}
}
while (!myServerSocket.isClosed());
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
@ -382,7 +376,7 @@ public abstract class NanoHTTPD
String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
if (!parms.containsKey(propertyName))
{
parms.put(propertyName, new ArrayList<String>());
parms.put(propertyName, new ArrayList<>());
}
String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null;
if (propertyValue != null)
@ -573,8 +567,8 @@ public abstract class NanoHTTPD
public static class DefaultTempFile implements TempFile
{
private File file;
private OutputStream fstream;
private final File file;
private final OutputStream fstream;
public DefaultTempFile(String tempdir) throws IOException
{
@ -583,7 +577,7 @@ public abstract class NanoHTTPD
}
@Override
public OutputStream open() throws Exception
public OutputStream open()
{
return fstream;
}
@ -608,6 +602,10 @@ public abstract class NanoHTTPD
public static class Response
{
/**
* Headers for the HTTP response. Use addHeader() to add lines.
*/
private final Map<String, String> header = new HashMap<>();
/**
* HTTP status code after processing, e.g. "200 OK", HTTP_OK
*/
@ -620,10 +618,6 @@ public abstract class NanoHTTPD
* Data of the response, may be null.
*/
private InputStream data;
/**
* Headers for the HTTP response. Use addHeader() to add lines.
*/
private Map<String, String> header = new HashMap<>();
/**
* The request method that spawned this response.
*/
@ -658,14 +652,7 @@ public abstract class NanoHTTPD
{
this.status = status;
this.mimeType = mimeType;
try
{
this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null;
}
catch (java.io.UnsupportedEncodingException uee)
{
FLog.severe(uee);
}
this.data = txt != null ? new ByteArrayInputStream(txt.getBytes(StandardCharsets.UTF_8)) : null;
}
/**
@ -699,18 +686,15 @@ public abstract class NanoHTTPD
pw.print("Content-Type: " + mime + "\r\n");
}
if (header == null || header.get("Date") == null)
if (header.get("Date") == null)
{
pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
}
if (header != null)
for (String key : header.keySet())
{
for (String key : header.keySet())
{
String value = header.get(key);
pw.print(key + ": " + value + "\r\n");
}
String value = header.get(key);
pw.print(key + ": " + value + "\r\n");
}
pw.print("Connection: keep-alive\r\n");
@ -747,7 +731,7 @@ public abstract class NanoHTTPD
outputStream.write(buff, 0, read);
outputStream.write(CRLF);
}
outputStream.write(String.format("0\r\n\r\n").getBytes());
outputStream.write("0\r\n\r\n".getBytes());
}
private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException
@ -764,7 +748,7 @@ public abstract class NanoHTTPD
byte[] buff = new byte[BUFFER_SIZE];
while (pending > 0)
{
int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending));
int read = data.read(buff, 0, (Math.min(pending, BUFFER_SIZE)));
if (read <= 0)
{
break;
@ -876,10 +860,52 @@ public abstract class NanoHTTPD
}
}
public static class Cookie
{
private final String n;
private final String v;
private final String e;
public Cookie(String name, String value, String expires)
{
n = name;
v = value;
e = expires;
}
public Cookie(String name, String value)
{
this(name, value, 30);
}
public Cookie(String name, String value, int numDays)
{
n = name;
v = value;
e = getHTTPTime(numDays);
}
public static String getHTTPTime(int days)
{
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}
public String getHTTPHeader()
{
String fmt = "%s=%s; expires=%s";
return String.format(fmt, n, v, e);
}
}
/**
* Default strategy for creating and cleaning up temporary files.
*/
private class DefaultTempFileManagerFactory implements TempFileManagerFactory
private static class DefaultTempFileManagerFactory implements TempFileManagerFactory
{
@Override
@ -889,6 +915,92 @@ public abstract class NanoHTTPD
}
}
/**
* Provides rudimentary support for cookies. Doesn't support 'path', 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported features.
*
* @author LordFokas
*/
public static class CookieHandler implements Iterable<String>
{
private final HashMap<String, String> cookies = new HashMap<>();
private final ArrayList<Cookie> queue = new ArrayList<>();
public CookieHandler(Map<String, String> httpHeaders)
{
String raw = httpHeaders.get("cookie");
if (raw != null)
{
String[] tokens = raw.split(";");
for (String token : tokens)
{
String[] data = token.trim().split("=");
if (data.length == 2)
{
cookies.put(data[0], data[1]);
}
}
}
}
@Override
public @NotNull Iterator<String> iterator()
{
return cookies.keySet().iterator();
}
/**
* Read a cookie from the HTTP Headers.
*
* @param name The cookie's name.
* @return The cookie's value if it exists, null otherwise.
*/
public String read(String name)
{
return cookies.get(name);
}
/**
* Sets a cookie.
*
* @param name The cookie's name.
* @param value The cookie's value.
* @param expires How many days until the cookie expires.
*/
public void set(String name, String value, int expires)
{
queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
}
public void set(Cookie cookie)
{
queue.add(cookie);
}
/**
* Set a cookie with an expiration date from a month ago, effectively deleting it on the client side.
*
* @param name The cookie name.
*/
public void delete(String name)
{
set(name, "-delete-", -30);
}
/**
* Internally used by the webserver to add all queued cookies into the Response's HTTP Headers.
*
* @param response The Response object to which headers the queued cookies will be added.
*/
public void unloadQueue(Response response)
{
for (Cookie cookie : queue)
{
response.addHeader("Set-Cookie", cookie.getHTTPHeader());
}
}
}
/**
* Handles one session, i.e. parses the HTTP request and returns the response.
*/
@ -949,8 +1061,7 @@ public abstract class NanoHTTPD
if (splitbyte < rlen)
{
ByteArrayInputStream splitInputStream = new ByteArrayInputStream(buf, splitbyte, rlen - splitbyte);
SequenceInputStream sequenceInputStream = new SequenceInputStream(splitInputStream, inputStream);
inputStream = sequenceInputStream;
inputStream = new SequenceInputStream(splitInputStream, inputStream);
}
parms = new HashMap<>();
@ -1040,11 +1151,13 @@ public abstract class NanoHTTPD
size -= rlen;
if (rlen > 0)
{
assert randomAccessFile != null;
randomAccessFile.write(buf, 0, rlen);
}
}
// Get the raw body as a byte []
assert randomAccessFile != null;
ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
randomAccessFile.seek(0);
@ -1079,7 +1192,7 @@ public abstract class NanoHTTPD
String boundaryStartString = "boundary=";
int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length();
String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length());
String boundary = contentTypeHeader.substring(boundaryContentStart);
if (boundary.startsWith("\"") && boundary.endsWith("\""))
{
boundary = boundary.substring(1, boundary.length() - 1);
@ -1090,16 +1203,16 @@ public abstract class NanoHTTPD
else
{
// Handle application/x-www-form-urlencoded
String postLine = "";
char pbuf[] = new char[512];
StringBuilder postLine = new StringBuilder();
char[] pbuf = new char[512];
int read = in.read(pbuf);
while (read >= 0 && !postLine.endsWith("\r\n"))
while (read >= 0 && !postLine.toString().endsWith("\r\n"))
{
postLine += String.valueOf(pbuf, 0, read);
postLine.append(String.valueOf(pbuf, 0, read));
read = in.read(pbuf);
}
postLine = postLine.trim();
decodeParms(postLine, parms);
postLine = new StringBuilder(postLine.toString().trim());
decodeParms(postLine.toString(), parms);
}
}
else if (Method.PUT.equals(method))
@ -1232,7 +1345,7 @@ public abstract class NanoHTTPD
String pname = disposition.get("name");
pname = pname.substring(1, pname.length() - 1);
String value = "";
StringBuilder value = new StringBuilder();
if (item.get("content-type") == null)
{
while (mpline != null && !mpline.contains(boundary))
@ -1243,11 +1356,11 @@ public abstract class NanoHTTPD
int d = mpline.indexOf(boundary);
if (d == -1)
{
value += mpline;
value.append(mpline);
}
else
{
value += mpline.substring(0, d - 2);
value.append(mpline, 0, d - 2);
}
}
}
@ -1261,15 +1374,15 @@ public abstract class NanoHTTPD
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
files.put(pname, path);
value = disposition.get("filename");
value = value.substring(1, value.length() - 1);
value = new StringBuilder(disposition.get("filename"));
value = new StringBuilder(value.substring(1, value.length() - 1));
do
{
mpline = in.readLine();
}
while (mpline != null && !mpline.contains(boundary));
}
parms.put(pname, value);
parms.put(pname, value.toString());
}
}
}
@ -1462,130 +1575,4 @@ public abstract class NanoHTTPD
}
}
public static class Cookie
{
private String n, v, e;
public Cookie(String name, String value, String expires)
{
n = name;
v = value;
e = expires;
}
public Cookie(String name, String value)
{
this(name, value, 30);
}
public Cookie(String name, String value, int numDays)
{
n = name;
v = value;
e = getHTTPTime(numDays);
}
public String getHTTPHeader()
{
String fmt = "%s=%s; expires=%s";
return String.format(fmt, n, v, e);
}
public static String getHTTPTime(int days)
{
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}
}
/**
* Provides rudimentary support for cookies. Doesn't support 'path', 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported features.
*
* @author LordFokas
*/
public class CookieHandler implements Iterable<String>
{
private HashMap<String, String> cookies = new HashMap<>();
private ArrayList<Cookie> queue = new ArrayList<>();
public CookieHandler(Map<String, String> httpHeaders)
{
String raw = httpHeaders.get("cookie");
if (raw != null)
{
String[] tokens = raw.split(";");
for (String token : tokens)
{
String[] data = token.trim().split("=");
if (data.length == 2)
{
cookies.put(data[0], data[1]);
}
}
}
}
@Override
public Iterator<String> iterator()
{
return cookies.keySet().iterator();
}
/**
* Read a cookie from the HTTP Headers.
*
* @param name The cookie's name.
* @return The cookie's value if it exists, null otherwise.
*/
public String read(String name)
{
return cookies.get(name);
}
/**
* Sets a cookie.
*
* @param name The cookie's name.
* @param value The cookie's value.
* @param expires How many days until the cookie expires.
*/
public void set(String name, String value, int expires)
{
queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
}
public void set(Cookie cookie)
{
queue.add(cookie);
}
/**
* Set a cookie with an expiration date from a month ago, effectively deleting it on the client side.
*
* @param name The cookie name.
*/
public void delete(String name)
{
set(name, "-delete-", -30);
}
/**
* Internally used by the webserver to add all queued cookies into the Response's HTTP Headers.
*
* @param response The Response object to which headers the queued cookies will be added.
*/
public void unloadQueue(Response response)
{
for (Cookie cookie : queue)
{
response.addHeader("Set-Cookie", cookie.getHTTPHeader());
}
}
}
}

View File

@ -4,7 +4,6 @@ import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.HTTPSession;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Method;
@ -21,7 +20,7 @@ public abstract class HTTPDModule extends FreedomService
protected final Socket socket;
protected final HTTPSession session;
public HTTPDModule(TotalFreedomMod plugin, HTTPSession session)
public HTTPDModule(HTTPSession session)
{
this.uri = session.getUri();
this.method = session.getMethod();

View File

@ -1,18 +1,17 @@
package me.totalfreedom.totalfreedommod.httpd.module;
import java.io.File;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.admin.ActivityLog;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
public class Module_activitylog extends HTTPDModule
{
public Module_activitylog(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
public Module_activitylog(NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override

View File

@ -1,15 +1,14 @@
package me.totalfreedom.totalfreedommod.httpd.module;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
public class Module_admins extends HTTPDModule
{
public Module_admins(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
public Module_admins(NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override

View File

@ -1,15 +1,14 @@
package me.totalfreedom.totalfreedommod.httpd.module;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
public class Module_bans extends HTTPDModule
{
public Module_bans(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
public Module_bans(NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override

View File

@ -2,7 +2,6 @@ package me.totalfreedom.totalfreedommod.httpd.module;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@ -12,7 +11,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
@ -25,7 +23,6 @@ import org.apache.commons.lang3.StringUtils;
public class Module_file extends HTTPDModule
{
private final File rootDir = new File(ConfigEntry.HTTPD_PUBLIC_FOLDER.getString());
public static final Map<String, String> MIME_TYPES = new HashMap<>();
static
@ -58,9 +55,11 @@ public class Module_file extends HTTPDModule
MIME_TYPES.put("class", "application/octet-stream");
}
public Module_file(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
private final File rootDir = new File(ConfigEntry.HTTPD_PUBLIC_FOLDER.getString());
public Module_file(NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
private File getRootDir()
@ -70,31 +69,31 @@ public class Module_file extends HTTPDModule
private String encodeUri(String uri)
{
String newUri = "";
StringBuilder newUri = new StringBuilder();
StringTokenizer st = new StringTokenizer(uri, "/ ", true);
while (st.hasMoreTokens())
{
String tok = st.nextToken();
if (tok.equals("/"))
{
newUri += "/";
newUri.append("/");
}
else if (tok.equals(" "))
{
newUri += "%20";
newUri.append("%20");
}
else
{
try
{
newUri += URLEncoder.encode(tok, "UTF-8");
newUri.append(URLEncoder.encode(tok, "UTF-8"));
}
catch (UnsupportedEncodingException ignored)
{
}
}
}
return newUri;
return newUri.toString();
}
public Response serveFile(String uri, Map<String, String> params, File homeDir)
@ -237,7 +236,6 @@ public class Module_file extends HTTPDModule
{
res = new Response(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
res.addHeader("ETag", etag);
}
else
{
@ -255,25 +253,25 @@ public class Module_file extends HTTPDModule
FileInputStream fis = new FileInputStream(f)
{
@Override
public int available() throws IOException
public int available()
{
return (int)dataLen;
}
};
//noinspection ResultOfMethodCallIgnored
fis.skip(startFrom);
res = new Response(Response.Status.PARTIAL_CONTENT, mime, fis);
res.addHeader("Content-Length", "" + dataLen);
res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
res.addHeader("ETag", etag);
}
}
else
{
res = new Response(Response.Status.OK, mime, new FileInputStream(f));
res.addHeader("Content-Length", "" + fileLen);
res.addHeader("ETag", etag);
}
res.addHeader("ETag", etag);
}
}
catch (IOException ioe)
@ -288,12 +286,12 @@ public class Module_file extends HTTPDModule
private String listDirectory(String uri, File f)
{
String heading = "Directory " + uri;
String msg = "<html><head><title>" + heading + "</title><style><!--\n"
StringBuilder msg = new StringBuilder("<html><head><title>" + heading + "</title><style><!--\n"
+ "span.dirname { font-weight: bold; }\n"
+ "span.filesize { font-size: 75%; }\n"
+ "// -->\n"
+ "</style>"
+ "</head><body><h1>" + heading + "</h1>";
+ "</head><body><h1>" + heading + "</h1>");
String up = null;
if (uri.length() > 1)
@ -306,72 +304,56 @@ public class Module_file extends HTTPDModule
}
}
List<String> files = Arrays.asList(f.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return new File(dir, name).isFile();
}
}));
List<String> files = Arrays.asList(f.list((dir, name) -> new File(dir, name).isFile()));
Collections.sort(files);
List<String> directories = Arrays.asList(f.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return new File(dir, name).isDirectory();
}
}));
List<String> directories = Arrays.asList(f.list((dir, name) -> new File(dir, name).isDirectory()));
Collections.sort(directories);
if (up != null || directories.size() + files.size() > 0)
{
msg += "<ul>";
msg.append("<ul>");
if (up != null || directories.size() > 0)
{
msg += "<section class=\"directories\">";
msg.append("<section class=\"directories\">");
if (up != null)
{
msg += "<li><a rel=\"directory\" href=\"" + up + "\"><span class=\"dirname\">..</span></a></b></li>";
msg.append("<li><a rel=\"directory\" href=\"").append(up).append("\"><span class=\"dirname\">..</span></a></b></li>");
}
for (int i = 0; i < directories.size(); i++)
for (String directory : directories)
{
String dir = directories.get(i) + "/";
msg += "<li><a rel=\"directory\" href=\"" + encodeUri(uri + dir) + "\"><span class=\"dirname\">" + dir + "</span></a></b></li>";
String dir = directory + "/";
msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir)).append("\"><span class=\"dirname\">").append(dir).append("</span></a></b></li>");
}
msg += "</section>";
msg.append("</section>");
}
if (files.size() > 0)
{
msg += "<section class=\"files\">";
for (int i = 0; i < files.size(); i++)
msg.append("<section class=\"files\">");
for (String file : files)
{
String file = files.get(i);
msg += "<li><a href=\"" + encodeUri(uri + file) + "\"><span class=\"filename\">" + file + "</span></a>";
msg.append("<li><a href=\"").append(encodeUri(uri + file)).append("\"><span class=\"filename\">").append(file).append("</span></a>");
File curFile = new File(f, file);
long len = curFile.length();
msg += "&nbsp;<span class=\"filesize\">(";
msg.append("&nbsp;<span class=\"filesize\">(");
if (len < 1024)
{
msg += len + " bytes";
msg.append(len).append(" bytes");
}
else if (len < 1024 * 1024)
{
msg += len / 1024 + "." + (len % 1024 / 10 % 100) + " KB";
msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB");
}
else
{
msg += len / (1024 * 1024) + "." + len % (1024 * 1024) / 10 % 100 + " MB";
msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10 % 100).append(" MB");
}
msg += ")</span></li>";
msg.append(")</span></li>");
}
msg += "</section>";
msg.append("</section>");
}
msg += "</ul>";
msg.append("</ul>");
}
msg += "</body></html>";
return msg;
msg.append("</body></html>");
return msg.toString();
}
@Override

View File

@ -2,12 +2,11 @@ package me.totalfreedom.totalfreedommod.httpd.module;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.command.FreedomCommand;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
@ -24,16 +23,39 @@ import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
public class Module_help extends HTTPDModule
{
public Module_help(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
public Module_help(NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
private static String buildDescription(Command command)
{
StringBuilder sb = new StringBuilder();
sb.append(
"<li><span class=\"commandName\">{$CMD_NAME}</span> - Usage: <span class=\"commandUsage\">{$CMD_USAGE}</span>"
.replace("{$CMD_NAME}", escapeHtml4(command.getName().trim()))
.replace("{$CMD_USAGE}", escapeHtml4(command.getUsage().trim())));
if (!command.getAliases().isEmpty())
{
sb.append(
" - Aliases: <span class=\"commandAliases\">{$CMD_ALIASES}</span>"
.replace("{$CMD_ALIASES}", escapeHtml4(StringUtils.join(command.getAliases(), ", "))));
}
sb.append(
"<br><span class=\"commandDescription\">{$CMD_DESC}</span></li>\r\n"
.replace("{$CMD_DESC}", escapeHtml4(command.getDescription().trim())));
return sb.toString();
}
@Override
public String getBody()
{
final CommandMap map = FreedomCommand.getCommandMap();
if (map == null || !(map instanceof SimpleCommandMap))
if (!(map instanceof SimpleCommandMap))
{
return paragraph("Error loading commands.");
}
@ -60,14 +82,12 @@ public class Module_help extends HTTPDModule
pluginCommands.add(command);
}
final Iterator<Map.Entry<String, List<Command>>> it = commandsByPlugin.entrySet().iterator();
while (it.hasNext())
for (Map.Entry<String, List<Command>> entry : commandsByPlugin.entrySet())
{
final Map.Entry<String, List<Command>> entry = it.next();
final String pluginName = entry.getKey();
final List<Command> commands = entry.getValue();
Collections.sort(commands, new CommandComparator());
commands.sort(new CommandComparator());
responseBody.append(heading(pluginName, 2)).append("<ul>\r\n");
@ -80,7 +100,7 @@ public class Module_help extends HTTPDModule
continue;
}
Displayable tfmCommandLevel = FreedomCommand.getFrom(command).getPerms().level();
Displayable tfmCommandLevel = Objects.requireNonNull(FreedomCommand.getFrom(command)).getPerms().level();
if (lastTfmCommandLevel == null || lastTfmCommandLevel != tfmCommandLevel)
{
responseBody.append("</ul>\r\n").append(heading(tfmCommandLevel.getName(), 3)).append("<ul>\r\n");
@ -95,29 +115,6 @@ public class Module_help extends HTTPDModule
return responseBody.toString();
}
private static String buildDescription(Command command)
{
StringBuilder sb = new StringBuilder();
sb.append(
"<li><span class=\"commandName\">{$CMD_NAME}</span> - Usage: <span class=\"commandUsage\">{$CMD_USAGE}</span>"
.replace("{$CMD_NAME}", escapeHtml4(command.getName().trim()))
.replace("{$CMD_USAGE}", escapeHtml4(command.getUsage().trim())));
if (!command.getAliases().isEmpty())
{
sb.append(
" - Aliases: <span class=\"commandAliases\">{$CMD_ALIASES}</span>"
.replace("{$CMD_ALIASES}", escapeHtml4(StringUtils.join(command.getAliases(), ", "))));
}
sb.append(
"<br><span class=\"commandDescription\">{$CMD_DESC}</span></li>\r\n"
.replace("{$CMD_DESC}", escapeHtml4(command.getDescription().trim())));
return sb.toString();
}
@Override
public String getTitle()
{

View File

@ -1,18 +1,17 @@
package me.totalfreedom.totalfreedommod.httpd.module;
import java.io.File;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.banning.IndefiniteBanList;
import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.admin.Admin;
public class Module_indefbans extends HTTPDModule
{
public Module_indefbans(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
public Module_indefbans(NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override

View File

@ -1,7 +1,6 @@
package me.totalfreedom.totalfreedommod.httpd.module;
import java.util.Set;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools;
import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder;
@ -11,9 +10,9 @@ import org.reflections.Reflections;
public class Module_index extends HTTPDModule
{
public Module_index(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
public Module_index(NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override
@ -32,7 +31,7 @@ public class Module_index extends HTTPDModule
Set<Class<? extends HTTPDModule>> moduleClasses = r.getSubTypesOf(HTTPDModule.class);
for (Class c : moduleClasses)
for (Class<?> c : moduleClasses)
{
String name = c.getSimpleName().replace("Module_", "");

View File

@ -2,9 +2,9 @@ package me.totalfreedom.totalfreedommod.httpd.module;
import java.util.Collection;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -16,7 +16,7 @@ public class Module_list extends HTTPDModule
public Module_list(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override

View File

@ -7,13 +7,13 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools;
import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder;
import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Response;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringEscapeUtils;
@ -31,7 +31,13 @@ public class Module_logfile extends HTTPDModule
public Module_logfile(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
private static String getArg(String[] args, int index)
{
String out = (args.length == index + 1 ? args[index] : null);
return (out == null ? null : (out.trim().isEmpty() ? null : out.trim()));
}
@Override
@ -169,6 +175,40 @@ public class Module_logfile extends HTTPDModule
return entry != null && entry.isActive();
}
private enum ModuleMode
{
LIST("list"),
DOWNLOAD("download"),
INVALID(null);
//
private final String modeName;
ModuleMode(String modeName)
{
this.modeName = modeName;
}
public static ModuleMode getMode(String needle)
{
for (ModuleMode mode : values())
{
final String haystack = mode.toString();
if (haystack != null && haystack.equalsIgnoreCase(needle))
{
return mode;
}
}
return INVALID;
}
@Override
public String toString()
{
return this.modeName;
}
}
private static class LogFileTransferException extends Exception
{
@ -197,44 +237,4 @@ public class Module_logfile extends HTTPDModule
return response;
}
}
private static String getArg(String[] args, int index)
{
String out = (args.length == index + 1 ? args[index] : null);
return (out == null ? null : (out.trim().isEmpty() ? null : out.trim()));
}
private static enum ModuleMode
{
LIST("list"),
DOWNLOAD("download"),
INVALID(null);
//
private final String modeName;
private ModuleMode(String modeName)
{
this.modeName = modeName;
}
@Override
public String toString()
{
return this.modeName;
}
public static ModuleMode getMode(String needle)
{
for (ModuleMode mode : values())
{
final String haystack = mode.toString();
if (haystack != null && haystack.equalsIgnoreCase(needle))
{
return mode;
}
}
return INVALID;
}
}
}

View File

@ -1,9 +1,9 @@
package me.totalfreedom.totalfreedommod.httpd.module;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -15,7 +15,7 @@ public class Module_players extends HTTPDModule
public Module_players(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override

View File

@ -2,17 +2,17 @@ package me.totalfreedom.totalfreedommod.httpd.module;
import java.io.File;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.punishments.PunishmentList;
import me.totalfreedom.totalfreedommod.admin.Admin;
public class Module_punishments extends HTTPDModule
{
public Module_punishments(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
@Override

View File

@ -14,6 +14,7 @@ import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.httpd.HTMLGenerationTools;
import me.totalfreedom.totalfreedommod.httpd.HTTPDPageBuilder;
@ -22,7 +23,6 @@ import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Method;
import me.totalfreedom.totalfreedommod.httpd.NanoHTTPD.Response;
import me.totalfreedom.totalfreedommod.player.PlayerData;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringEscapeUtils;
@ -48,7 +48,13 @@ public class Module_schematic extends HTTPDModule
public Module_schematic(TotalFreedomMod plugin, NanoHTTPD.HTTPSession session)
{
super(plugin, session);
super(session);
}
private static String getArg(String[] args, int index)
{
String out = (args.length == index + 1 ? args[index] : null);
return (out == null ? null : (out.trim().isEmpty() ? null : out.trim()));
}
@Override
@ -285,6 +291,41 @@ public class Module_schematic extends HTTPDModule
return ((adminEntry != null && adminEntry.isActive()) || data != null && data.isMasterBuilder());
}
private enum ModuleMode
{
LIST("list"),
UPLOAD("upload"),
DOWNLOAD("download"),
INVALID(null);
//
private final String modeName;
ModuleMode(String modeName)
{
this.modeName = modeName;
}
public static ModuleMode getMode(String needle)
{
for (ModuleMode mode : values())
{
final String haystack = mode.toString();
if (haystack != null && haystack.equalsIgnoreCase(needle))
{
return mode;
}
}
return INVALID;
}
@Override
public String toString()
{
return this.modeName;
}
}
private static class SchematicTransferException extends Exception
{
@ -313,45 +354,4 @@ public class Module_schematic extends HTTPDModule
return response;
}
}
private static String getArg(String[] args, int index)
{
String out = (args.length == index + 1 ? args[index] : null);
return (out == null ? null : (out.trim().isEmpty() ? null : out.trim()));
}
private static enum ModuleMode
{
LIST("list"),
UPLOAD("upload"),
DOWNLOAD("download"),
INVALID(null);
//
private final String modeName;
ModuleMode(String modeName)
{
this.modeName = modeName;
}
@Override
public String toString()
{
return this.modeName;
}
public static ModuleMode getMode(String needle)
{
for (ModuleMode mode : values())
{
final String haystack = mode.toString();
if (haystack != null && haystack.equalsIgnoreCase(needle))
{
return mode;
}
}
return INVALID;
}
}
}