Skip to content

Commit

Permalink
#103 Don't try to render HTML pages if the setup is REST-only.
Browse files Browse the repository at this point in the history
  • Loading branch information
nmihajlovski committed Feb 19, 2017
1 parent 0f22bd5 commit 1e0b811
Show file tree
Hide file tree
Showing 9 changed files with 126 additions and 12 deletions.
8 changes: 8 additions & 0 deletions rapidoid-commons/src/main/java/org/rapidoid/util/Msc.java
Expand Up @@ -809,6 +809,10 @@ public static boolean hasRapidoidGUI() {
return Cls.exists("org.rapidoid.gui.GUI"); return Cls.exists("org.rapidoid.gui.GUI");
} }


public static boolean hasRapidoidHTML() {
return Cls.exists("org.rapidoid.html.HTML");
}

public static boolean hasRapidoidWatch() { public static boolean hasRapidoidWatch() {
return Cls.exists("org.rapidoid.reload.Reload"); return Cls.exists("org.rapidoid.reload.Reload");
} }
Expand All @@ -829,6 +833,10 @@ public static boolean hasMavenEmbedder() {
return Cls.exists("org.apache.maven.cli.MavenCli"); return Cls.exists("org.apache.maven.cli.MavenCli");
} }


public static boolean isRestOnly() {
return !hasRapidoidHTML();
}

public static boolean isValidationError(Throwable error) { public static boolean isValidationError(Throwable error) {
return (error instanceof InvalidData) || error.getClass().getName().startsWith("javax.validation."); return (error instanceof InvalidData) || error.getClass().getName().startsWith("javax.validation.");
} }
Expand Down
Expand Up @@ -246,7 +246,7 @@ public ReqImpl createReq(Channel channel, boolean isGet, boolean isKeepAlive,
String query = Msc.urlDecodeOrKeepOriginal(helper.query.str(buf)); String query = Msc.urlDecodeOrKeepOriginal(helper.query.str(buf));
String zone = null; String zone = null;


MediaType contentType = MediaType.HTML_UTF_8; MediaType contentType = HttpUtils.getDefaultContentType();


if (handler != null) { if (handler != null) {
contentType = handler.contentType(); contentType = handler.contentType();
Expand Down Expand Up @@ -279,7 +279,7 @@ private HttpStatus handleIfFound(Channel channel, boolean isKeepAlive, HttpHandl
} }


private void internalServerError(final Channel channel, final boolean isKeepAlive, final Req req) { private void internalServerError(final Channel channel, final boolean isKeepAlive, final Req req) {
MediaType contentType = req != null ? req.contentType() : MediaType.HTML_UTF_8; MediaType contentType = req != null ? req.contentType() : HttpUtils.getDefaultContentType();


JsonResponseRenderer jsonRenderer = Customization.of(req).jsonResponseRenderer(); JsonResponseRenderer jsonRenderer = Customization.of(req).jsonResponseRenderer();
byte[] body = HttpUtils.responseToBytes(req, INTERNAL_SERVER_ERROR, contentType, jsonRenderer); byte[] body = HttpUtils.responseToBytes(req, INTERNAL_SERVER_ERROR, contentType, jsonRenderer);
Expand Down
Expand Up @@ -385,4 +385,8 @@ public static void proxyResponseHeaders(Map<String, String> respHeaders, SimpleH
} }
} }


public static MediaType getDefaultContentType() {
return Msc.hasRapidoidHTML() ? MediaType.HTML_UTF_8 : MediaType.JSON;
}

} }
Expand Up @@ -452,7 +452,7 @@ public void doRendering(int code, byte[] responseBody) {
} }


private void respond(int code, byte[] responseBody) { private void respond(int code, byte[] responseBody) {
MediaType contentType = MediaType.HTML_UTF_8; MediaType contentType = HttpUtils.getDefaultContentType();


if (tokenChanged.get()) { if (tokenChanged.get()) {
HttpUtils.saveTokenBeforeRenderingHeaders(this, token); HttpUtils.saveTokenBeforeRenderingHeaders(this, token);
Expand All @@ -463,7 +463,7 @@ private void respond(int code, byte[] responseBody) {
} }


if (response != null) { if (response != null) {
contentType = U.or(response.contentType(), MediaType.HTML_UTF_8); contentType = U.or(response.contentType(), contentType);
} }


renderResponse(code, contentType, responseBody); renderResponse(code, contentType, responseBody);
Expand Down Expand Up @@ -921,7 +921,7 @@ private void saveToCache() {
proxyResp.code = response != null ? response.code() : 200; proxyResp.code = response != null ? response.code() : 200;


if (proxyResp.contentType == null) { if (proxyResp.contentType == null) {
proxyResp.contentType = response != null ? response.contentType() : U.or(defaultContentType, MediaType.HTML_UTF_8); proxyResp.contentType = response != null ? response.contentType() : defaultContentType;
} }


// don't cache the response if it contains cookies or token data // don't cache the response if it contains cookies or token data
Expand Down
Expand Up @@ -65,7 +65,7 @@ public class RespImpl extends RapidoidThing implements Resp {


private volatile int code = 200; private volatile int code = 200;


private volatile MediaType contentType = MediaType.HTML_UTF_8; private volatile MediaType contentType = HttpUtils.getDefaultContentType();


private final Map<String, String> headers = Coll.synchronizedMap(); private final Map<String, String> headers = Coll.synchronizedMap();


Expand Down Expand Up @@ -326,7 +326,11 @@ public boolean hasCustomView() {
@Override @Override
public synchronized Resp view(String view) { public synchronized Resp view(String view) {
this.view = view; this.view = view;
this.mvc(true);
if (view != null) {
this.mvc(true);
}

return this; return this;
} }


Expand All @@ -337,6 +341,11 @@ public synchronized boolean mvc() {


@Override @Override
public synchronized Resp mvc(boolean mvc) { public synchronized Resp mvc(boolean mvc) {

if (mvc) {
U.must(Msc.hasRapidoidHTML(), "The rapidoid-html module must be included for the MVC feature!");
}

this.mvc = mvc; this.mvc = mvc;
return this; return this;
} }
Expand Down Expand Up @@ -475,7 +484,7 @@ public String toString() {


public byte[] renderToBytes() { public byte[] renderToBytes() {
if (mvc()) { if (mvc()) {
byte[] bytes = ResponseRenderer.render(req, this); byte[] bytes = ResponseRenderer.renderMvc(req, this);
HttpUtils.postProcessResponse(this); // the response might have been changed, so post-process again HttpUtils.postProcessResponse(this); // the response might have been changed, so post-process again
return bytes; return bytes;


Expand Down
Expand Up @@ -45,7 +45,7 @@
@Since("5.1.0") @Since("5.1.0")
public class ResponseRenderer extends RapidoidThing { public class ResponseRenderer extends RapidoidThing {


public static byte[] render(ReqImpl req, Resp resp) { public static byte[] renderMvc(ReqImpl req, Resp resp) {


Object result = resp.result(); Object result = resp.result();


Expand All @@ -54,8 +54,8 @@ public static byte[] render(ReqImpl req, Resp resp) {
if (shouldRenderView(resp)) { if (shouldRenderView(resp)) {
content = renderView(req, resp, result); content = renderView(req, resp, result);
} else { } else {
Object cnt = U.or(result, ""); Object respResult = U.or(result, "");
content = new String(HttpUtils.responseToBytes(req, cnt, MediaType.HTML_UTF_8, null)); content = new String(HttpUtils.responseToBytes(req, respResult, MediaType.HTML_UTF_8, null));
} }


return renderPage(req, content); return renderPage(req, content);
Expand Down
Expand Up @@ -5,6 +5,7 @@
import org.rapidoid.annotation.Since; import org.rapidoid.annotation.Since;
import org.rapidoid.annotation.TransactionMode; import org.rapidoid.annotation.TransactionMode;
import org.rapidoid.collection.Coll; import org.rapidoid.collection.Coll;
import org.rapidoid.http.HttpUtils;
import org.rapidoid.http.HttpWrapper; import org.rapidoid.http.HttpWrapper;
import org.rapidoid.http.MediaType; import org.rapidoid.http.MediaType;
import org.rapidoid.http.RouteConfig; import org.rapidoid.http.RouteConfig;
Expand Down Expand Up @@ -37,7 +38,7 @@
@Since("5.1.0") @Since("5.1.0")
public class RouteOptions extends RapidoidThing implements RouteConfig { public class RouteOptions extends RapidoidThing implements RouteConfig {


private volatile MediaType contentType = MediaType.HTML_UTF_8; private volatile MediaType contentType = HttpUtils.getDefaultContentType();


private volatile String view; private volatile String view;


Expand Down
90 changes: 90 additions & 0 deletions rapidoid-http-server/src/test/java/HttpRestAPITest.java
@@ -0,0 +1,90 @@
/*
* #%L
* rapidoid-http-server
* %%
* Copyright (C) 2014 - 2017 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/

import org.junit.Test;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.data.JSON;
import org.rapidoid.http.HttpResp;
import org.rapidoid.http.Req;
import org.rapidoid.http.ReqHandler;
import org.rapidoid.http.Self;
import org.rapidoid.setup.On;
import org.rapidoid.test.ExpectErrors;
import org.rapidoid.test.TestCommons;
import org.rapidoid.u.U;
import org.rapidoid.util.Msc;

@Authors("Nikolche Mihajlovski")
@Since("5.2.9")
public class HttpRestAPITest extends TestCommons {

private void initAPI() {
On.get("/inc/{x}").json(new ReqHandler() {
@Override
public Object execute(Req req) {
return U.num(req.param("x")) + 1;
}
});
}

@Test
public void testIncludedModules() {
isFalse(Msc.hasRapidoidHTML());
isFalse(Msc.hasRapidoidGUI());
}

@Test
public void testRestAPI() {
initAPI();

Self.get("/inc/99").expect("100");
}

@Test
public void testNotFound() {
initAPI();

HttpResp resp = Self.get("/foo/baz").execute();

eq(resp.code(), 404);
eq(resp.body(), JSON.stringify(U.map(
"error", "The requested resource could not be found!",
"code", 404,
"status", "Not Found"
)));
}

@Test
@ExpectErrors
public void testRuntimeError() {
initAPI();

HttpResp resp = Self.get("/inc/d9g").execute();

eq(resp.code(), 500);
eq(resp.body(), JSON.stringify(U.map(
"error", "For input string: \"d9g\"",
"code", 500,
"status", "Internal Server Error"
)));
}

}
Expand Up @@ -69,6 +69,8 @@ public final void initTest() {
System.out.println("--------------------------------------------------------------------------------"); System.out.println("--------------------------------------------------------------------------------");


hasError = false; hasError = false;
callIfExists("org.rapidoid.log.LogStats", "reset");
callIfExists("org.rapidoid.util.Msc", "reset");


String s = File.separator; String s = File.separator;
String resultsDir = "src" + s + "test" + s + "resources" + s + TEST_RESULTS_FOLDER + s + getTestName(); String resultsDir = "src" + s + "test" + s + "resources" + s + TEST_RESULTS_FOLDER + s + getTestName();
Expand Down

0 comments on commit 1e0b811

Please sign in to comment.