Skip to content

Commit

Permalink
conflict fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
zjhch123 committed Feb 11, 2017
2 parents fb3fb7d + 8fefea6 commit a67b6d2
Show file tree
Hide file tree
Showing 28 changed files with 174 additions and 62 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

<build>
Expand Down
52 changes: 46 additions & 6 deletions src/main/java/com/zjh/tears/config/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import com.zjh.tears.listener.socket.HeaderSocketListener;
import com.zjh.tears.listener.socket.SocketListener;
import com.zjh.tears.util.ClassParse;
import com.zjh.tears.util.Util;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

Expand Down Expand Up @@ -48,59 +50,90 @@ public final class Config {
public static Set<File> ACCEPT_FILE = new HashSet<>();
public static Set<File> EXCEPT_FILE = new HashSet<>();

static {
private static Logger logger = Logger.getLogger(Config.class);

static {
logger.debug("Load Config File...");
File configFile = new File(Config.class.getClassLoader().getResource("config.json").getFile());
try {
long startTime = System.currentTimeMillis();
logger.debug("\n _____ _____ ___ _____ _____ \n" +
"|_ _| | ____| / | | _ \\ / ___/ \n" +
" | | | |__ / /| | | |_| | | |___ \n" +
" | | | __| / / | | | _ / \\___ \\ \n" +
" | | | |___ / / | | | | \\ \\ ___| | \n" +
" |_| |_____| /_/ |_| |_| \\_\\ /_____/ - zjh\n");
JSONObject config = new JSONObject(Files.readAllLines(configFile.toPath()).stream().collect(Collectors.joining()));
logger.debug("Load Config File SUCCESS!");
logger.debug("Setting...");
JSONObject serverConfig = config.getJSONObject("serverConfig");
JSONObject pageConfig = config.getJSONObject("pageConfig");
JSONObject acceptConfig = config.getJSONObject("acceptConfig");
Config.INIT_SERVER_CONFIG(serverConfig);
Config.INIT_PAGE_CONFIG(pageConfig);
Config.INIT_ACCEPT_CONFIG(acceptConfig);
long endTime = System.currentTimeMillis();
logger.debug("Config SUCCESS! at " + (endTime - startTime) + "ms");
logger.debug("Server start...");
} catch (IOException e) {
e.printStackTrace();
logger.error(Util.stackTraceToString(e));
System.exit(-1);
} catch (Exception e) {
e.printStackTrace();
logger.error(Util.stackTraceToString(e));
System.exit(-1);
}
}

private static final void INIT_SERVER_CONFIG(final JSONObject serverConfig) throws Exception {
Config.PORT = serverConfig.getInt("port");
logger.debug("server port - " + Config.PORT);
Config.THREAD_POOL_SIZE = serverConfig.getInt("threadPoolSize");
logger.debug("server thread pool size - " + Config.THREAD_POOL_SIZE);
Config.SERVER_NAME = serverConfig.getString("serverName");
logger.debug("server name - " + Config.SERVER_NAME);
Config.STATIC_ROOT_FILE = serverConfig.getString("staticRootFile");
logger.debug("static root file - " + Config.STATIC_ROOT_FILE);
Config.DEFAULT_CHARSET = serverConfig.getString("defaultCharset");
logger.debug("default charset - " + Config.DEFAULT_CHARSET);
SocketFilter headerFilter = Config.SOCKET_FILTER_HEADER;
logger.debug("Init Socket Filter...");
for (Object obj : serverConfig.getJSONArray("socketFilter")) {
String className = (String) obj;
logger.debug("init class - " + className);
SocketFilter filter = (SocketFilter) ClassParse.getInstance().getObject(className);
headerFilter.setNext(filter);
headerFilter = filter;
}

logger.debug("Init Socket Filter SUCCESS!");
SocketListener headerListener = Config.SOCKET_LISTENER_HEADER;
logger.debug("Init Socket Listener...");
for (Object obj : serverConfig.getJSONArray("socketListener")) {
String className = (String) obj;
logger.debug("init class - " + className);
SocketListener listener = (SocketListener) ClassParse.getInstance().getObject(className);
headerListener.setNext(listener);
headerListener = listener;
}

logger.debug("Init Socket Listener SUCCESS!");
HTTPHandler headerHandler = Config.HTTP_HANDLER_HEADER;
logger.debug("Init HTTP Handler...");
for (Object obj : serverConfig.getJSONArray("httpHandler")) {
String className = (String) obj;
logger.debug("init class - " + className);
HTTPHandler handler = (HTTPHandler) ClassParse.getInstance().getObject(className);
headerHandler.setNext(handler);
headerHandler = handler;
}

logger.debug("Init HTTP Handler SUCCESS!");
logger.debug("Init Static File Strategy...");
for (Object obj : serverConfig.getJSONArray("staticFileStrategy")) {
JSONObject strategy = (JSONObject) obj;
STATIC_FILE_STRATEGYS.put(strategy.getString("name"), strategy.getString("strategy"));
String strategyName = strategy.getString("name");
String strategyClass = strategy.getString("strategy");
logger.debug("init strategy - " + strategyName + ", class - " + strategyClass);
STATIC_FILE_STRATEGYS.put(strategyName, strategyClass);
}
}

Expand All @@ -109,17 +142,24 @@ private static final void INIT_PAGE_CONFIG(final JSONObject pageConfig) {
String index = (String) obj;
Config.DEFAULT_INDEX.add(index);
}
logger.debug("set default Index - " + Config.DEFAULT_INDEX);
for (Object obj : pageConfig.getJSONArray("errorPages")) {
JSONObject errorPage = (JSONObject) obj;
Config.ERR_PAGES.put(errorPage.getInt("code"), errorPage.getString("page"));
int code = errorPage.getInt("code");
String page = errorPage.getString("page");
Config.ERR_PAGES.put(code, page);
logger.debug("set error Page - code " + code + ", page " + page);
}
}

private static final void INIT_ACCEPT_CONFIG(final JSONObject acceptConfig) {
Config.ACCEPT_CONFIG_USAGE = acceptConfig.optBoolean("usage", false);
logger.debug("accept config usage? - " + Config.ACCEPT_CONFIG_USAGE);
if(Config.ACCEPT_CONFIG_USAGE) {
JSONArray accept = acceptConfig.getJSONArray("accept");
logger.debug("load accept path pattern - " + accept);
JSONArray except = acceptConfig.getJSONArray("except");
logger.debug("load except path pattern - " + except);
Config.initFile(true, accept);
Config.initFile(false, except);
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/com/zjh/tears/factory/RequestFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import com.zjh.tears.model.HTTPMethod;
import com.zjh.tears.model.Request;
import com.zjh.tears.model.SocketObject;

import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -42,10 +43,9 @@ private void initBody(String line, Request req) {
req.setBody(line);
}

public Request create(String requestSource) {
Request request = new Request();
request.setRequestSource(requestSource);
String[] analyStringArray = requestSource.split("\n");
public Request create(SocketObject socketObject) {
Request request = socketObject.getRequest();
String[] analyStringArray = request.getRequestSource().split("\n");
String firstLine = analyStringArray[0];
StringBuilder headersBuilder = new StringBuilder();
StringBuilder bodyBuilder = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
public class HTTPRequestSocketFilter extends SocketFilter {
@Override
public void execute(SocketObject socketObject) throws FilterException {
if(socketObject.getRequestSource() == null) {
if(socketObject.getRequest().getRequestSource() == null || socketObject.getRequest().getRequestSource().length() == 0) {
throw new FilterException();
}
String firstLine = socketObject.getRequestSource().split("\n")[0];
String firstLine = socketObject.getRequest().getRequestSource().split("\n")[0];
if(firstLine == null) {
throw new FilterException();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@
public class DebugSocketListener extends SocketListener {
@Override
public void preHandler(SocketObject socketObject) {
System.out.println("*** debug socket listener pre ***");
System.out.println("*** request ***\n" + socketObject.getRequest().getRequestSource());
}

@Override
public void afterHandler(SocketObject socketObject) {
System.out.println("*** debug socket listener after ***");
System.out.println("*** response ***\n" + new String(socketObject.getResponseSource()));
}

}
21 changes: 21 additions & 0 deletions src/main/java/com/zjh/tears/listener/socket/LogSocketListener.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.zjh.tears.listener.socket;

import com.zjh.tears.model.Request;
import com.zjh.tears.model.Response;
import com.zjh.tears.model.SocketObject;
import org.apache.log4j.Logger;

/**
* Created by zhangjiahao on 2017/2/10.
*/
public class LogSocketListener extends SocketListener {

private Logger logger = Logger.getLogger(this.getClass());

@Override
public void afterHandler(SocketObject socketObject) {
Request request = socketObject.getRequest();
Response response = socketObject.getResponse();
logger.info(request.getMethod() + " " + request.getPath() + " " + response.getCode() + " " + response.getMessage());
}
}

This file was deleted.

14 changes: 14 additions & 0 deletions src/main/java/com/zjh/tears/logger/MyAppender.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.zjh.tears.logger;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Priority;

/**
* Created by zhangjiahao on 2017/2/11.
*/
public class MyAppender extends DailyRollingFileAppender {
public boolean isAsSevereAsThreshold(Priority priority) {
//只判断是否相等,而不判断优先级
return this.getThreshold().equals(priority);
}
}
27 changes: 15 additions & 12 deletions src/main/java/com/zjh/tears/model/SocketObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ public class SocketObject {
private OutputStream os;
private BufferedReader br;

private String requestSource;

private byte[] responseSource;
private Request request;
private Response response;

public SocketObject(Socket socket) {
this.socket = socket;
Expand All @@ -27,10 +26,6 @@ public Socket getSocket() {
return this.socket;
}

public String getRequestSource() {
return this.requestSource;
}

public BufferedReader openBufferedReader() throws IOException {
if (this.br == null) {
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Expand Down Expand Up @@ -71,7 +66,7 @@ public void read() throws IOException {
char ch = (char) br.read();
sb.append(ch);
}
this.requestSource = sb.toString();
this.getRequest().setRequestSource(sb.toString());
}

public void response(byte[] data) throws IOException {
Expand Down Expand Up @@ -100,12 +95,20 @@ public void destory() {
}
}

public void setResponseSource(byte[] responseSource) {
this.responseSource = responseSource;
public void setResponse(Response res) {
this.response = res;
}
public Response getResponse() {
return this.response;
}
public void setRequest(Request req) {this.request = req;}
public Request getRequest() {
if(this.request == null)
this.request = new Request();
return this.request;
}

public byte[] getResponseSource() {
return responseSource;
return this.response.getBytes();
}

}
6 changes: 3 additions & 3 deletions src/main/java/com/zjh/tears/process/HTTPProcess.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public byte[] getResponse(SocketObject socketObject) throws FilterException {
}

public byte[] process(SocketObject socketObject) {
Request request = requestFactory.create(socketObject.getRequestSource());
Request request = requestFactory.create(socketObject);
Response response = this.responseProcess.getResponse(request);
socketObject.setResponseSource(response.getBytes());
return socketObject.getResponseSource();
socketObject.setResponse(response);
return socketObject.getResponse().getBytes();
}
}
8 changes: 6 additions & 2 deletions src/main/java/com/zjh/tears/process/SocketProcess.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.zjh.tears.exception.FilterException;
import com.zjh.tears.manager.SocketChainManager;
import com.zjh.tears.model.SocketObject;
import com.zjh.tears.util.Util;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.Socket;
Expand All @@ -15,6 +17,8 @@ public class SocketProcess {
private Socket socket;
private HTTPProcess httpProcess;

private Logger logger = Logger.getLogger(this.getClass());

public SocketProcess(Socket socket) {
this.socket = socket;
this.httpProcess = new HTTPProcess();
Expand All @@ -28,9 +32,9 @@ public void process() {
byte[] res = httpProcess.getResponse(socketObject);
socketObject.response(res);
} catch (IOException e){
e.printStackTrace();
logger.warn(Util.stackTraceToString(e));
} catch (FilterException e) {
socketObject.destory();
// logger.warn(Util.stackTraceToString(e)); 这里还没想好怎么处理
} finally {
socketObject.destory();
}
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/com/zjh/tears/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* Created by zhangjiahao on 2017/2/8.
Expand Down Expand Up @@ -44,6 +46,10 @@ public static String getGMTString() {
return Util.getGMTString(new Date());
}

public static String stackTraceToString(Throwable e) {
return Stream.of(e.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.joining("\n"));
}

public static void closeFileInputStream(FileInputStream fis) {
if (fis != null) {
try {
Expand Down
11 changes: 5 additions & 6 deletions src/main/resources/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@
"serverConfig": {
"port": "8080",
"threadPoolSize": "10",
"serverName": "Tears 1.25 - beta",
"serverName": "Tears 1.3 - beta",
"staticRootFile": "/Users/zhangjiahao/Desktop/play",
"defaultCharset": "UTF-8",
"socketFilter": [
"com.zjh.tears.filter.socket.HTTPRequestSocketFilter",
"com.zjh.tears.filter.socket.TestSocketFilter"
"com.zjh.tears.filter.socket.HTTPRequestSocketFilter"
],
"socketListener": [
"com.zjh.tears.listener.socket.DebugSocketListener",
"com.zjh.tears.listener.socket.TestSocketListener"
"com.zjh.tears.listener.socket.LogSocketListener"
],
"httpHandler": [
"com.zjh.tears.handler.DefaultIndexHTTPHandler",
Expand All @@ -36,7 +34,8 @@
},
"pageConfig": {
"defaultIndex": [
"index.html", "page.html"
"index.html",
"page.html"
],
"errorPages": [
{
Expand Down
Loading

0 comments on commit a67b6d2

Please sign in to comment.