diff options
Diffstat (limited to 'samples/src/main/java/fi/iki')
11 files changed, 1057 insertions, 0 deletions
diff --git a/samples/src/main/java/fi/iki/elonen/router/App.java b/samples/src/main/java/fi/iki/elonen/router/App.java new file mode 100644 index 0000000..e43e025 --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/App.java @@ -0,0 +1,86 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +/** + * Created by vnnv on 7/17/15. + * Simple httpd server based on NanoHTTPD + * Read the source. Everything is there. + */ + +import fi.iki.elonen.ServerRunner; + +import java.io.IOException; + +public class App extends RouterNanoHTTPD { + + private static final int PORT = 8081; + + /** + Create the server instance + */ + public App() throws IOException { + super(PORT); + addMappings(); + System.out.println("\nRunning! Point your browers to http://localhost:" + PORT + "/ \n"); + } + + /** + * Add the routes + * Every route is an absolute path + * Parameters starts with ":" + * Handler class should implement @UriResponder interface + * If the handler not implement UriResponder interface - toString() is used + */ + @Override + public void addMappings() { + super.addMappings(); + addRoute("/user", UserHandler.class); + addRoute("/user/:id", UserHandler.class); + addRoute("/user/help", GeneralHandler.class); + addRoute("/photos/:customer_id/:photo_id", null); + addRoute("/test", String.class); + } + + /** + * Main entry point + * @param args + */ + public static void main(String[] args) { + try { + ServerRunner.run(App.class); + } catch (Exception ioe) { + System.err.println("Couldn't start server:\n" + ioe); + } + } +}
\ No newline at end of file diff --git a/samples/src/main/java/fi/iki/elonen/router/DefaultHandler.java b/samples/src/main/java/fi/iki/elonen/router/DefaultHandler.java new file mode 100644 index 0000000..57e7b47 --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/DefaultHandler.java @@ -0,0 +1,78 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import fi.iki.elonen.NanoHTTPD; + +import java.io.ByteArrayInputStream; +import java.util.Map; + +/** + * Created by vnnv on 7/21/15. + * + */ +public abstract class DefaultHandler implements UriResponder { + + public abstract String getText(); + public abstract String getMimeType(); + public abstract NanoHTTPD.Response.IStatus getStatus(); + + public RouterResponse get(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + String text = getText(); + ByteArrayInputStream inp = new ByteArrayInputStream(text.getBytes()); + + RouterResponse result = new RouterResponse(); + result.setData(inp); + result.setMimeType(getMimeType()); + result.setSize(text.getBytes().length); + result.setStatus(getStatus()); + + return result; + } + + public RouterResponse post(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } + + public RouterResponse put(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } + + public RouterResponse delete(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } + public RouterResponse other(String method, UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } + +} diff --git a/samples/src/main/java/fi/iki/elonen/router/GeneralHandler.java b/samples/src/main/java/fi/iki/elonen/router/GeneralHandler.java new file mode 100644 index 0000000..4e7f56a --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/GeneralHandler.java @@ -0,0 +1,82 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import fi.iki.elonen.NanoHTTPD; + +import java.io.ByteArrayInputStream; +import java.util.Map; + +/** + * Created by vnnv on 7/22/15. + */ +public class GeneralHandler extends DefaultHandler { + + @Override + public String getText() { + return null; + } + + @Override + public String getMimeType() { + return "text/html"; + } + + @Override + public NanoHTTPD.Response.IStatus getStatus() { + return NanoHTTPD.Response.Status.OK; + } + + public RouterResponse get(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + String text = "<html><body>"; + text += "<h1>Url: " + session.getUri() + "</h1><br>"; + Map<String, String> queryParams = session.getParms(); + if (queryParams.size() > 0) { + for (Map.Entry<String, String> entry : queryParams.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + text += "<p>Param '" + key + "' = " + value + "</p>"; + } + }else{ + text +="<p>no params in url</p><br>"; + } + + RouterResponse res = new RouterResponse(); + res.setData(new ByteArrayInputStream(text.getBytes())); + res.setSize(text.getBytes().length); + res.setStatus(getStatus()); + res.setMimeType(getMimeType()); + return res; + } + +} diff --git a/samples/src/main/java/fi/iki/elonen/router/RouterNanoHTTPD.java b/samples/src/main/java/fi/iki/elonen/router/RouterNanoHTTPD.java new file mode 100644 index 0000000..5da177c --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/RouterNanoHTTPD.java @@ -0,0 +1,145 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import fi.iki.elonen.NanoHTTPD; + +import java.util.Map; + +/** + * Created by vnnv on 7/21/15. + */ +public class RouterNanoHTTPD extends NanoHTTPD { + + /** + * Handling error 404 - unrecognized urls + */ + public static class Error404UriHandler extends DefaultHandler { + + public String getText() { + String res = "<html><body><h3>Error 404: " + + "the requested page doesn't exist.</h3></body></html>"; + return res; + } + + @Override + public String getMimeType() { + return "text/html"; + } + + @Override + public Response.IStatus getStatus() { + return Response.Status.NOT_FOUND; + } + + } + + /** + * Handling index + */ + public static class IndexHandler extends DefaultHandler { + + public String getText() { + String res = "<html><body><h2>Hello world!</h3></body></html>"; + return res; + } + + @Override + public String getMimeType() { + return "text/html"; + } + + @Override + public Response.IStatus getStatus() { + return Response.Status.OK; + } + + } + + public static class NotImplementedHandler extends DefaultHandler { + + public String getText() { + String res = "<html><body><h2>The uri is mapped in the router, " + + "but no handler is specified. <br> " + + "Status: Not implemented!</h3></body></html>"; + return res; + } + + @Override + public String getMimeType() { + return "text/html"; + } + + @Override + public Response.IStatus getStatus() { + return Response.Status.OK; + } + + } + + + private UriRouter router; + + public RouterNanoHTTPD(int port) { + super(port); + router = new UriRouter(); + } + + public void addMappings() { + router.setNotImplemented(NotImplementedHandler.class); + router.setNotFoundHandler(Error404UriHandler.class); +// router.setNotFoundHandler(GeneralHandler.class); // You can use this instead of Error404UriHandler + router.addRoute("/", IndexHandler.class); + router.addRoute("/index.html", IndexHandler.class); + } + + public void addRoute(String url, Class<?> handler) { + router.addRoute(url, handler); + } + + public void removeRoute(String url) { + router.removeRoute(url); + } + + @Override + public Response serve(IHTTPSession session) { + // Try to find match + UriResource uriResource = router.matchUrl(session.getUri()); + // Extract uri parameters + Map<String, String> urlParams = router.getUrlParams(uriResource, session.getUri()); + // Process the uri + RouterResponse result = uriResource.process(urlParams, session); + // Return the response + return newFixedLengthResponse(result.getStatus(), result.getMimeType(), result.getData(), result.getSize()); + } +} diff --git a/samples/src/main/java/fi/iki/elonen/router/RouterResponse.java b/samples/src/main/java/fi/iki/elonen/router/RouterResponse.java new file mode 100644 index 0000000..ed16524 --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/RouterResponse.java @@ -0,0 +1,80 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import fi.iki.elonen.NanoHTTPD; + +import java.io.InputStream; + +/** + * Created by vnnv on 7/21/15. + * Transport class because NanoHTTPD.Response has protected constructor + */ +public class RouterResponse { + private NanoHTTPD.Response.IStatus status; + private InputStream data; + private long size; + private String mimeType; + + public NanoHTTPD.Response.IStatus getStatus() { + return status; + } + + public void setStatus(NanoHTTPD.Response.IStatus status) { + this.status = status; + } + + public InputStream getData() { + return data; + } + + public void setData(InputStream data) { + this.data = data; + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public String getMimeType() { + return mimeType; + } + + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } +} diff --git a/samples/src/main/java/fi/iki/elonen/router/StringUtils.java b/samples/src/main/java/fi/iki/elonen/router/StringUtils.java new file mode 100644 index 0000000..bacaceb --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/StringUtils.java @@ -0,0 +1,54 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +/** + * Created by victor on 7/20/15. + * Util methods + */ +public class StringUtils { + public static String normalizeUri(String value) { + if (value == null) { + return value; + } + if (value.startsWith("/")) { + value = value.substring(1); + } + if (value.endsWith("/")) { + value = value.substring(0, value.length() - 1); + } + return value; + + } + +} diff --git a/samples/src/main/java/fi/iki/elonen/router/UriPart.java b/samples/src/main/java/fi/iki/elonen/router/UriPart.java new file mode 100644 index 0000000..19225b3 --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/UriPart.java @@ -0,0 +1,63 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +/** + * Created by vnnv on 7/20/15. + */ +public class UriPart { + private String name; + private boolean isParam; + + public UriPart(String name, boolean isParam) { + this.name = name; + this.isParam = isParam; + } + + @Override + public String toString() { + return "UriPart{" + + "name='" + name + '\'' + + ", isParam=" + isParam + + '}'; + } + + public boolean isParam() { + return isParam; + } + + public String getName() { + return name; + } + +} diff --git a/samples/src/main/java/fi/iki/elonen/router/UriResource.java b/samples/src/main/java/fi/iki/elonen/router/UriResource.java new file mode 100644 index 0000000..0ec45fe --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/UriResource.java @@ -0,0 +1,149 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import fi.iki.elonen.NanoHTTPD; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Created by vnnv on 7/20/15. + * Represent single uri + */ +public class UriResource { + private boolean hasParameters; + private int uriParamsCount; + private String uri; + private List<UriPart> uriParts; + private Class handler; + + public UriResource(String uri, Class<?> handler) { + this.hasParameters = false; + this.handler = handler; + uriParamsCount = 0; + if (uri != null) { + this.uri = StringUtils.normalizeUri(uri); + parse(); + } + } + + private void parse(){ + String[] parts = uri.split("/"); + uriParts = new ArrayList<UriPart>(); + for (String part : parts) { + boolean isParam = part.startsWith(":"); + UriPart uriPart = null; + if (isParam) { + hasParameters = true; + uriParamsCount++; + uriPart = new UriPart(part.substring(1), true); + }else{ + uriPart = new UriPart(part, false); + } + uriParts.add(uriPart); + } + + } + + public RouterResponse process(Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + String error = "General error!"; + if (handler != null) { + try { + Object object = handler.newInstance(); + if (object instanceof UriResponder) { + UriResponder responder = (UriResponder) object; + switch (session.getMethod()) { + case GET: return responder.get(this, urlParams, session); + case POST: return responder.post(this, urlParams, session); + case PUT: return responder.put(this, urlParams, session); + case DELETE: return responder.delete(this, urlParams, session); + default: return responder.other(session.getMethod().toString(), this, urlParams, session); + } + }else { + // return toString() + String text = "Return: " + handler.getCanonicalName() + ".toString() -> " + object.toString(); + RouterResponse res = new RouterResponse(); + res.setStatus(NanoHTTPD.Response.Status.OK); + res.setMimeType("text/plain"); + res.setData(new ByteArrayInputStream(text.getBytes())); + res.setSize(text.getBytes().length); + return res; + } + } catch (InstantiationException e) { + error = "Error: " + InstantiationException.class.getName() + " : " + e.getMessage(); + e.printStackTrace(); + } catch (IllegalAccessException e) { + error = "Error: " + IllegalAccessException.class.getName() + " : " + e.getMessage(); + e.printStackTrace(); + } + } + + RouterResponse res = new RouterResponse(); + res.setStatus(NanoHTTPD.Response.Status.INTERNAL_ERROR); + res.setMimeType("text/plain"); + res.setData(new ByteArrayInputStream(error.getBytes())); + res.setSize(error.getBytes().length); + return res; + } + + + @Override + public String toString() { + return "UrlResource{" + + "hasParameters=" + hasParameters + + ", uriParamsCount=" + uriParamsCount + + ", uri='" + (uri != null ? "/" : "") + uri + '\'' + + ", urlParts=" + uriParts + + '}'; + } + + public boolean hasParameters() { + return hasParameters; + } + + public String getUri() { + return uri; + } + + public List<UriPart> getUriParts() { + return uriParts; + } + + public int getUriParamsCount() { + return uriParamsCount; + } + +} diff --git a/samples/src/main/java/fi/iki/elonen/router/UriResponder.java b/samples/src/main/java/fi/iki/elonen/router/UriResponder.java new file mode 100644 index 0000000..1015250 --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/UriResponder.java @@ -0,0 +1,50 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import fi.iki.elonen.NanoHTTPD; + +import java.util.Map; + +/** + * Created by vnnv on 7/20/15. + */ +public interface UriResponder { + + public RouterResponse get(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session); + public RouterResponse put(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session); + public RouterResponse post(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session); + public RouterResponse delete(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session); + public RouterResponse other(String method, UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session); + +} diff --git a/samples/src/main/java/fi/iki/elonen/router/UriRouter.java b/samples/src/main/java/fi/iki/elonen/router/UriRouter.java new file mode 100644 index 0000000..c28cecf --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/UriRouter.java @@ -0,0 +1,182 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by vnnv on 7/17/15. + */ +public class UriRouter { + + private List<UriResource> mappings; + private UriResource error404Url; + private Class<?> notImplemented; + + public UriRouter() { + mappings = new ArrayList<UriResource>(); + } + + /** + * Search in the mappings if the given url matches some of the rules + * If there are more than one marches returns the rule with less parameters + * e.g. + * mapping 1 = /user/:id + * mapping 2 = /user/help + * + * if the incoming uri is www.example.com/user/help - mapping 2 is returned + * if the incoming uri is www.example.com/user/3232 - mapping 1 is returned + * + * @param url + * @return + */ + public UriResource matchUrl(String url) { + + String work = StringUtils.normalizeUri(url); + + String[] parts = work.split("/"); + List<UriResource> resultList = new ArrayList<UriResource>(); + + for (UriResource u : mappings) { + + // Check if count of parts is the same + if (parts.length != u.getUriParts().size()) { + continue; // different + } + + List<UriPart> uriParts = u.getUriParts(); + + boolean match = true; + for (int i = 0; i < parts.length; i++) { + String currentPart = parts[i]; + UriPart uriPart = uriParts.get(i); + boolean goOn = false; + + if (currentPart.equals(uriPart.getName())) { + // exact match + goOn = true; + }else { + // not match + if (uriPart.isParam()){ + goOn = true; + }else{ + match = false; + goOn = false; + } + } + if (!goOn) { + match = false; + break; + } + } // for - iterate incoming url parts + if (match) { + resultList.add(u); // current match + } + } // end iterate over all rules + if (resultList.size() > 0) { + // some results + UriResource result = null; + if (resultList.size() > 1) { + //return the rule with less parameters + int params = 1024; + for (UriResource u : resultList) { + if (!u.hasParameters()) { + result = u; + break; + }else{ + if (u.getUriParamsCount() <= params) { + result = u; + } + } + } + return result; + }else{ + return resultList.get(0); + } + } + return error404Url; + } + + public void addRoute(String url, Class<?> handler) { + if (url != null) { + if (handler != null) { + mappings.add(new UriResource(url, handler)); + }else{ + mappings.add(new UriResource(url, notImplemented)); + } + } + + } + + public void removeRoute(String url) { + if (mappings.contains(url)) { + mappings.remove(url); + } + } + + public void setNotFoundHandler(Class<?> handler) { + error404Url = new UriResource(null, handler); + } + + public void setNotImplemented(Class<?> handler) { + notImplemented = handler; + } + + /** + * Extract parameters and their values for the given route + * @param route + * @param uri + * @return + */ + public Map<String, String> getUrlParams(UriResource route, String uri) { + Map<String, String> result = new HashMap<String, String>(); + if (route.getUri() == null) { + return result; + } + + String workUri = StringUtils.normalizeUri(uri); + String[] parts = workUri.split("/"); + + + for (int i = 0; i < parts.length; i++ ) { + UriPart currentPart = route.getUriParts().get(i); + if (currentPart.isParam()) { + result.put(currentPart.getName(), parts[i]); + } + } + return result; + } +} diff --git a/samples/src/main/java/fi/iki/elonen/router/UserHandler.java b/samples/src/main/java/fi/iki/elonen/router/UserHandler.java new file mode 100644 index 0000000..8999793 --- /dev/null +++ b/samples/src/main/java/fi/iki/elonen/router/UserHandler.java @@ -0,0 +1,88 @@ +package fi.iki.elonen.router; +/* + * #%L + * NanoHttpd-Samples + * %% + * Copyright (C) 2012 - 2015 nanohttpd + * %% + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the nanohttpd nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +import fi.iki.elonen.NanoHTTPD; + +import java.io.ByteArrayInputStream; +import java.util.Map; + + + +/** + * Created by vnnv on 7/21/15. + */ +public class UserHandler implements UriResponder { + public RouterResponse get(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + String text = "<html><body>User handler. Method: " + session.getMethod().toString() + "<br>"; + text += "<h1>Uri parameters:</h1>"; + for (Map.Entry<String, String> entry : urlParams.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + text += "<div> Param: " + key + " Value: " + value + "</div>"; + } + text += "<h1>Query parameters:</h1>"; + for (Map.Entry<String, String> entry : session.getParms().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + text += "<div> Query Param: " + key + " Value: " + value + "</div>"; + } + text += "</body></html>"; + + ByteArrayInputStream inp = new ByteArrayInputStream(text.getBytes()); + + RouterResponse result = new RouterResponse(); + result.setData(inp); + result.setMimeType("text/html"); + result.setSize(text.getBytes().length); + result.setStatus(NanoHTTPD.Response.Status.OK); + + return result; + } + + public RouterResponse post(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } + + public RouterResponse put(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } + + public RouterResponse delete(UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } + + public RouterResponse other(String method, UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { + return get(uriResource, urlParams, session); + } +} |