http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package-info.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package-info.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package-info.java deleted file mode 100755 index 5d597ca..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package-info.java +++ /dev/null @@ -1,35 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -// XML namespaces used in this package -@XmlSchema( - prefix="ab", - xmlNs={ - @XmlNs(prefix="ab", namespaceURI="http://www.apache.org/addressBook/"), - @XmlNs(prefix="per", namespaceURI="http://www.apache.org/person/"), - @XmlNs(prefix="addr", namespaceURI="http://www.apache.org/address/"), - @XmlNs(prefix="mail", namespaceURI="http://www.apache.org/mail/") - } -) -@RdfSchema( - prefix="ab", - rdfNs={ - @RdfNs(prefix="ab", namespaceURI="http://www.apache.org/addressBook/"), - @RdfNs(prefix="per", namespaceURI="http://www.apache.org/person/"), - @RdfNs(prefix="addr", namespaceURI="http://www.apache.org/address/"), - @RdfNs(prefix="mail", namespaceURI="http://www.apache.org/mail/") - } -) -package org.apache.juneau.examples.addressbook; -import org.apache.juneau.jena.annotation.*; -import org.apache.juneau.xml.annotation.*; -
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package.html ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package.html b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package.html deleted file mode 100755 index 21caee9..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/addressbook/package.html +++ /dev/null @@ -1,42 +0,0 @@ -<!-- -/*************************************************************************************************************************** - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file - * to you 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. - * - ***************************************************************************************************************************/ - --> -<html> -<head> - <style type="text/css"> - /* For viewing in Page Designer */ - @IMPORT url("../../../../../../org.apache.juneau/javadoc.css"); - - /* For viewing in REST interface */ - @IMPORT url("../htdocs/javadoc.css"); - body { - margin: 20px; - } - </style> - <script> - /* Replace all @code and @link tags. */ - window.onload = function() { - document.body.innerHTML = document.body.innerHTML.replace(/\{\@code ([^\}]+)\}/g, '<code>$1</code>'); - document.body.innerHTML = document.body.innerHTML.replace(/\{\@link (([^\}]+)\.)?([^\.\}]+)\}/g, '<code>$3</code>'); - } - </script> -</head> -<body> -<p>Javadocs for Address Book Resource Example</p> -<p> - Pretend there is documentation here. -</p> -</body> -</html> \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AdminGuard.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AdminGuard.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AdminGuard.java deleted file mode 100644 index f9b85c6..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AdminGuard.java +++ /dev/null @@ -1,26 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import org.apache.juneau.rest.*; - -/** - * Sample guard that only lets administrators through. - */ -public class AdminGuard extends RestGuard { - - @Override /* RestGuard */ - public boolean isRequestAllowed(RestRequest req) { - return true; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AtomFeedResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AtomFeedResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AtomFeedResource.java deleted file mode 100644 index 7d7eebe..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/AtomFeedResource.java +++ /dev/null @@ -1,116 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static org.apache.juneau.dto.atom.AtomBuilder.*; -import static org.apache.juneau.html.HtmlDocSerializerContext.*; -import static org.apache.juneau.jena.RdfCommonContext.*; -import static org.apache.juneau.jena.RdfSerializerContext.*; - -import java.net.*; - -import org.apache.juneau.dto.atom.*; -import org.apache.juneau.encoders.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.widget.*; - -/** - * Sample resource that shows how to generate ATOM feeds. - */ -@RestResource( - path="/atom", - title="Sample ATOM feed resource", - description="Sample resource that shows how to render ATOM feeds", - htmldoc=@HtmlDoc( - widgets={ - ContentTypeMenuItem.class, - StyleMenuItem.class - }, - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "$W{ContentTypeMenuItem}", - "$W{StyleMenuItem}", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - } - ), - properties={ - @Property(name=SERIALIZER_quoteChar, value="'"), - @Property(name=RDF_rdfxml_tab, value="5"), - @Property(name=RDF_addRootProperty, value="true") - }, - encoders=GzipEncoder.class -) -public class AtomFeedResource extends ResourceJena { - private static final long serialVersionUID = 1L; - - private Feed feed; // The root resource object - - @Override /* Servlet */ - public void init() { - - try { - feed = - feed("tag:juneau.sample.com,2013:1", "Juneau ATOM specification", "2013-05-08T12:29:29Z") - .subtitle(text("html").text("A <em>lot</em> of effort went into making this effortless")) - .links( - link("alternate", "text/html", "http://www.sample.com/").hreflang("en"), - link("self", "application/atom+xml", "http://www.sample.com/feed.atom") - ) - .generator( - generator("Juneau").uri("http://juneau.apache.org/").version("1.0") - ) - .entries( - entry("tag:juneau.sample.com,2013:1.2345", "Juneau ATOM specification snapshot", "2013-05-08T12:29:29Z") - .links( - link("alternate", "text/html", "http://www.sample.com/2012/05/08/juneau.atom"), - link("enclosure", "audio/mpeg", "http://www.sample.com/audio/juneau_podcast.mp3").length(1337) - ) - .published("2013-05-08T12:29:29Z") - .authors( - person("James Bognar").uri(new URI("http://www.sample.com/")).email("[email protected]") - ) - .contributors( - person("Barry M. Caceres") - ) - .content( - content("xhtml") - .lang("en") - .base("http://www.apache.org/") - .text("<div><p>[Update: Juneau supports ATOM.]</p></div>") - ) - ); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * GET request handler - */ - @RestMethod(name="GET", path="/", summary="Get the sample ATOM feed") - public Feed getFeed() throws Exception { - return feed; - } - - /** - * PUT request handler. - * Replaces the feed with the specified content, and then mirrors it as the response. - */ - @RestMethod(name="PUT", path="/", summary="Overwrite the sample ATOM feed") - public Feed setFeed(@Body Feed feed) throws Exception { - this.feed = feed; - return feed; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/CodeFormatterResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/CodeFormatterResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/CodeFormatterResource.java deleted file mode 100644 index cc7ca69..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/CodeFormatterResource.java +++ /dev/null @@ -1,125 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static org.apache.juneau.dto.html5.HtmlBuilder.*; - -import org.apache.juneau.dto.html5.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; - -/** - * Service at <code>/codeFormatter</code>. - * Used for executing SQL queries against the repository database. - */ -@RestResource( - path="/codeFormatter", - messages="nls/CodeFormatterResource", - title="Code Formatter", - description="Utility for generating HTML code-formatted source code", - htmldoc=@HtmlDoc( - links={ - "up: servlet:/..", - "options: servlet:/?method=OPTIONS", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='min-width:200px' class='text'>", - " <p>Utility for adding code syntax tags to Java and XML/HTML code.</p>", - " <p>It's by no means perfect, but provides a good starting point.</p>", - "</div>" - }, - style="aside {display:table-caption;}" - ) -) -@SuppressWarnings({"serial"}) -public class CodeFormatterResource extends Resource { - - /** [GET /] - Display query entry page. */ - @RestMethod(name="GET", path="/") - public Div getQueryEntryPage(RestRequest req) { - return div( - script("text/javascript", - "\n // Quick and dirty function to allow tabs in textarea." - +"\n function checkTab(e) {" - +"\n if (e.keyCode == 9) {" - +"\n var t = e.target;" - +"\n var ss = t.selectionStart, se = t.selectionEnd;" - +"\n t.value = t.value.slice(0,ss).concat('\\t').concat(t.value.slice(ss,t.value.length));" - +"\n e.preventDefault();" - +"\n }" - +"\n }" - +"\n // Load results from IFrame into this document." - +"\n function loadResults(b) {" - +"\n var doc = b.contentDocument || b.contentWindow.document;" - +"\n var data = doc.getElementById('data') || doc.getElementsByTagName('body')[0];" - +"\n document.getElementById('results').innerHTML = data.innerHTML;" - +"\n }" - ), - form("form").action("codeFormatter").method("POST").target("buff").children( - table( - tr( - th("Language: "), - td( - select().name("lang").children( - option("java","Java"), - option("xml", "XML") - ) - ), - td(button("submit", "Submit"), button("reset", "Reset")) - ), - tr( - td().colspan(3).children( - textarea().name("code").style("min-width:800px;min-height:400px;font-family:Courier;font-size:9pt;").onkeydown("checkTab(event)") - ) - ) - ) - ), - br(), - div().id("results")._class("monospace"), - iframe().name("buff").style("display:none").onload("parent.loadResults(this)") - ); - } - - /** [POST /] - Add syntax highlighting to input. */ - @RestMethod(name="POST", path="/") - public String executeQuery(@FormData("code") String code, @FormData("lang") String lang) throws Exception { - return highlight(code, lang); - } - - private static String highlight(String code, String lang) throws Exception { - if (lang.equalsIgnoreCase("xml")) { - code = code.replaceAll("&", "&"); - code = code.replaceAll("<", "<"); - code = code.replaceAll(">", ">"); - code = code.replaceAll("(<[^\\s&]+>)", "<xt>$1</xt>"); - code = code.replaceAll("(<[^\\s&]+)(\\s)", "<xt>$1</xt>$2"); - code = code.replaceAll("(['\"])(/?>)", "$1<xt>$2</xt>"); - code = code.replaceAll("([\\S]+)=", "<xa>$1</xa>="); - code = code.replaceAll("=(['\"][^'\"]+['\"])", "=<xs>$1</xs>"); - } else if (lang.equalsIgnoreCase("java")) { - code = code.replaceAll("&", "&"); - code = code.replaceAll("<", "<"); - code = code.replaceAll(">", ">"); - code = code.replaceAll("(?s)(\\/\\*\\*.*?\\*\\/)", "<jd>$1</jd>"); // javadoc comments - code = code.replaceAll("(@\\w+)", "<ja>$1</ja>"); // annotations - code = code.replaceAll("(?s)(?!\\/)(\\/\\*.*?\\*\\/)", "<jc>$1</jc>"); // C style comments - code = code.replaceAll("(?m)(\\/\\/.*)", "<jc>$1</jc>"); // C++ style comments - code = code.replaceAll("(?m)('[^'\n]*'|\"[^\"\n]*\")", "<js>$1</js>"); // quotes - code = code.replaceAll("(?<!@)(import|package|boolean|byte|char|double|float|final|static|transient|synchronized|private|protected|public|int|long|short|abstract|class|interface|extends|implements|null|true|false|void|break|case|catch|continue|default|do|else|finally|for|goto|if|instanceof|native|new|return|super|switch|this|threadsafe|throws|throw|try|while)(?=\\W)", "<jk>$1</jk>"); // quotes - code = code.replaceAll("<\\/jk>(\\s+)<jk>", "$1"); // quotes - } - return code; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DirectoryResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DirectoryResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DirectoryResource.java deleted file mode 100644 index 101681a..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DirectoryResource.java +++ /dev/null @@ -1,248 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static org.apache.juneau.rest.annotation.HookEvent.*; - -import static java.util.logging.Level.*; -import static javax.servlet.http.HttpServletResponse.*; -import static org.apache.juneau.html.HtmlDocSerializerContext.*; -import static org.apache.juneau.rest.RestContext.*; - -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.logging.*; - -import org.apache.juneau.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.annotation.Properties; -import org.apache.juneau.rest.converters.*; -import org.apache.juneau.rest.widget.*; -import org.apache.juneau.utils.*; - -/** - * Sample REST resource for exploring local file systems. - */ -@RestResource( - messages="nls/DirectoryResource", - htmldoc=@HtmlDoc( - widgets={ - ContentTypeMenuItem.class, - StyleMenuItem.class - }, - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "$W{ContentTypeMenuItem}", - "$W{StyleMenuItem}", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - } - ), - properties={ - @Property(name=HTML_uriAnchorText, value=PROPERTY_NAME), - @Property(name=REST_allowMethodParam, value="*"), - @Property(name="rootDir", value="$S{java.io.tmpdir}"), - @Property(name="allowViews", value="false"), - @Property(name="allowDeletes", value="false"), - @Property(name="allowPuts", value="false") - } -) -public class DirectoryResource extends Resource { - private static final long serialVersionUID = 1L; - - - private File rootDir; // The root directory - - // Settings enabled through servlet init parameters - private boolean allowDeletes, allowPuts, allowViews; - - private static Logger logger = Logger.getLogger(DirectoryResource.class.getName()); - - @RestHook(INIT) - public void init(RestConfig config) throws Exception { - ObjectMap p = config.getProperties(); - rootDir = new File(p.getString("rootDir")); - allowViews = p.getBoolean("allowViews", false); - allowDeletes = p.getBoolean("allowDeletes", false); - allowPuts = p.getBoolean("allowPuts", false); - } - - /** Returns the root directory defined by the 'rootDir' init parameter */ - protected File getRootDir() { - if (rootDir == null) { - rootDir = new File(getProperties().getString("rootDir")); - if (! rootDir.exists()) - if (! rootDir.mkdirs()) - throw new RuntimeException("Could not create root dir"); - } - return rootDir; - } - - /** GET request handler */ - @RestMethod(name="GET", path="/*", converters={Queryable.class}) - public Object doGet(RestRequest req, @Properties ObjectMap properties) throws Exception { - - String pathInfo = req.getPathInfo(); - File f = pathInfo == null ? rootDir : new File(rootDir.getAbsolutePath() + pathInfo); - - if (!f.exists()) - throw new RestException(SC_NOT_FOUND, "File not found"); - - properties.put("path", f.getAbsolutePath()); - - if (f.isDirectory()) { - List<FileResource> l = new LinkedList<FileResource>(); - for (File fc : f.listFiles()) { - URL fUrl = new URL(req.getRequestURL().append("/").append(fc.getName()).toString()); - l.add(new FileResource(fc, fUrl)); - } - return l; - } - - return new FileResource(f, new URL(req.getRequestURL().toString())); - } - - /** DELETE request handler */ - @RestMethod(name="DELETE", path="/*", guards=AdminGuard.class) - public Object doDelete(RestRequest req) throws Exception { - - if (! allowDeletes) - throw new RestException(SC_METHOD_NOT_ALLOWED, "DELETE not enabled"); - - File f = new File(rootDir.getAbsolutePath() + req.getPathInfo()); - deleteFile(f); - - if (req.getHeader("Accept").contains("text/html")) - return new Redirect(); - return "File deleted"; - } - - /** PUT request handler */ - @RestMethod(name="PUT", path="/*", guards=AdminGuard.class) - public Object doPut(RestRequest req) throws Exception { - - if (! allowPuts) - throw new RestException(SC_METHOD_NOT_ALLOWED, "PUT not enabled"); - - File f = new File(rootDir.getAbsolutePath() + req.getPathInfo()); - String parentSubPath = f.getParentFile().getAbsolutePath().substring(rootDir.getAbsolutePath().length()); - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f)); - IOPipe.create(req.getInputStream(), bos).closeOut().run(); - if (req.getContentType().contains("html")) - return new Redirect(parentSubPath); - return "File added"; - } - - /** VIEW request handler (overloaded GET for viewing file contents) */ - @RestMethod(name="VIEW", path="/*") - public void doView(RestRequest req, RestResponse res) throws Exception { - - if (! allowViews) - throw new RestException(SC_METHOD_NOT_ALLOWED, "VIEW not enabled"); - - File f = new File(rootDir.getAbsolutePath() + req.getPathInfo()); - - if (!f.exists()) - throw new RestException(SC_NOT_FOUND, "File not found"); - - if (f.isDirectory()) - throw new RestException(SC_METHOD_NOT_ALLOWED, "VIEW not available on directories"); - - res.setOutput(new FileReader(f)).setContentType("text/plain"); - } - - /** DOWNLOAD request handler (overloaded GET for downloading file contents) */ - @RestMethod(name="DOWNLOAD") - public void doDownload(RestRequest req, RestResponse res) throws Exception { - - if (! allowViews) - throw new RestException(SC_METHOD_NOT_ALLOWED, "DOWNLOAD not enabled"); - - File f = new File(rootDir.getAbsolutePath() + req.getPathInfo()); - - if (!f.exists()) - throw new RestException(SC_NOT_FOUND, "File not found"); - - if (f.isDirectory()) - throw new RestException(SC_METHOD_NOT_ALLOWED, "DOWNLOAD not available on directories"); - - res.setOutput(new FileReader(f)).setContentType("application"); - } - - /** File POJO */ - public class FileResource { - private File f; - private URL url; - - /** Constructor */ - public FileResource(File f, URL url) { - this.f = f; - this.url = url; - } - - // Bean property getters - - public URL getUrl() { - return url; - } - - public String getType() { - return (f.isDirectory() ? "dir" : "file"); - } - - public String getName() { - return f.getName(); - } - - public long getSize() { - return f.length(); - } - - public Date getLastModified() { - return new Date(f.lastModified()); - } - - public URL getView() throws Exception { - if (allowViews && f.canRead() && ! f.isDirectory()) - return new URL(url + "?method=VIEW"); - return null; - } - - public URL getDownload() throws Exception { - if (allowViews && f.canRead() && ! f.isDirectory()) - return new URL(url + "?method=DOWNLOAD"); - return null; - } - - public URL getDelete() throws Exception { - if (allowDeletes && f.canWrite()) - return new URL(url + "?method=DELETE"); - return null; - } - } - - /** Utility method */ - private void deleteFile(File f) { - try { - if (f.isDirectory()) - for (File fc : f.listFiles()) - deleteFile(fc); - f.delete(); - } catch (Exception e) { - logger.log(WARNING, "Cannot delete file '" + f.getAbsolutePath() + "'", e); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DockerRegistryResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DockerRegistryResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DockerRegistryResource.java deleted file mode 100644 index abad766..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/DockerRegistryResource.java +++ /dev/null @@ -1,100 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static org.apache.juneau.rest.annotation.HookEvent.*; - -import java.util.*; - -import org.apache.juneau.ini.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.client.*; -import org.apache.juneau.rest.labels.*; - -/** - * Sample resource that shows how to mirror query results from a Docker registry. - */ -@RestResource( - path="/docker", - title="Sample Docker resource", - description="Docker registry explorer", - htmldoc=@HtmlDoc( - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - // Pull in aside contents from file. - aside="$F{resources/DockerRegistryResourceAside.html}" - ) -) -public class DockerRegistryResource extends Resource { - private static final long serialVersionUID = 1L; - - // Get registry URL from examples.cfg file. - private String registryUrl; - - RestClient rc; - - /** - * Initializes the registry URL and rest client. - * - * @param servletConfig The resource config. - * @throws Exception - */ - @RestHook(INIT) - public void initRegistry(RestConfig config) throws Exception { - ConfigFile cf = config.getConfigFile(); - registryUrl = cf.getString("DockerRegistry/url"); - rc = new RestClientBuilder().build(); - } - - @Override /* Servlet */ - public void destroy() { - rc.closeQuietly(); - super.destroy(); - } - - /** [GET /] - Show child resources. */ - @SuppressWarnings("nls") - @RestMethod(name="GET", path="/") - public ResourceDescription[] getChildren(RestRequest req) { - return new ResourceDescription[] { - new ResourceDescription("search", "Search Registry") - }; - } - - /** - * PUT request handler. - * Replaces the feed with the specified content, and then mirrors it as the response. - */ - @RestMethod(name="GET", path="/search") - public QueryResults query(@Query("q") String q) throws Exception { - String url = registryUrl + "/search" + (q == null ? "" : "?q=" + q); - synchronized(rc) { - return rc.doGet(url).getResponse(QueryResults.class); - } - } - - public static class QueryResults { - public int num_results; - public String query; - public List<DockerImage> results; - } - - public static class DockerImage { - public String name, description; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/HelloWorldResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/HelloWorldResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/HelloWorldResource.java deleted file mode 100644 index dcf3b08..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/HelloWorldResource.java +++ /dev/null @@ -1,48 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.annotation.*; - -/** - * Sample REST resource that prints out a simple "Hello world!" message. - */ -@RestResource( - messages="nls/HelloWorldResource", - title="Hello World", - description="An example of the simplest-possible resource", - path="/helloWorld", - htmldoc=@HtmlDoc( - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='max-width:400px' class='text'>", - " <p>This page shows a resource that simply response with a 'Hello world!' message</p>", - " <p>The POJO serialized is a simple String.</p>", - "</div>" - } - ) -) -public class HelloWorldResource extends Resource { - private static final long serialVersionUID = 1L; - - /** GET request handler */ - @RestMethod(name="GET", path="/*", summary="Responds with \"Hello world!\"") - public String sayHello() { - return "Hello world!"; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/JsonSchemaResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/JsonSchemaResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/JsonSchemaResource.java deleted file mode 100644 index 5a201b8..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/JsonSchemaResource.java +++ /dev/null @@ -1,89 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import org.apache.juneau.dto.jsonschema.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.widget.*; - -/** - * Sample resource that shows how to serialize JSON-Schema documents. - */ -@RestResource( - path="/jsonSchema", - messages="nls/JsonSchemaResource", - title="Sample JSON-Schema document", - description="Sample resource that shows how to generate JSON-Schema documents", - htmldoc=@HtmlDoc( - widgets={ - ContentTypeMenuItem.class, - StyleMenuItem.class - }, - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "$W{ContentTypeMenuItem}", - "$W{StyleMenuItem}", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='min-width:200px' class='text'>", - " <p>Shows how to produce JSON-Schema documents in a variety of languages using the JSON-Schema DTOs.</p>", - "</div>" - } - ) -) -public class JsonSchemaResource extends ResourceJena { - private static final long serialVersionUID = 1L; - - private Schema schema; // The schema document - - @Override /* Servlet */ - public void init() { - - try { - schema = new Schema() - .setId("http://example.com/sample-schema#") - .setSchemaVersionUri("http://json-schema.org/draft-04/schema#") - .setTitle("Example Schema") - .setType(JsonType.OBJECT) - .addProperties( - new SchemaProperty("firstName", JsonType.STRING), - new SchemaProperty("lastName", JsonType.STRING), - new SchemaProperty("age", JsonType.INTEGER) - .setDescription("Age in years") - .setMinimum(0) - ) - .addRequired("firstName", "lastName"); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** GET request handler */ - @RestMethod(name="GET", path="/", summary="Get the JSON-Schema document") - public Schema getSchema() throws Exception { - return schema; - } - - /** - * PUT request handler. - * Replaces the schema document with the specified content, and then mirrors it as the response. - */ - @RestMethod(name="PUT", path="/", summary="Overwrite the JSON-Schema document") - public Schema setSchema(@Body Schema schema) throws Exception { - this.schema = schema; - return schema; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/MethodExampleResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/MethodExampleResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/MethodExampleResource.java deleted file mode 100644 index a0c7d44..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/MethodExampleResource.java +++ /dev/null @@ -1,189 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import java.util.*; - -import org.apache.juneau.http.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.annotation.Method; -import org.apache.juneau.rest.labels.*; -import org.apache.juneau.utils.*; - -/** - * Sample REST resource that shows how to define REST methods. - */ -@RestResource( - path="/methodExample", - messages="nls/MethodExampleResource", - htmldoc=@HtmlDoc( - links={ - "up: servlet:/..", - "options: servlet:/?method=OPTIONS", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='max-width:400px' class='text'>", - " <p>Shows the different methods for retrieving HTTP query/form-data parameters, headers, and path variables.</p>", - " <p>Each method is functionally equivalent but demonstrate different ways to accomplish the same tasks.</p>", - "</div>" - } - ) -) -public class MethodExampleResource extends Resource { - private static final long serialVersionUID = 1L; - - private static final UUID SAMPLE_UUID = UUID.fromString("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); - private static final String SAMPLE_UUID_STRING = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"; - - /** Example GET request that redirects to our example method */ - @RestMethod(name="GET", path="/") - public ResourceDescription[] doExample() throws Exception { - return new ResourceDescription[] { - new ResourceDescription("example1/foo/123/"+SAMPLE_UUID+"/path-remainder?q1=456&q2=bar", "Example 1 - Annotated method attributes."), - new ResourceDescription("example2/foo/123/"+SAMPLE_UUID+"/path-remainder?q1=456&q2=bar", "Example 2 - Low-level RestRequest/RestResponse objects."), - new ResourceDescription("example3/foo/123/"+SAMPLE_UUID+"/path-remainder?q1=456&q2=bar", "Example 3 - Intermediate-level APIs.") - }; - } - - /** - * Methodology #1 - GET request using annotated attributes. - * This approach uses annotated parameters for retrieving input. - */ - @RestMethod(name="GET", path="/example1/{p1}/{p2}/{p3}/*") - public Map<String,Object> example1( - @Method String method, // HTTP method. - @Path String p1, // Path variables. - @Path int p2, - @Path UUID p3, - @Query("q1") int q1, // Query parameters. - @Query("q2") String q2, - @Query(name="q3",def=SAMPLE_UUID_STRING) UUID q3, - @PathRemainder String remainder, // Path remainder after pattern match. - @Header("Accept-Language") String lang, // Headers. - @Header("Accept") String accept, - @Header(name="DNT",def="1") Integer doNotTrack - ) { - - // Send back a simple Map response - return new AMap<String,Object>() - .append("method", method) - .append("path-p1", p1) - .append("path-p2", p2) - .append("path-p3", p3) - .append("remainder", remainder) - .append("query-q1", q1) - .append("query-q2", q2) - .append("query-q3", q3) - .append("header-lang", lang) - .append("header-accept", accept) - .append("header-doNotTrack", doNotTrack); - } - - /** - * Methodology #2 - GET request using methods on RestRequest and RestResponse. - * This approach uses low-level request/response objects to perform the same as above. - */ - @RestMethod(name="GET", path="/example2/{p1}/{p2}/{p3}/*") - public void example2( - RestRequest req, // A direct subclass of HttpServletRequest. - RestResponse res // A direct subclass of HttpServletResponse. - ) throws Exception { - - // HTTP method. - String method = req.getMethod(); - - // Path variables. - RequestPathMatch path = req.getPathMatch(); - String p1 = path.get("p1", String.class); - int p2 = path.get("p2", int.class); - UUID p3 = path.get("p3", UUID.class); - - // Query parameters. - RequestQuery query = req.getQuery(); - int q1 = query.get("q1", 0, int.class); - String q2 = query.get("q2", String.class); - UUID q3 = query.get("q3", SAMPLE_UUID, UUID.class); - - // Path remainder after pattern match. - String remainder = req.getPathMatch().getRemainder(); - - // Headers. - String lang = req.getHeader("Accept-Language"); - String accept = req.getHeader("Accept"); - int doNotTrack = req.getHeaders().get("DNT", 1, int.class); - - // Send back a simple Map response - Map<String,Object> m = new AMap<String,Object>() - .append("method", method) - .append("path-p1", p1) - .append("path-p2", p2) - .append("path-p3", p3) - .append("remainder", remainder) - .append("query-q1", q1) - .append("query-q2", q2) - .append("query-q3", q3) - .append("header-lang", lang) - .append("header-accept", accept) - .append("header-doNotTrack", doNotTrack); - res.setOutput(m); - } - - /** - * Methodology #3 - GET request using special objects. - * This approach uses intermediate-level APIs. - * The framework recognizes the parameter types and knows how to resolve them. - */ - @RestMethod(name="GET", path="/example3/{p1}/{p2}/{p3}/*") - public Map<String,Object> example3( - HttpMethod method, // HTTP method. - RequestPathMatch path, // Path variables. - RequestQuery query, // Query parameters. - RequestHeaders headers, // Headers. - AcceptLanguage lang, // Specific header classes. - Accept accept - ) throws Exception { - - // Path variables. - String p1 = path.get("p1", String.class); - int p2 = path.get("p2", int.class); - UUID p3 = path.get("p3", UUID.class); - - // Query parameters. - int q1 = query.get("q1", 0, int.class); - String q2 = query.get("q2", String.class); - UUID q3 = query.get("q3", SAMPLE_UUID, UUID.class); - - // Path remainder after pattern match. - String remainder = path.getRemainder(); - - // Headers. - int doNotTrack = headers.get("DNT", 1, int.class); - - // Send back a simple Map response - return new AMap<String,Object>() - .append("method", method) - .append("path-p1", p1) - .append("path-p2", p2) - .append("path-p3", p3) - .append("remainder", remainder) - .append("query-q1", q1) - .append("query-q2", q2) - .append("query-q3", q3) - .append("header-lang", lang) - .append("header-accept", accept) - .append("header-doNotTrack", doNotTrack); - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PetStoreResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PetStoreResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PetStoreResource.java deleted file mode 100644 index 868c205..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PetStoreResource.java +++ /dev/null @@ -1,240 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static org.apache.juneau.dto.html5.HtmlBuilder.*; -import static org.apache.juneau.rest.annotation.HookEvent.*; - -import java.util.*; -import java.util.Map; - -import org.apache.juneau.annotation.*; -import org.apache.juneau.dto.html5.*; -import org.apache.juneau.html.*; -import org.apache.juneau.html.annotation.Html; -import org.apache.juneau.json.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.annotation.Body; -import org.apache.juneau.rest.converters.*; -import org.apache.juneau.rest.widget.*; -import org.apache.juneau.serializer.*; -import org.apache.juneau.transforms.*; - -/** - * Sample REST resource that renders summary and detail views of the same bean. - */ -@RestResource( - title="Pet Store", - description="An example of a typical REST resource where beans are rendered in summary and details views.", - path="/petstore", - htmldoc=@HtmlDoc( - widgets={ - ContentTypeMenuItem.class, - StyleMenuItem.class, - PetStoreResource.AddPet.class - }, - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "$W{ContentTypeMenuItem}", - "$W{StyleMenuItem}", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java", - "$W{AddPet}" - }, - aside={ - "<div style='max-width:400px' class='text'>", - " <p>This page shows a standard REST resource that renders bean summaries and details.</p>", - " <p>It shows how different properties can be rendered on the same bean in different views.</p>", - " <p>It also shows examples of HtmlRender classes and @BeanProperty(format) annotations.</p>", - " <p>It also shows how the Queryable converter and query widget can be used to create searchable interfaces.</p>", - "</div>" - } - ) -) -public class PetStoreResource extends ResourceJena { - private static final long serialVersionUID = 1L; - - // Our database. - private Map<Integer,Pet> petDB; - - /** - * Initializes the pet store database. - * - * @param RestConfig config The resource config. - * @throws Exception - */ - @RestHook(INIT) - public void initDatabase(RestConfig config) throws Exception { - // Load our database from a local JSON file. - petDB = JsonParser.DEFAULT.parse(getClass().getResourceAsStream("PetStore.json"), LinkedHashMap.class, Integer.class, Pet.class); - } - - // Exclude the 'breed' and 'getsAlongWith' properties from the beans. - @RestMethod( - name="GET", - path="/", - summary="The complete list of pets in the store", - bpx="Pet: breed,getsAlongWith", - - // Add our converter for POJO query support. - converters=Queryable.class, - - // Add our menu items in the nav links. - htmldoc=@HtmlDoc( - - widgets={ - QueryMenuItem.class, - ContentTypeMenuItem.class, - StyleMenuItem.class - }, - - links={ - "INHERIT", // Inherit links from class. - "[2]:$W{QueryMenuItem}" // Insert QUERY link in position 2. - } - ) - ) - public Collection<Pet> getPets() { - return petDB.values(); - } - - // Shows all bean properties. - @RestMethod(name="GET", path="/{id}", summary="Pet details") - public Pet getPet(@Path("id") Integer id) { - return petDB.get(id); - } - - @RestMethod(name="POST", path="/") - public Redirect addPet(@Body Pet pet) throws Exception { - this.petDB.put(pet.id, pet); - return new Redirect("servlet:/"); - } - - // Our bean class. - public static class Pet { - - @Html(link="servlet:/{id}") // Creates a hyperlink in HTML view. - @NameProperty // Links the parent key to this bean. - public int id; - - public String name; - public Kind kind; - public String breed; - public List<Kind> getsAlongWith; - - @BeanProperty(format="$%.2f") // Renders price in dollars. - public float price; - - @BeanProperty(swap=DateSwap.ISO8601D.class) // Renders dates in ISO8601 format. - public Date birthDate; - - public int getAge() { - Calendar c = new GregorianCalendar(); - c.setTime(birthDate); - return new GregorianCalendar().get(Calendar.YEAR) - c.get(Calendar.YEAR); - } - } - - @Html(render=KindRender.class) // Render as an icon in HTML. - public static enum Kind { - CAT, DOG, BIRD, FISH, MOUSE, RABBIT, SNAKE - } - - public static class KindRender extends HtmlRender<Kind> { - @Override - public Object getContent(SerializerSession session, Kind value) { - return new Img().src("servlet:/htdocs/"+value.toString().toLowerCase()+".png"); - } - @Override - public String getStyle(SerializerSession session, Kind value) { - return "background-color:#FDF2E9"; - } - } - - /** - * Renders the "ADD" menu item. - */ - public class AddPet extends MenuItemWidget { - - @Override - public String getLabel(RestRequest req) throws Exception { - return "add"; - } - - @Override - public Object getContent(RestRequest req) throws Exception { - return div( - form().id("form").action("servlet:/").method("POST").children( - table( - tr( - th("ID:"), - td(input().name("id").type("number").value(getNextAvailableId())), - td(new Tooltip("(?)", "A unique identifer for the pet.", br(), "Must not conflict with existing IDs")) - ), - tr( - th("Name:"), - td(input().name("name").type("text")), - td(new Tooltip("(?)", "The name of the pet.", br(), "e.g. 'Fluffy'")) - ), - tr( - th("Kind:"), - td( - select().name("kind").children( - option("CAT"), option("DOG"), option("BIRD"), option("FISH"), option("MOUSE"), option("RABBIT"), option("SNAKE") - ) - ), - td(new Tooltip("(?)", "The kind of animal.")) - ), - tr( - th("Breed:"), - td(input().name("breed").type("text")), - td(new Tooltip("(?)", "The breed of animal.", br(), "Can be any arbitrary text")) - ), - tr( - th("Gets along with:"), - td(input().name("getsAlongWith").type("text")), - td(new Tooltip("(?)", "A comma-delimited list of other animal types that this animal gets along with.")) - ), - tr( - th("Price:"), - td(input().name("price").type("number").placeholder("1.0").step("0.01").min(1).max(100)), - td(new Tooltip("(?)", "The price to charge for this pet.")) - ), - tr( - th("Birthdate:"), - td(input().name("birthDate").type("date")), - td(new Tooltip("(?)", "The pets birthday.")) - ), - tr( - td().colspan(2).style("text-align:right").children( - button("reset", "Reset"), - button("button","Cancel").onclick("window.location.href='/'"), - button("submit", "Submit") - ) - ) - ).style("white-space:nowrap") - ) - ); - } - } - - private int getNextAvailableId() { - int i = 100; - for (Integer k : petDB.keySet()) - i = Math.max(i, k); - return i+1; - } -} - http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PhotosResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PhotosResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PhotosResource.java deleted file mode 100644 index 475ef07..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/PhotosResource.java +++ /dev/null @@ -1,180 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static javax.servlet.http.HttpServletResponse.*; -import static org.apache.juneau.html.HtmlSerializerContext.*; - -import java.awt.image.*; -import java.io.*; -import java.net.*; -import java.net.URI; -import java.util.*; - -import javax.imageio.*; - -import org.apache.juneau.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.parser.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.serializer.*; - -/** - * Sample resource that allows images to be uploaded and retrieved. - */ -@RestResource( - path="/photos", - messages="nls/PhotosResource", - title="Photo REST service", - description="Sample resource that allows images to be uploaded and retrieved.", - htmldoc=@HtmlDoc( - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='max-width:400px;min-width:200px' class='text'>", - " <p>Shows an example of using custom serializers and parsers to create REST interfaces over binary resources.</p>", - " <p>In this case, our resources are marshalled jpeg and png binary streams and are stored in an in-memory 'database' (also known as a <code>TreeMap</code>).</p>", - "</div>" - } - ), - properties={ - // Make the anchor text on URLs be just the path relative to the servlet. - @Property(name=HTML_uriAnchorText, value="SERVLET_RELATIVE") - } -) -public class PhotosResource extends Resource { - private static final long serialVersionUID = 1L; - - // Our cache of photos - private Map<String,Photo> photos = new TreeMap<String,Photo>(); - - @Override /* Servlet */ - public void init() { - try { - // Preload an image. - InputStream is = getClass().getResourceAsStream("averycutecat.jpg"); - BufferedImage image = ImageIO.read(is); - Photo photo = new Photo("cat", image); - photos.put(photo.id, photo); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** Our bean class for storing photos */ - public static class Photo { - String id; - BufferedImage image; - - Photo(String id, BufferedImage image) { - this.id = id; - this.image = image; - } - - public URI getURI() throws URISyntaxException { - return new URI("servlet:/" + id); - } - } - - /** GET request handler for list of all photos */ - @RestMethod(name="GET", path="/", summary="Show the list of all currently loaded photos") - public Collection<Photo> getAllPhotos() throws Exception { - return photos.values(); - } - - /** GET request handler for single photo */ - @RestMethod(name="GET", path="/{id}", serializers=ImageSerializer.class, summary="Get a photo by ID") - public BufferedImage getPhoto(@Path String id) throws Exception { - Photo p = photos.get(id); - if (p == null) - throw new RestException(SC_NOT_FOUND, "Photo not found"); - return p.image; - } - - /** PUT request handler */ - @RestMethod(name="PUT", path="/{id}", parsers=ImageParser.class, summary="Add or overwrite a photo") - public String addPhoto(@Path String id, @Body BufferedImage image) throws Exception { - photos.put(id, new Photo(id, image)); - return "OK"; - } - - /** POST request handler */ - @RestMethod(name="POST", path="/", parsers=ImageParser.class, summary="Add a photo") - public Photo setPhoto(@Body BufferedImage image) throws Exception { - Photo p = new Photo(UUID.randomUUID().toString(), image); - photos.put(p.id, p); - return p; - } - - /** DELETE request handler */ - @RestMethod(name="DELETE", path="/{id}", summary="Delete a photo by ID") - public String deletePhoto(@Path String id) throws Exception { - Photo p = photos.remove(id); - if (p == null) - throw new RestException(SC_NOT_FOUND, "Photo not found"); - return "OK"; - } - - /** Serializer for converting images to byte streams */ - public static class ImageSerializer extends OutputStreamSerializer { - - /** - * Constructor. - * @param propertyStore The property store containing all the settings for this object. - */ - public ImageSerializer(PropertyStore propertyStore) { - super(propertyStore, null, "image/png", "image/jpeg"); - } - - @Override /* Serializer */ - public OutputStreamSerializerSession createSession(SerializerSessionArgs args) { - return new OutputStreamSerializerSession(args) { - - @Override /* SerializerSession */ - protected void doSerialize(SerializerPipe out, Object o) throws Exception { - RenderedImage image = (RenderedImage)o; - String mediaType = getStringProperty("mediaType"); - ImageIO.write(image, mediaType.substring(mediaType.indexOf('/')+1), out.getOutputStream()); - } - }; - } - } - - /** Parser for converting byte streams to images */ - public static class ImageParser extends InputStreamParser { - - /** - * Constructor. - * @param propertyStore The property store containing all the settings for this object. - */ - public ImageParser(PropertyStore propertyStore) { - super(propertyStore, "image/png", "image/jpeg"); - } - - @Override /* Parser */ - public InputStreamParserSession createSession(final ParserSessionArgs args) { - return new InputStreamParserSession(args) { - - @Override /* ParserSession */ - @SuppressWarnings("unchecked") - protected <T> T doParse(ParserPipe pipe, ClassMeta<T> type) throws Exception { - return (T)ImageIO.read(pipe.getInputStream()); - } - }; - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RequestEchoResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RequestEchoResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RequestEchoResource.java deleted file mode 100644 index 82a6a4c..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RequestEchoResource.java +++ /dev/null @@ -1,77 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static org.apache.juneau.html.HtmlDocSerializerContext.*; - -import javax.servlet.*; -import javax.servlet.http.*; - -import org.apache.juneau.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.converters.*; -import org.apache.juneau.rest.widget.*; -import org.apache.juneau.transforms.*; - -/** - * Sample REST resource for echoing HttpServletRequests back to the browser. - */ -@RestResource( - path="/echo", - title="Request echo service", - description="Echos the current HttpServletRequest object back to the browser.", - htmldoc=@HtmlDoc( - widgets={ - ContentTypeMenuItem.class, - StyleMenuItem.class - }, - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "$W{ContentTypeMenuItem}", - "$W{StyleMenuItem}", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='max-width:400px;min-width:200px' class='text'>", - " <p>Shows how even arbitrary POJOs such as <code>HttpServletRequest</code> can be serialized by the framework.</p>", - " <p>Also shows how to specify serializer properties, filters, and swaps at the servlet level to control how POJOs are serialized.</p>", - " <p>Also provides an example of how to use the Traversable and Queryable APIs.</p>", - "</div>" - } - ), - properties={ - @Property(name=SERIALIZER_maxDepth, value="5"), - @Property(name=SERIALIZER_detectRecursions, value="true") - }, - beanFilters={ - // Interpret these as their parent classes, not subclasses - HttpServletRequest.class, HttpSession.class, ServletContext.class, - }, - pojoSwaps={ - // Add a special filter for Enumerations - EnumerationSwap.class - } -) -public class RequestEchoResource extends Resource { - private static final long serialVersionUID = 1L; - - /** GET request handler */ - @RestMethod(name="*", path="/*", converters={Traversable.class,Queryable.class}, summary="Serializes the incoming HttpServletRequest object.") - public HttpServletRequest doGet(RestRequest req, RestResponse res, @Properties ObjectMap properties) { - // Just echo the request back as the response. - return req; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RootResources.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RootResources.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RootResources.java deleted file mode 100644 index 9ee9abe..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/RootResources.java +++ /dev/null @@ -1,76 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import org.apache.juneau.examples.rest.addressbook.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.microservice.resources.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.widget.*; - -/** - * Sample REST resource showing how to implement a "router" resource page. - */ -@RestResource( - path="/", - title="Root resources", - description="Example of a router resource page.", - htmldoc=@HtmlDoc( - widgets={ - PoweredByApache.class, - ContentTypeMenuItem.class, - StyleMenuItem.class - }, - links={ - "options: ?method=OPTIONS", - "$W{ContentTypeMenuItem}", - "$W{StyleMenuItem}", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='max-width:400px' class='text'>", - " <p>This is an example of a 'router' page that serves as a jumping-off point to child resources.</p>", - " <p>Resources can be nested arbitrarily deep through router pages.</p>", - " <p>Note the <span class='link'>options</span> link provided that lets you see the generated swagger doc for this page.</p>", - " <p>Also note the <span class='link'>sources</span> link on these pages to view the source code for the page.</p>", - " <p>All content on pages in the UI are serialized POJOs. In this case, it's a serialized array of beans with 2 properties, 'name' and 'description'.</p>", - " <p>Other features (such as this aside) are added through annotations.</p>", - "</div>" - }, - footer="$W{PoweredByApache}" - ), - children={ - HelloWorldResource.class, - PetStoreResource.class, - SystemPropertiesResource.class, - MethodExampleResource.class, - RequestEchoResource.class, - TempDirResource.class, - AddressBookResource.class, - SampleRemoteableServlet.class, - PhotosResource.class, - AtomFeedResource.class, - JsonSchemaResource.class, - SqlQueryResource.class, - TumblrParserResource.class, - CodeFormatterResource.class, - UrlEncodedFormResource.class, - ConfigResource.class, - LogsResource.class, - DockerRegistryResource.class, - ShutdownResource.class - } -) -public class RootResources extends ResourceJenaGroup { - private static final long serialVersionUID = 1L; -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SampleRemoteableServlet.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SampleRemoteableServlet.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SampleRemoteableServlet.java deleted file mode 100644 index 1306d97..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SampleRemoteableServlet.java +++ /dev/null @@ -1,68 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static org.apache.juneau.rest.RestContext.*; - -import java.util.*; - -import org.apache.juneau.examples.addressbook.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.remoteable.*; - -/** - * Class showing the functionality of the RemoteableServlet class. - */ -@SuppressWarnings("serial") -@RestResource( - path="/remoteable", - messages="nls/SampleRemoteableServlet", - title="Remoteable Service Proxy API", - description="Sample class showing how to use remoteable proxies.", - htmldoc=@HtmlDoc( - links={ - "up: request:/..", - "options: servlet:/?method=OPTIONS", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='max-width:400px;min-width:200px' class='text'>", - " <p>Shows how to use the <code>RemoteableServlet</code> class to define RPC-style remoteable interfaces using REST as a protocol.</p>", - " <p>Remoteable proxies are retrieved on the client side using <code>RestClient.getInterfaceProxy(Class)</code>.</p>", - " <p>Methods are invoked using POSTs of serialized arrays of objects and the returned value is marshalled back as a response.</p>", - " <p>GET requests (as shown here) show the available methods on the interface.</p>", - "</div>" - } - ), - properties={ - // Allow us to use method=POST from a browser. - @Property(name=REST_allowMethodParam, value="*") - }, - config="$S{juneau.configFile}" // So we can resolve $C{Source/gitHub} above. -) -public class SampleRemoteableServlet extends RemoteableServlet { - - AddressBook addressBook = new AddressBook(); - - @Override /* RemoteableServlet */ - protected Map<Class<?>,Object> getServiceMap() throws Exception { - Map<Class<?>,Object> m = new LinkedHashMap<Class<?>,Object>(); - - // In this simplified example, we expose the same POJO service under two different interfaces. - // One is IAddressBook which only exposes methods defined on that interface, and - // the other is AddressBook itself which exposes all methods defined on the class itself. - m.put(IAddressBook.class, addressBook); - m.put(AddressBook.class, addressBook); - return m; - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab15d45b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SqlQueryResource.java ---------------------------------------------------------------------- diff --git a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SqlQueryResource.java b/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SqlQueryResource.java deleted file mode 100644 index 691f0d0..0000000 --- a/juneau-examples-rest/src/main/java/org/apache/juneau/examples/rest/SqlQueryResource.java +++ /dev/null @@ -1,190 +0,0 @@ -// *************************************************************************************************************************** -// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * -// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * -// * to you 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. * -// *************************************************************************************************************************** -package org.apache.juneau.examples.rest; - -import static javax.servlet.http.HttpServletResponse.*; -import static org.apache.juneau.dto.html5.HtmlBuilder.*; -import static org.apache.juneau.internal.StringUtils.*; -import static org.apache.juneau.rest.annotation.HookEvent.*; - -import java.sql.*; -import java.util.*; - -import org.apache.juneau.dto.*; -import org.apache.juneau.dto.html5.*; -import org.apache.juneau.ini.*; -import org.apache.juneau.microservice.*; -import org.apache.juneau.rest.*; -import org.apache.juneau.rest.annotation.*; -import org.apache.juneau.rest.annotation.Body; -import org.apache.juneau.rest.widget.*; - -/** - * Sample resource that shows how Juneau can serialize ResultSets. - */ -@RestResource( - path="/sqlQuery", - messages="nls/SqlQueryResource", - title="SQL query service", - description="Executes queries against the local derby '$C{SqlQueryResource/connectionUrl}' database", - htmldoc=@HtmlDoc( - widgets={ - StyleMenuItem.class - }, - links={ - "up: request:/..", - "options: servlet:/..", - "$W{StyleMenuItem}", - "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" - }, - aside={ - "<div style='min-width:200px' class='text'>", - " <p>An example of a REST interface over a relational database.</p>", - " <p><a class='link' href='?sql=select+*+from sys.systables'>try me</a></p>", - "</div>" - } - ) -) -public class SqlQueryResource extends Resource { - private static final long serialVersionUID = 1L; - - private String driver, connectionUrl; - private boolean allowUpdates, allowTempUpdates, includeRowNums; - - /** - * Initializes the registry URL and rest client. - * - * @param servletConfig The resource config. - * @throws Exception - */ - @RestHook(INIT) - public void initConnection(RestConfig config) throws Exception { - ConfigFile cf = config.getConfigFile(); - - driver = cf.getString("SqlQueryResource/driver"); - connectionUrl = cf.getString("SqlQueryResource/connectionUrl"); - allowUpdates = cf.getBoolean("SqlQueryResource/allowUpdates", false); - allowTempUpdates = cf.getBoolean("SqlQueryResource/allowTempUpdates", false); - includeRowNums = cf.getBoolean("SqlQueryResource/includeRowNums", false); - - try { - Class.forName(driver).newInstance(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** GET request handler - Display the query entry page. */ - @RestMethod(name="GET", path="/", summary="Display the query entry page") - public Div doGet(RestRequest req, @Query("sql") String sql) { - return div( - script("text/javascript", - "\n // Quick and dirty function to allow tabs in textarea." - +"\n function checkTab(e) {" - +"\n if (e.keyCode == 9) {" - +"\n var t = e.target;" - +"\n var ss = t.selectionStart, se = t.selectionEnd;" - +"\n t.value = t.value.slice(0,ss).concat('\\t').concat(t.value.slice(ss,t.value.length));" - +"\n e.preventDefault();" - +"\n }" - +"\n }" - +"\n // Load results from IFrame into this document." - +"\n function loadResults(b) {" - +"\n var doc = b.contentDocument || b.contentWindow.document;" - +"\n var data = doc.getElementById('data') || doc.getElementsByTagName('body')[0];" - +"\n document.getElementById('results').innerHTML = data.innerHTML;" - +"\n }" - ), - form("sqlQuery").method("POST").target("buf").children( - table( - tr( - th("Position (1-10000):"), - td(input().name("pos").type("number").value(1)), - th("Limit (1-10000):"), - td(input().name("limit").type("number").value(100)), - td(button("submit", "Submit"), button("reset", "Reset")) - ), - tr( - td().colspan(5).children( - textarea().name("sql").text(sql == null ? " " : sql).style("width:100%;height:200px;font-family:Courier;font-size:9pt;").onkeydown("checkTab(event)") - ) - ) - ) - ), - br(), - div().id("results"), - iframe().name("buf").style("display:none").onload("parent.loadResults(this)") - ); - } - - /** POST request handler - Execute the query. */ - @RestMethod(name="POST", path="/", summary="Execute one or more queries") - public List<Object> doPost(@Body PostInput in) throws Exception { - - List<Object> results = new LinkedList<Object>(); - - // Don't try to submit empty input. - if (isEmpty(in.sql)) - return results; - - if (in.pos < 1 || in.pos > 10000) - throw new RestException(SC_BAD_REQUEST, "Invalid value for position. Must be between 1-10000"); - if (in.limit < 1 || in.limit > 10000) - throw new RestException(SC_BAD_REQUEST, "Invalid value for limit. Must be between 1-10000"); - - // Create a connection and statement. - // If these fais, let the exception filter up as a 500 error. - Connection c = DriverManager.getConnection(connectionUrl); - c.setAutoCommit(false); - Statement st = c.createStatement(); - String sql = null; - - try { - for (String s : in.sql.split(";")) { - sql = s.trim(); - if (! sql.isEmpty()) { - Object o = null; - if (allowUpdates || (allowTempUpdates && ! sql.matches("(?:i)commit.*"))) { - if (st.execute(sql)) { - ResultSet rs = st.getResultSet(); - o = new ResultSetList(rs, in.pos, in.limit, includeRowNums); - } else { - o = st.getUpdateCount(); - } - } else { - ResultSet rs = st.executeQuery(sql); - o = new ResultSetList(rs, in.pos, in.limit, includeRowNums); - } - results.add(o); - } - } - if (allowUpdates) - c.commit(); - else if (allowTempUpdates) - c.rollback(); - } catch (SQLException e) { - c.rollback(); - throw new RestException(SC_BAD_REQUEST, "Invalid query: {0}", sql).initCause(e); - } finally { - c.close(); - } - - return results; - } - - /** The parsed form post */ - public static class PostInput { - public String sql; - public int pos = 1, limit = 100; - } -}
