Skip to content

Commit

Permalink
Merge pull request #283 from lets-blade/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
hellokaton committed Oct 17, 2018
2 parents 34e3c5b + 27fb00a commit 0b8d360
Show file tree
Hide file tree
Showing 13 changed files with 150 additions and 124 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Expand Up @@ -5,7 +5,7 @@

<groupId>com.bladejava</groupId>
<artifactId>blade-mvc</artifactId>
<version>2.0.11.BETA</version>
<version>2.0.12-SNAPSHOT</version>
<packaging>jar</packaging>

<name>blade</name>
Expand Down
32 changes: 14 additions & 18 deletions src/main/java/com/blade/Blade.java
Expand Up @@ -22,6 +22,7 @@
import com.blade.ioc.SimpleIoc;
import com.blade.kit.Assert;
import com.blade.kit.BladeKit;
import com.blade.kit.JsonKit;
import com.blade.kit.StringKit;
import com.blade.kit.reload.FileChangeDetector;
import com.blade.loader.BladeLoader;
Expand Down Expand Up @@ -809,15 +810,6 @@ public Blade disableSession() {
return this;
}

public Blade disableCost() {
this.environment.set(ENV_KEY_HTTP_REQUEST_COST, false);
return this;
}

public boolean allowCost() {
return this.environment.getBoolean(ENV_KEY_HTTP_REQUEST_COST, true);
}

public Blade watchEnvChange(boolean watchEnvChange) {
this.environment.set(ENV_KEY_APP_WATCH_ENV, watchEnvChange);
return this;
Expand Down Expand Up @@ -1040,6 +1032,7 @@ public WebSocketHandler webSocketHandler() {
private void loadConfig(String[] args) {
String bootConf = environment().get(ENV_KEY_BOOT_CONF, PROP_NAME);
Environment bootEnv = Environment.of(bootConf);
String envName = "default";

if (null == bootEnv || bootEnv.isEmpty()) {
bootEnv = Environment.of(PROP_NAME0);
Expand All @@ -1051,9 +1044,8 @@ private void loadConfig(String[] args) {
entrySet.forEach(entry -> environment.set(entry.getKey(), entry.getValue()));
}

String envName = "default";

Map<String, String> argsMap = BladeKit.parseArgs(args);
log.info("command line args: {}", JsonKit.toString(argsMap));

if (StringKit.isNotEmpty(argsMap.get(ENV_KEY_APP_ENV))) {
envName = argsMap.get(ENV_KEY_APP_ENV);
Expand All @@ -1065,10 +1057,16 @@ private void loadConfig(String[] args) {
// compatible with older versions
evnFileName = "app-" + envName + ".properties";
customEnv = Environment.of(evnFileName);

if (customEnv != null && !customEnv.isEmpty()) {
customEnv.props().forEach((key, value) -> this.environment.set(key.toString(), value));
Iterator<Map.Entry<Object, Object>> iterator = customEnv.props().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Object, Object> next = iterator.next();
this.environment.set(next.getKey().toString(), next.getValue());
}
}
}
argsMap.remove(ENV_KEY_APP_ENV);
}

log.info("current environment is: {}", envName);
Expand All @@ -1080,12 +1078,10 @@ private void loadConfig(String[] args) {
return;
}

if (StringKit.isNotEmpty(argsMap.get(ENV_KEY_SERVER_ADDRESS))) {
this.environment.set(ENV_KEY_SERVER_ADDRESS, argsMap.get(ENV_KEY_SERVER_ADDRESS));
}

if (StringKit.isNotEmpty(argsMap.get(ENV_KEY_SERVER_PORT))) {
this.environment.set(ENV_KEY_SERVER_PORT, argsMap.get(ENV_KEY_SERVER_PORT));
Iterator<Map.Entry<String, String>> iterator = argsMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
this.environment.set(next.getKey(), next.getValue());
}

}
Expand Down
11 changes: 10 additions & 1 deletion src/main/java/com/blade/kit/BladeKit.java
Expand Up @@ -254,7 +254,16 @@ public static void log304(Logger log, String method, String uri) {
log.warn("{} {} {} {}", msg304, pad, method, uri);
}

public static long log200(Logger log, Instant start, String method, String uri) {
public static void log200(Logger log, String method, String uri) {
if (!log.isInfoEnabled()) {
return;
}
String pad = StringKit.padLeft("", 6);
String msg200 = Ansi.BgGreen.and(Ansi.Black).format(" 200 ");
log.info("{} {} {} {}", msg200, pad, method, uri);
}

public static long log200AndCost(Logger log, Instant start, String method, String uri) {
long cost = getCostMS(start);
if (!log.isInfoEnabled()) {
return cost;
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/blade/mvc/Const.java
Expand Up @@ -31,7 +31,7 @@ public interface Const {
int DEFAULT_SERVER_PORT = 9000;
String DEFAULT_SERVER_ADDRESS = "0.0.0.0";
String LOCAL_IP_ADDRESS = "127.0.0.1";
String VERSION = "2.0.11.BETA";
String VERSION = "2.0.11.RELEASE";
String WEB_JARS = "/webjars/";
String CLASSPATH = BladeKit.getCurrentClassPath();
String CONTENT_TYPE_HTML = "text/html; charset=UTF-8";
Expand Down Expand Up @@ -69,6 +69,7 @@ public interface Const {
String ENV_KEY_TEMPLATE_PATH = "mvc.template.path";
String ENV_KEY_SERVER_ADDRESS = "server.address";
String ENV_KEY_SERVER_PORT = "server.port";
String ENV_KEY_PERFORMANCE = "server.performance";
String ENV_KEY_SSL = "server.ssl.enable";
String ENV_KEY_SSL_CERT = "server.ssl.cert-path";
String ENE_KEY_SSL_PRIVATE_KEY = "server.ssl.private-key-path";
Expand Down
10 changes: 1 addition & 9 deletions src/main/java/com/blade/mvc/WebContext.java
Expand Up @@ -163,7 +163,7 @@ public static void clean() {
}

public Environment environment() {
return blade().environment();
return blade.environment();
}

/**
Expand Down Expand Up @@ -191,18 +191,10 @@ public ChannelHandlerContext getChannelHandlerContext() {
return channelHandlerContext;
}

public LocalContext getLocalContext() {
return localContext;
}

public Route getRoute() {
return route;
}

public void setLocalContext(LocalContext localContext) {
this.localContext = localContext;
}

public void setRoute(Route route) {
this.route = route;
}
Expand Down
89 changes: 49 additions & 40 deletions src/main/java/com/blade/mvc/http/HttpRequest.java
Expand Up @@ -56,7 +56,8 @@
@NoArgsConstructor
public class HttpRequest implements Request {

private static final HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed
private static final HttpDataFactory factory =
new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed

private static final ByteBuf EMPTY_BUF = Unpooled.copiedBuffer("", CharsetUtil.UTF_8);

Expand All @@ -73,13 +74,15 @@ public class HttpRequest implements Request {
private String url;
private String protocol;
private String method;
private String cookieString;
private boolean keepAlive;
private Session session;

private boolean isRequestPart;
private boolean isChunked;
private boolean isMultipart;
private boolean isEnd;
private boolean initCookie;

private Map<String, String> headers = null;
private Map<String, Object> attributes = null;
Expand Down Expand Up @@ -147,10 +150,10 @@ public Map<String, String> pathParams() {

@Override
public String queryString() {
if (null != this.url && this.url.contains("?")) {
return this.url.substring(this.url.indexOf("?") + 1);
if (null == url || !url.contains("?")) {
return "";
}
return "";
return url.substring(url.indexOf("?") + 1);
}

@Override
Expand Down Expand Up @@ -180,10 +183,14 @@ public HttpMethod httpMethod() {

@Override
public boolean useGZIP() {
boolean useGZIP = WebContext.blade().environment().getBoolean(Const.ENV_KEY_GZIP_ENABLE, false);

boolean useGZIP = WebContext.blade().environment()
.getBoolean(Const.ENV_KEY_GZIP_ENABLE, false);

if (!useGZIP) {
return false;
}

String acceptEncoding = this.header(HttpConst.ACCEPT_ENCODING);
if (StringKit.isEmpty(acceptEncoding)) {
return false;
Expand All @@ -209,6 +216,10 @@ public boolean isIE() {

@Override
public Map<String, Cookie> cookies() {
if (!initCookie && StringKit.isNotEmpty(cookieString)) {
initCookie = true;
ServerCookieDecoder.LAX.decode(cookieString).forEach(this::parseCookie);
}
return this.cookies;
}

Expand Down Expand Up @@ -336,80 +347,76 @@ public static HttpRequest build(String remoteAddress, HttpObject msg) {
request.uri = cleanUri;
}

SessionManager sessionManager = WebContext.blade().sessionManager();
if (null != sessionManager) {
request.session = SESSION_HANDLER.createSession(request);
if (!HttpServerHandler.PERFORMANCE) {
SessionManager sessionManager = WebContext.blade().sessionManager();
if (null != sessionManager) {
request.session = SESSION_HANDLER.createSession(request);
}
}

HttpServerHandler.setLocalContext(new LocalContext(msg, request, decoder));
return request;
}

private static HttpPostRequestDecoder initRequest(HttpRequest request, io.netty.handler.codec.http.HttpRequest nettyRequest) {
private static HttpPostRequestDecoder initRequest(
HttpRequest request,
io.netty.handler.codec.http.HttpRequest nettyRequest) {

// headers
var httpHeaders = nettyRequest.headers();
if (httpHeaders.isEmpty()) {
request.headers = new HashMap<>();
} else {
request.headers = new HashMap<>(httpHeaders.size());

httpHeaders.forEach(entry -> request.headers.put(entry.getKey(), entry.getValue()));

// Iterator<Map.Entry<String, String>> entryIterator = httpHeaders.iteratorAsString();
// while (entryIterator.hasNext()) {
// var entry = entryIterator.next();
// request.headers.put(entry.getKey(), entry.getValue());
// }
Iterator<Map.Entry<String, String>> entryIterator = httpHeaders.iteratorAsString();
while (entryIterator.hasNext()) {
Map.Entry<String, String> next = entryIterator.next();
request.headers.put(next.getKey(), next.getValue());
}
}

// request query parameters
var parameters = new QueryStringDecoder(request.url(), CharsetUtil.UTF_8).parameters();
if (null != parameters) {
request.parameters = new HashMap<>();
request.parameters.putAll(parameters);
if (request.url().contains("?")) {
var parameters = new QueryStringDecoder(request.url(), CharsetUtil.UTF_8)
.parameters();

if (null != parameters) {
request.parameters.putAll(parameters);
}
}

request.initCookie();
// cookies
request.cookieString = request.header(HttpConst.COOKIE_STRING);

if ("GET".equals(request.method())) {
return null;
}

try {
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(factory, nettyRequest);
HttpPostRequestDecoder decoder =
new HttpPostRequestDecoder(factory, nettyRequest);

request.isMultipart = decoder.isMultipart();
return decoder;
} catch (Exception e) {
throw new HttpParseException("build decoder fail", e);
}
}

private void initCookie() {
// cookies
var cookie = this.header(HttpConst.COOKIE_STRING);
cookie = cookie.length() > 0 ? cookie : this.header(HttpConst.COOKIE_STRING.toLowerCase());
if (null != cookie && cookie.length() > 0) {
ServerCookieDecoder.LAX.decode(cookie).forEach(this::parseCookie);
}
}

/**
* Example of reading request by chunk and getting values from chunk to chunk
* Reading request by chunk and getting values from chunk
*/
private boolean readHttpDataChunkByChunk(HttpPostRequestDecoder decoder) {
private void readHttpDataChunkByChunk(HttpPostRequestDecoder decoder) {
try {
boolean read = false;
while (decoder.hasNext()) {
read = true;
InterfaceHttpData data = decoder.next();
if (data != null) {
parseData(data);
}
}
return read;
} catch (HttpPostRequestDecoder.EndOfDataDecoderException e) {
// ignore
return true;
} catch (Exception e) {
throw new HttpParseException(e);
}
Expand Down Expand Up @@ -453,7 +460,6 @@ private void parseAttribute(Attribute attribute) throws IOException {
* Parse FileUpload to {@link FileItem}.
*
* @param fileUpload netty http file upload
* @throws IOException
*/
private void parseFileUpload(FileUpload fileUpload) throws IOException {
if (!fileUpload.isCompleted()) {
Expand All @@ -466,8 +472,11 @@ private void parseFileUpload(FileUpload fileUpload) throws IOException {
// Upload the file is moved to the specified temporary file,
// because FileUpload will be release after completion of the analysis.
// tmpFile will be deleted automatically if they are used.
Path tmpFile = Files.createTempFile(Paths.get(fileUpload.getFile().getParent()), "blade_", "_upload");
Files.move(Paths.get(fileUpload.getFile().getPath()), tmpFile, StandardCopyOption.REPLACE_EXISTING);
Path tmpFile = Files.createTempFile(
Paths.get(fileUpload.getFile().getParent()), "blade_", "_upload");

Path fileUploadPath = Paths.get(fileUpload.getFile().getPath());
Files.move(fileUploadPath, tmpFile, StandardCopyOption.REPLACE_EXISTING);

fileItem.setFile(tmpFile.toFile());
fileItem.setPath(tmpFile.toFile().getPath());
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/com/blade/server/netty/HttpConst.java
Expand Up @@ -17,7 +17,6 @@ public interface HttpConst {
String COOKIE_STRING = "Cookie";
String METHOD_GET = "GET";
String METHOD_POST = "POST";
String IE_UA = "MSIE";
String DEFAULT_SESSION_KEY = "SESSION";
String SLASH = "/";
char CHAR_SLASH = '/';
Expand All @@ -29,7 +28,6 @@ public interface HttpConst {
CharSequence CONTENT_ENCODING = AsciiString.cached("Content-Encoding");
CharSequence DATE = AsciiString.cached("Date");
CharSequence LOCATION = AsciiString.cached("Location");
CharSequence X_POWER_BY = AsciiString.cached("X-Powered-By");
CharSequence EXPIRES = AsciiString.cached("Expires");
CharSequence CACHE_CONTROL = AsciiString.cached("Cache-Control");
CharSequence LAST_MODIFIED = AsciiString.cached("Last-Modified");
Expand All @@ -39,6 +37,6 @@ public interface HttpConst {

String CONTENT_TYPE_HTML = "text/html; charset=UTF-8";

CharSequence VERSION = AsciiString.cached("blade-" + Const.VERSION);
String VERSION = "blade-" + Const.VERSION;

}

0 comments on commit 0b8d360

Please sign in to comment.