Commit 3cf3583b authored by Sefa Eyeoglu's avatar Sefa Eyeoglu

Prepared pom.xml for Maven Central, Switched from log4j to java.util.logging, Small tweaks

parent d66df4a1
......@@ -8,41 +8,51 @@
<artifactId>implify</artifactId>
<version>0.0.1</version>
<name>Implify Core</name>
<description>Implify HTTP Server.</description>
<url>https://github.com/Scrumplex/Implify</url>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>Sefa Eyeoglu</name>
<email>contact@scrumplex.net</email>
<url>https://scrumplex.net</url>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/Scrumplex/Implify.git</connection>
<developerConnection>scm:git:ssh://github.com:Scrumplex/Implify.git</developerConnection>
<url>http://github.com/Scrumplex/Implify.git</url>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.build.timestamp.format>dd-MM-yyyy'T'HH:mm:ss'Z'</maven.build.timestamp.format>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>15.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.build.timestamp.format>dd-MM-yyyy'T'HH:mm:ss'Z'</maven.build.timestamp.format>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
......@@ -55,20 +65,40 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<version>3.0.0</version>
<configuration>
<archive>
<manifest>
<mainClass>net.scrumplex.implify.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>implify-full</finalName>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<configuration>
<show>public</show>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
</project>
......@@ -4,15 +4,17 @@ import net.scrumplex.implify.core.ImplifyServer;
import net.scrumplex.implify.core.exchange.handler.FileSystemHTTPHandler;
import net.scrumplex.implify.exceptions.ImplifyException;
import java.nio.file.Paths;
import java.io.File;
import java.util.logging.Level;
public class Main {
public static void main(String[] args) {
ImplifyServer implifyServer = new ImplifyServer(8080, "default");
implifyServer.setLogLevel(Level.ALL);
implifyServer.setHttpHandler(new FileSystemHTTPHandler(new File("").getAbsoluteFile(), "index.html"));
try {
implifyServer.start();
implifyServer.setHttpHandler(new FileSystemHTTPHandler(Paths.get("").toFile(), "index.html"));
} catch (ImplifyException e) {
e.printStackTrace();
}
......
package net.scrumplex.implify.core;
import net.scrumplex.implify.concurrent.ImplifyThreadFactory;
import net.scrumplex.implify.core.exchange.*;
import net.scrumplex.implify.core.exchange.HTTPRequest;
import net.scrumplex.implify.core.exchange.HTTPResponse;
import net.scrumplex.implify.core.exchange.handler.DefaultHTTPHandler;
import net.scrumplex.implify.core.exchange.handler.HTTPHandler;
import net.scrumplex.implify.core.exchange.preprocess.DefaultHTTPPreprocessor;
import net.scrumplex.implify.core.exchange.preprocess.HTTPPreprocessor;
import net.scrumplex.implify.core.exchange.socket.DefaultSocketHandler;
import net.scrumplex.implify.core.exchange.socket.SocketHandler;
import net.scrumplex.implify.exceptions.ExceptionHandler;
import net.scrumplex.implify.exceptions.ImplifyException;
import net.scrumplex.implify.exceptions.ImplifyExceptionHandler;
import net.scrumplex.implify.exceptions.ExceptionHandler;
import net.scrumplex.implify.core.exchange.handler.HTTPHandler;
import net.scrumplex.implify.core.exchange.preprocess.HTTPPreprocessor;
import net.scrumplex.implify.core.exchange.socket.SocketHandler;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
public class ImplifyServer {
......@@ -32,6 +35,7 @@ public class ImplifyServer {
private final String identifier;
private boolean running;
private boolean gzipEnabled;
private ImplifyThreadFactory threadFactory;
private ExceptionHandler exceptionHandler;
......@@ -56,15 +60,42 @@ public class ImplifyServer {
this.port = port;
this.backlog = backlog;
this.identifier = identifier;
exceptionHandler = new ImplifyExceptionHandler(this);
threadFactory = new ImplifyThreadFactory(this);
this.exceptionHandler = new ImplifyExceptionHandler(this);
this.threadFactory = new ImplifyThreadFactory(this);
//May be changed by user if needed
socketHandler = new DefaultSocketHandler();
httpPreprocessor = new DefaultHTTPPreprocessor();
this.socketHandler = new DefaultSocketHandler();
this.httpPreprocessor = new DefaultHTTPPreprocessor();
//Should be changed by user
httpHandler = new DefaultHTTPHandler();
this.httpHandler = new DefaultHTTPHandler();
this.logger = Logger.getLogger("implify_" + identifier);
Handler handler = new Handler() {
@Override
public void publish(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append("[" + record.getLevel().getName() + "] ");
sb.append(record.getMessage()).append('\n');
if (record.getLevel() == Level.WARNING || record.getLevel() == Level.SEVERE) {
System.err.println(sb.toString());
return;
}
System.out.println(sb.toString());
}
this.logger = LogManager.getLogger("implify_" + identifier);
@Override
public void flush() {
System.out.flush();
System.err.flush();
}
@Override
public void close() throws SecurityException {
//ignored
}
};
this.logger.addHandler(handler);
this.logger.setUseParentHandlers(false);
}
/**
......@@ -88,6 +119,7 @@ public class ImplifyServer {
while (running) {
try {
Socket socket = serverSocket.accept();
logger.log(Level.FINE, "Connection from " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort());
getThreadFactory().newThread(() -> {
try {
HTTPRequest request = getSocketHandler().handle(this, socket);
......@@ -105,15 +137,18 @@ public class ImplifyServer {
response = getHttpHandler().handle(this, request, response);
if (response == null)
response = HTTPUtils.getInternalServerErrorResponse(this, request);
if(!response.isSaved())
if (!response.isSaved())
response.save();
}
logger.log(Level.FINE, "HTTP request for " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + " completed. Sending response...");
//Send to client
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeBytes("HTTP/1.1 " + response.getStatusCode().getCode() + " " + response.getStatusCode().getCodeName() + "\n");
//Send the headers
for (String headerKey : response.getHeaders().keySet()) {
String headerValue = response.getHeaders().get(headerKey);
out.writeBytes(headerKey + ": " + headerValue + "\n");
......@@ -121,11 +156,18 @@ public class ImplifyServer {
out.writeBytes("\n");
OutputStream dataOut = out;
if (response.isCompressed()) {
dataOut = new GZIPOutputStream(out);
if (response.isCompressed() && gzipEnabled)
dataOut = new GZIPOutputStream(dataOut);
//Send the response data
InputStream dataIn = response.getResponseData();
byte[] buffer = new byte[2048];
int length;
while ((length = dataIn.read(buffer)) != -1) {
dataOut.write(buffer, 0, length);
}
IOUtils.copy(response.getResponseData(), dataOut);
response.getResponseData().close();
dataIn.close();
dataOut.close();
out.close();
response.close();
......@@ -140,6 +182,7 @@ public class ImplifyServer {
}, "implify_" + getInstanceIdentifier());
mainThread.start();
logger.log(Level.FINE, "Implify " + getInstanceIdentifier() + " started!");
}
/**
......@@ -160,14 +203,6 @@ public class ImplifyServer {
}
}
public ExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
private void setExceptionHandler(@NotNull ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
public String getIdentifier() {
return identifier;
}
......@@ -176,19 +211,38 @@ public class ImplifyServer {
return "instance_" + identifier;
}
public ImplifyThreadFactory getThreadFactory() {
public boolean isRunning() {
return running;
}
private ImplifyThreadFactory getThreadFactory() {
return threadFactory;
}
public HTTPPreprocessor getHttpPreprocessor() {
return httpPreprocessor;
public Logger getLogger() {
return logger;
}
public void setHttpPreprocessor(@NotNull HTTPPreprocessor httpPreprocessor) {
this.httpPreprocessor = httpPreprocessor;
public void setLogger(@NotNull Logger logger) {
this.logger = logger;
}
public SocketHandler getSocketHandler() {
public void setLogLevel(@NotNull Level level) {
logger.setLevel(level);
for (Handler h : logger.getHandlers()) {
h.setLevel(level);
}
}
public ExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
public void setExceptionHandler(@NotNull ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
private SocketHandler getSocketHandler() {
return socketHandler;
}
......@@ -196,23 +250,27 @@ public class ImplifyServer {
this.socketHandler = socketHandler;
}
public Logger getLogger() {
return logger;
}
public void setLogger(@NotNull Logger logger) {
this.logger = logger;
private HTTPPreprocessor getHttpPreprocessor() {
return httpPreprocessor;
}
public boolean isRunning() {
return running;
public void setHttpPreprocessor(@NotNull HTTPPreprocessor httpPreprocessor) {
this.httpPreprocessor = httpPreprocessor;
}
public HTTPHandler getHttpHandler() {
private HTTPHandler getHttpHandler() {
return httpHandler;
}
public void setHttpHandler(@NotNull HTTPHandler httpHandler) {
this.httpHandler = httpHandler;
}
public boolean isGzipEnabled() {
return gzipEnabled;
}
public void setGzipEnabled(boolean gzipEnabled) {
this.gzipEnabled = gzipEnabled;
}
}
......@@ -78,7 +78,7 @@ public class HTTPRequest {
/**
* Getter method for socket.
*
* @return socket as {@link java.net,Socket}
* @return socket as {@link java.net.Socket}
*/
public Socket getSocket() {
return socket;
......
......@@ -7,6 +7,7 @@ import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
......@@ -84,7 +85,7 @@ public class HTTPResponse {
}
public void setCompressed(boolean compressed) {
if (isSaved() || isClosed())
if (isSaved() || isClosed() || serverInstance.isGzipEnabled())
return;
this.compressed = compressed;
}
......@@ -104,7 +105,11 @@ public class HTTPResponse {
public void setResponseData(@NotNull String responseData) {
if (isSaved() || isClosed())
return;
setResponseData(responseData.getBytes());
try {
setResponseData(responseData.getBytes("UTF-8"));
} catch (UnsupportedEncodingException ignored) {
setResponseData(responseData.getBytes());
}
}
public void setResponseData(@NotNull InputStream responseData) {
......
......@@ -35,7 +35,7 @@ public class DefaultHTTPPreprocessor implements HTTPPreprocessor {
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put("Accept-Ranges", "bytes");
responseHeaders.put("Connection", "close"); //TODO: implement keep-alive
if (response.isCompressed())
if (response.isCompressed() && serverInstance.isGzipEnabled())
responseHeaders.put("Content-Encoding", "gzip");
responseHeaders.put("Date", dateFormat.format(calendar.getTime()));
responseHeaders.put("Server", "Implify/1.0");
......
......@@ -2,6 +2,8 @@ package net.scrumplex.implify.exceptions;
import net.scrumplex.implify.core.ImplifyServer;
import java.util.logging.Level;
public class ImplifyExceptionHandler implements ExceptionHandler {
private final ImplifyServer serverInstance;
......@@ -12,12 +14,12 @@ public class ImplifyExceptionHandler implements ExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
serverInstance.getLogger().error("An error occurred in thread " + t.getName());
serverInstance.getLogger().log(Level.SEVERE, "An error occurred in thread " + t.getName());
e.printStackTrace();
}
public void caughtException(Throwable e, String context) {
serverInstance.getLogger().error("An error occurred in context " + context);
serverInstance.getLogger().log(Level.SEVERE, "An error occurred in context " + context);
e.printStackTrace();
}
}
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment