Skip to content

Commit

Permalink
Refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
simonwep committed Oct 11, 2018
1 parent 2836fb2 commit fced7c5
Show file tree
Hide file tree
Showing 17 changed files with 117 additions and 73 deletions.
5 changes: 3 additions & 2 deletions src/main/java/express/Express.java
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public Object get(String key) {
*/
public void setExecutor(Executor executor) throws IOException {
if (httpServer != null) {
throw new IOException("Cannot set the executor after the server has starderd!");
throw new IOException("Cannot set executor after the server has stardet!");
} else {
this.executor = executor;
}
Expand Down Expand Up @@ -371,8 +371,9 @@ public void listen(ExpressListener onStart, int port) {
httpServer.start();

// Fire listener
if (onStart != null)
if (onStart != null) {
onStart.action();
}

} catch (IOException e) {
e.printStackTrace();
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/express/ExpressListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,5 @@
* Listener for express actions
*/
public interface ExpressListener {

void action();

}
30 changes: 21 additions & 9 deletions src/main/java/express/filter/FilterImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,19 @@ public FilterImpl(String requestMethod, String context, HttpRequestHandler httpR
}

public void setRoot(String root) {
if (root == null || root.isEmpty())

// Ignore empty root
if (root == null || root.isEmpty()) {
return;
}

if (root.charAt(0) != '/')
if (root.charAt(0) != '/') {
root = '/' + root;
}

if (root.charAt(root.length() - 1) != '/')
if (root.charAt(root.length() - 1) != '/') {
root += '/';
}

this.root = normalizePath(root);
this.fullContext = normalizePath(this.root + context);
Expand All @@ -69,8 +74,9 @@ public void handle(Request req, Response res) {

// Parse params
HashMap<String, String> params = matchURL(fullContext, requestPath);
if (params == null)
if (params == null) {
return;
}

// Save parameter to request object
req.setParams(params);
Expand All @@ -79,13 +85,15 @@ public void handle(Request req, Response res) {
params.forEach((s, s2) -> {
HttpRequestHandler request = parameterListener.get(s);

if (request != null)
if (request != null) {
request.handle(req, res);
}
});

// Check if the response is closed
if (res.isClosed())
if (res.isClosed()) {
return;
}

// Handle request
req.setContext(context);
Expand All @@ -110,11 +118,14 @@ private HashMap<String, String> matchURL(String filter, String url) {
val.setLength(0);

fi++;
while (fi < fc.length && fc[fi] != '/')

while (fi < fc.length && fc[fi] != '/') {
key.append(fc[fi++]);
}

while (ui < uc.length && uc[ui] != '/')
while (ui < uc.length && uc[ui] != '/') {
val.append(uc[ui++]);
}

try {
String decVal = URLDecoder.decode(val.toString(), "UTF8");
Expand Down Expand Up @@ -149,8 +160,9 @@ private String normalizePath(String context) {

sb.append(chars[0]);
for (int i = 1; i < chars.length; i++) {
if ((chars[i] == '/' && chars[i - 1] != '/') || chars[i] != '/')
if ((chars[i] == '/' && chars[i - 1] != '/') || chars[i] != '/') {
sb.append(chars[i]);
}
}

return sb.toString();
Expand Down
25 changes: 17 additions & 8 deletions src/main/java/express/filter/FilterLayerHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ public FilterLayerHandler(int layers) {

// Create & initialize layers
this.layers = new FilterLayer[layers];
for (int i = 0; i < this.layers.length; i++)
for (int i = 0; i < this.layers.length; i++) {
this.layers[i] = new FilterLayer<>();
}
}

public void handle(HttpExchange httpExchange, Express express) {
Expand All @@ -34,8 +35,9 @@ public void handle(HttpExchange httpExchange, Express express) {
for (FilterLayer chain : layers) {
chain.filter(request, response);

if (response.isClosed())
if (response.isClosed()) {
return;
}
}
}

Expand All @@ -48,10 +50,13 @@ public void handle(HttpExchange httpExchange, Express express) {
@SuppressWarnings("unchecked")
public void add(int level, HttpRequestHandler handler) {

if (level >= layers.length)
if (level >= layers.length) {
throw new IndexOutOfBoundsException("Out of bounds: " + level + " > " + layers.length);
if (level < 0)
}

if (level < 0) {
throw new IndexOutOfBoundsException("Cannot be under zero: " + level + " < 0");
}

layers[level].add(handler);
}
Expand All @@ -66,11 +71,13 @@ public void combine(FilterLayerHandler filterLayerHandler) {
if (filterLayerHandler != null) {
FilterLayer[] chains = filterLayerHandler.getLayers();

if (chains.length != layers.length)
if (chains.length != layers.length) {
throw new ExpressException("Cannot add an filterLayerHandler with different layers sizes: " + chains.length + " != " + layers.length);
}

for (int i = 0; i < chains.length; i++)
for (int i = 0; i < chains.length; i++) {
layers[i].addAll(chains[i].getFilter());
}
}
}

Expand All @@ -80,11 +87,13 @@ public void combine(FilterLayerHandler filterLayerHandler) {
* @param layerConsumer An consumer for the layers
*/
public void forEach(Consumer<FilterLayer> layerConsumer) {
if (layerConsumer == null)
if (layerConsumer == null) {
return;
}

for (FilterLayer layer : layers)
for (FilterLayer layer : layers) {
layerConsumer.accept(layer);
}
}

private FilterLayer[] getLayers() {
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/express/http/Cookie.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ public class Cookie {
public Cookie(String name, String value) {
name = name.trim();

if (name.isEmpty() || name.charAt(0) == '$')
if (name.isEmpty() || name.charAt(0) == '$') {
throw new IllegalArgumentException("Illegal cookie name");
}

this.name = name;
this.value = value;
Expand Down Expand Up @@ -203,6 +204,7 @@ public boolean equals(Object obj) {
if (!other.getExpire().equals(this.getExpire())) return false;
if (other.getMaxAge() != this.getMaxAge()) return false;
if (!other.getSameSite().equals(this.getSameSite())) return false;

return other.getPath().equals(this.getPath());
}
return super.equals(obj);
Expand Down
10 changes: 7 additions & 3 deletions src/main/java/express/http/CookieFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,16 @@ public static Cookie fromString(String cookieString) {
public static HashMap<String, Cookie> fromStrings(String[] stringCookies) {
HashMap<String, Cookie> cookies = new HashMap<>();

if (stringCookies == null || stringCookies.length == 0)
if (stringCookies == null || stringCookies.length == 0) {
return cookies;
}

for (String s : stringCookies) {
Cookie cookie = fromString(s);
if (cookie != null)

if (cookie != null) {
cookies.put(cookie.getName(), cookie);
}
}

return cookies;
Expand Down Expand Up @@ -109,8 +112,9 @@ private static Cookie addField(Cookie cookie, String key, String value) {
private static boolean isInteger(String str) {
char[] chars = str.toCharArray();

for (char c : chars)
for (char c : chars) {
if (c < 48 || c > 57) return false;
}

return true;
}
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/express/http/SameSite.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
* @author Simon Reinisch
*/
public enum SameSite {

STRICT,
LAX

}
48 changes: 26 additions & 22 deletions src/main/java/express/http/request/Authorization.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,38 +29,19 @@ public Authorization(String authHeader) {
this.data = parts[1];
}

/**
* @return The Authorization type
*/
public String getType() {
return type;
}

/**
* @return The Authorization data
*/
public String getData() {
return data;
}

/**
* @return The Authorization data base64 decoded
*/
public String getDataBase64Decoded() {
return new String(Base64.getDecoder().decode(data));
}

/**
* @return A list of authorization options that are contained in the given request.
* Authorization options can be separated by a comma in the Authorization header.
*/
public static List<Authorization> get(Request req) {
List<String> headerVals = req.getHeader(HEADER_NAME);

if (!headerVals.isEmpty()) {
String authHeader = headerVals.get(0);
return Collections.unmodifiableList(Stream.of(authHeader.split(","))
.map(Authorization::new).collect(Collectors.toList()));
}

return Collections.emptyList();
}

Expand All @@ -73,7 +54,9 @@ public static List<Authorization> get(Request req) {
public static boolean validate(Request req, Predicate<Authorization>... validators) {
for (Authorization auth : get(req)) {
for (Predicate<Authorization> validator : validators) {
if (validator.test(auth)) return true;
if (validator.test(auth)) {
return true;
}
}
}
return false;
Expand All @@ -88,4 +71,25 @@ public static boolean validate(Request req, Predicate<Authorization>... validato
public static Predicate<Authorization> validator(String type, String data) {
return (auth -> auth.getType().equals(type) && auth.getData().equals(data));
}

/**
* @return The Authorization type
*/
public String getType() {
return type;
}

/**
* @return The Authorization data
*/
public String getData() {
return data;
}

/**
* @return The Authorization data base64 decoded
*/
public String getDataBase64Decoded() {
return new String(Base64.getDecoder().decode(data));
}
}
4 changes: 2 additions & 2 deletions src/main/java/express/http/request/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public void pipe(Path f, int bufferSize) throws IOException {
}

/**
* Get an request cookie by name.
* Get a request cookie by name.
*
* @param name The cookie name.
* @return The cookie, null if there is no cookie with this name.
Expand All @@ -145,7 +145,7 @@ public HashMap<String, Cookie> getCookies() {
}

/**
* Add an the content from an middleware
* Add a the content from a middleware
*
* @param middleware The middleware
* @param middlewareData The data from the middleware
Expand Down
7 changes: 5 additions & 2 deletions src/main/java/express/http/request/RequestUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@ static HashMap<String, Cookie> parseCookies(Headers headers) {
static HashMap<String, String> parseRawQuery(String rawQuery) {
HashMap<String, String> querys = new HashMap<>();

if (rawQuery == null)
// Return empty map on null
if (rawQuery == null) {
return querys;
}

StringBuilder key = new StringBuilder();
StringBuilder val = new StringBuilder();
Expand Down Expand Up @@ -96,8 +98,9 @@ static HashMap<String, String> parseRawQuery(String rawQuery) {
}
}

if (c != '=' && c != '&')
if (c != '=' && c != '&') {
querys.put(key.toString(), val.toString());
}

return querys;
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/express/http/response/Response.java
Original file line number Diff line number Diff line change
Expand Up @@ -135,17 +135,17 @@ public String getContentType() {
*
* @param contentType - The contentType
*/
public void setContentType(MediaType contentType) {
this.contentType = contentType.getMIME();
public void setContentType(String contentType) {
this.contentType = contentType;
}

/**
* Set the contentType for this response.
*
* @param contentType - The contentType
*/
public void setContentType(String contentType) {
this.contentType = contentType;
public void setContentType(MediaType contentType) {
this.contentType = contentType.getMIME();
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/express/middleware/CookieSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ public void onUpdate() {
long current = System.currentTimeMillis();

cookies.forEach((cookieHash, cookie) -> {
if (current > cookie.getCreated() + cookie.getMaxAge())
if (current > cookie.getCreated() + cookie.getMaxAge()) {
cookies.remove(cookieHash);
}
});
}

Expand Down
2 changes: 0 additions & 2 deletions src/main/java/express/middleware/DotFiles.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
* @author Simon Reinisch
*/
public enum DotFiles {

IGNORE,
DENY,
ALLOW

}
Loading

0 comments on commit fced7c5

Please sign in to comment.