├── .gitignore ├── .travis.yml ├── LICENSE ├── pom.xml ├── readme.md └── src ├── main └── java │ └── io │ └── dropwizard │ └── bundles │ └── assets │ ├── AssetServlet.java │ ├── AssetsBundleConfiguration.java │ ├── AssetsConfiguration.java │ ├── ConfiguredAssetsBundle.java │ └── UrlUtil.java └── test ├── java └── io │ └── dropwizard │ └── bundles │ └── assets │ ├── AssetServletTest.java │ ├── AssetsBundleTest.java │ └── AssetsConfigurationTest.java ├── more-resources └── assets │ └── example2.txt └── resources ├── assets ├── config.yml ├── encoded example.txt ├── example.txt ├── foo.bar ├── foo.m4a ├── foo.mp4 ├── index.htm └── some_directory │ ├── example.txt │ └── index.htm └── json ├── example.txt └── json only.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ Files 2 | .idea/ 3 | *.ipr 4 | *.iws 5 | *.iml 6 | 7 | # Eclipse Files 8 | .classpath 9 | .project 10 | 11 | # Build outputs 12 | target/ 13 | reports/ 14 | 15 | # OS hidden files 16 | .DS_Store 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | install: mvn install -Dgpg.skip -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012-2015 dropwizard-bundles.io and Bazaarvoice, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | io.dropwizard-bundles 7 | parent-pom 8 | 1.3.5 9 | 10 | 11 | dropwizard-configurable-assets-bundle 12 | 1.3.5-1-SNAPSHOT 13 | jar 14 | 15 | Dropwizard Configurable Asset Bundle 16 | An implementation of an AssetBundle for use in Dropwizard that allows user configuration. 17 | 18 | 19 | 20 | The Apache Software License, Version 2.0 21 | http://www.apache.org/licenses/LICENSE-2.0 22 | repo 23 | 24 | 25 | 26 | 27 | https://github.com/dropwizard-bundles/dropwizard-configurable-assets-bundle 28 | scm:git:https://github.com/dropwizard-bundles/dropwizard-configurable-assets-bundle 29 | scm:git:https://github.com/dropwizard-bundles/dropwizard-configurable-assets-bundle 30 | HEAD 31 | 32 | 33 | 34 | 35 | bbeck 36 | Brandon Beck 37 | http://github.com/bbeck/ 38 | 39 | 40 | nbauernfeind 41 | Nate Bauernfeind 42 | http://github.com/nbauernfeind/ 43 | 44 | 45 | 46 | 47 | 48 | 49 | src/test/resources 50 | 51 | 52 | src/test/more-resources 53 | 54 | 55 | 56 | 57 | 58 | 59 | io.dropwizard 60 | dropwizard-core 61 | 62 | 63 | io.dropwizard 64 | dropwizard-servlets 65 | 66 | 67 | junit 68 | junit 69 | test 70 | 71 | 72 | org.assertj 73 | assertj-core 74 | 1.7.1 75 | test 76 | 77 | 78 | org.eclipse.jetty 79 | jetty-http 80 | tests 81 | test 82 | 83 | 84 | org.eclipse.jetty 85 | jetty-servlet 86 | test 87 | 88 | 89 | org.eclipse.jetty 90 | jetty-servlet 91 | tests 92 | test 93 | 94 | 95 | org.mockito 96 | mockito-core 97 | test 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Configurable Assets Bundle for Dropwizard 2 | 3 | This GitHub repository contains a drop-in replacement for Yammer's `AssetsBundle` class that allows 4 | for a better developer experience. Developers can use the `ConfiguredAssetsBundle` class anywhere 5 | they would use a `AssetsBundle` in their Dropwizard applications and take advantage of the ability 6 | to specify redirects for URIs to that loads them from disk instead of the classpath. This allows 7 | developers to edit browser-interpreted files and reload them without needing to recompile source. 8 | 9 | [![Build Status](https://travis-ci.org/dropwizard-bundles/dropwizard-configurable-assets-bundle.png)](https://travis-ci.org/dropwizard-bundles/dropwizard-configurable-assets-bundle) 10 | 11 | ## Maven Setup 12 | 13 | ```xml 14 | 15 | io.dropwizard-bundles 16 | dropwizard-configurable-assets-bundle 17 | 1.0.5 18 | 19 | ``` 20 | 21 | ## Getting Started 22 | 23 | Implement the AssetsBundleConfiguration: 24 | ```java 25 | public class SampleConfiguration extends Configuration implements AssetsBundleConfiguration { 26 | @Valid 27 | @NotNull 28 | @JsonProperty 29 | private final AssetsConfiguration assets = AssetsConfiguration.builder().build(); 30 | 31 | @Override 32 | public AssetsConfiguration getAssetsConfiguration() { 33 | return assets; 34 | } 35 | } 36 | ``` 37 | 38 | Add the assets bundle: 39 | ```java 40 | public class SampleService extends Application { 41 | public static void main(String[] args) throws Exception { 42 | new SampleService().run(args); 43 | } 44 | 45 | @Override 46 | public void initialize(Bootstrap bootstrap) { 47 | // Map requests to /dashboard/${1} to be found in the class path at /assets/${1}. 48 | bootstrap.addBundle(new ConfiguredAssetsBundle("/assets/", "/dashboard/")); 49 | } 50 | 51 | @Override 52 | public void run(SampleConfiguration configuration, Environment environment) { 53 | ... 54 | } 55 | } 56 | ``` 57 | 58 | A sample local development config: 59 | ```yml 60 | assets: 61 | overrides: 62 | # Override requests to /dashboard/${1} to instead look in 63 | # ${working directory}/src/main/resources/assets/${1} 64 | /dashboard: src/main/resources/assets/ 65 | ``` 66 | 67 | You can override multiple external folders with a single configuration in a following way: 68 | ```yml 69 | assets: 70 | overrides: 71 | /dashboard/assets: /some/absolute/path/with/assets/ 72 | /dashboard/images: /some/different/absolute/path/with/images 73 | ``` 74 | 75 | Instead of defining the resource path to uri path mappings in java code, they also can be specified in the configuration file. 76 | ```java 77 | public class SampleService extends Application { 78 | ... 79 | 80 | @Override 81 | public void initialize(Bootstrap bootstrap) { 82 | bootstrap.addBundle(new ConfiguredAssetsBundle()); 83 | } 84 | 85 | @Override 86 | public void run(SampleConfiguration configuration, Environment environment) { 87 | ... 88 | } 89 | } 90 | ``` 91 | 92 | ```yml 93 | assets: 94 | mappings: 95 | /assets: /dashboard 96 | overrides: 97 | /dashboard/assets: /some/absolute/path/with/assets/ 98 | /dashboard/images: /some/different/absolute/path/with/images 99 | ``` 100 | 101 | ## Add Mime Types 102 | 103 | Since 0.8, Dropwizard allows you to add new mimetypes directly to the application context. 104 | 105 | ```java 106 | public class SampleService extends Application { 107 | ... 108 | 109 | @Override 110 | public void run(SampleConfiguration configuration, Environment environment) { 111 | environment 112 | .getApplicationContext() 113 | .getMimeTypes() 114 | .addMimeMapping("mp4", "video/mp4"); 115 | } 116 | } 117 | ``` 118 | 119 | However if you want to override a pre-existing mime type, or add them dynamically, you can do so 120 | with your assets configuration. 121 | 122 | ```yml 123 | assets: 124 | mimeTypes: 125 | woff: application/font-woff 126 | ``` 127 | 128 | ## Multiple URI Mappings 129 | 130 | You can map different folders to multiple top-level directories if you wish. 131 | 132 | Either in java code 133 | ```java 134 | public class SampleService extends Application { 135 | ... 136 | 137 | @Override 138 | public void initialize(Bootstrap bootstrap) { 139 | bootstrap.addBundle(new ConfiguredAssetsBundle( 140 | ImmutableMap.builder() 141 | .put("/assets/", "/dashboard/") 142 | .put("/data/", "/static-data/") 143 | .build() 144 | )); 145 | } 146 | } 147 | ``` 148 | 149 | or either in the configuration file 150 | ```yml 151 | assets: 152 | mappings: 153 | /assets: /dashboard 154 | /data: /static-data 155 | overrides: 156 | ... 157 | ``` 158 | -------------------------------------------------------------------------------- /src/main/java/io/dropwizard/bundles/assets/AssetServlet.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | import com.google.common.base.CharMatcher; 4 | import com.google.common.base.Joiner; 5 | import com.google.common.base.Splitter; 6 | import com.google.common.cache.CacheBuilder; 7 | import com.google.common.cache.CacheBuilderSpec; 8 | import com.google.common.cache.CacheLoader; 9 | import com.google.common.cache.LoadingCache; 10 | import com.google.common.cache.Weigher; 11 | import com.google.common.collect.ImmutableList; 12 | import com.google.common.collect.Maps; 13 | import com.google.common.hash.Hashing; 14 | import com.google.common.io.Files; 15 | import com.google.common.io.Resources; 16 | import com.google.common.net.HttpHeaders; 17 | import com.google.common.net.MediaType; 18 | import io.dropwizard.servlets.assets.ByteRange; 19 | import io.dropwizard.servlets.assets.ResourceURL; 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.net.URL; 23 | import java.nio.charset.Charset; 24 | import java.util.List; 25 | import java.util.Map; 26 | import javax.servlet.ServletException; 27 | import javax.servlet.ServletOutputStream; 28 | import javax.servlet.http.HttpServlet; 29 | import javax.servlet.http.HttpServletRequest; 30 | import javax.servlet.http.HttpServletResponse; 31 | import org.eclipse.jetty.http.MimeTypes; 32 | 33 | /** 34 | * Servlet responsible for serving assets to the caller. This is basically completely stolen from 35 | * {@link io.dropwizard.servlets.assets.AssetServlet} with the exception of allowing for override 36 | * options. 37 | * 38 | * @see io.dropwizard.servlets.assets.AssetServlet 39 | */ 40 | public class AssetServlet extends HttpServlet { 41 | private static final long serialVersionUID = 6393345594784987908L; 42 | private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.HTML_UTF_8; 43 | private static final CharMatcher SLASHES = CharMatcher.is('/'); 44 | 45 | private final transient CacheBuilderSpec cacheSpec; 46 | private final transient LoadingCache cache; 47 | private final transient MimeTypes mimeTypes; 48 | 49 | private Charset defaultCharset; 50 | 51 | private String cacheControlHeader = null; 52 | 53 | /** 54 | * Creates a new {@code AssetServlet} that serves static assets loaded from {@code resourceURL} 55 | * (typically a file: or jar: URL). The assets are served at URIs rooted at {@code uriPath}. For 56 | * example, given a {@code resourceURL} of {@code "file:/data/assets"} and a {@code uriPath} of 57 | * {@code "/js"}, an {@code AssetServlet} would serve the contents of {@code 58 | * /data/assets/example.js} in response to a request for {@code /js/example.js}. If a directory 59 | * is requested and {@code indexFile} is defined, then {@code AssetServlet} will attempt to 60 | * serve a file with that name in that directory. If a directory is requested and {@code 61 | * indexFile} is null, it will serve a 404. 62 | * 63 | * @param resourcePathToUriPathMapping A mapping from base URL's from which assets are loaded to 64 | * the URI path fragment in which the requests for that asset 65 | * are rooted 66 | * @param indexFile the filename to use when directories are requested, or null 67 | * to serve no indexes 68 | * @param defaultCharset the default character set 69 | * @param spec the CacheBuilderSpec to use 70 | * @param overrides the path overrides 71 | * @param mimeTypes the mimeType overrides 72 | */ 73 | public AssetServlet(Iterable> resourcePathToUriPathMapping, 74 | String indexFile, 75 | Charset defaultCharset, 76 | CacheBuilderSpec spec, 77 | Iterable> overrides, 78 | Iterable> mimeTypes) { 79 | this.defaultCharset = defaultCharset; 80 | AssetLoader loader = new AssetLoader(resourcePathToUriPathMapping, indexFile, overrides); 81 | 82 | CacheBuilder cacheBuilder = CacheBuilder.from(spec); 83 | // Don't add the weigher if we are using maximumSize instead of maximumWeight. 84 | if (spec.toParsableString().contains("maximumWeight=")) { 85 | cacheBuilder.weigher(new AssetSizeWeigher()); 86 | } 87 | this.cache = cacheBuilder.build(loader); 88 | 89 | this.cacheSpec = spec; 90 | this.mimeTypes = new MimeTypes(); 91 | this.setMimeTypes(mimeTypes); 92 | } 93 | 94 | public void setCacheControlHeader(String cacheControlHeader) { 95 | this.cacheControlHeader = cacheControlHeader; 96 | } 97 | 98 | public String getCacheControlHeader() { 99 | return cacheControlHeader; 100 | } 101 | 102 | /** 103 | * Adds mimeType overrides. 104 | * 105 | * @param mimeTypes the mimeType override mapping 106 | */ 107 | public void setMimeTypes(Iterable> mimeTypes) { 108 | for (Map.Entry mime : mimeTypes) { 109 | this.mimeTypes.addMimeMapping(mime.getKey(), mime.getValue()); 110 | } 111 | } 112 | 113 | public MimeTypes getMimeTypes() { 114 | return mimeTypes; 115 | } 116 | 117 | public void setDefaultCharset(Charset defaultCharset) { 118 | this.defaultCharset = defaultCharset; 119 | } 120 | 121 | public Charset getDefaultCharset() { 122 | return this.defaultCharset; 123 | } 124 | 125 | public CacheBuilderSpec getCacheSpec() { 126 | return cacheSpec; 127 | } 128 | 129 | @Override 130 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) 131 | throws ServletException, IOException { 132 | try { 133 | final StringBuilder builder = new StringBuilder(req.getServletPath()); 134 | if (req.getPathInfo() != null) { 135 | builder.append(req.getPathInfo()); 136 | } 137 | final Asset cachedAsset = cache.getUnchecked(builder.toString()); 138 | if (cachedAsset == null) { 139 | resp.sendError(HttpServletResponse.SC_NOT_FOUND); 140 | return; 141 | } 142 | 143 | if (isCachedClientSide(req, cachedAsset)) { 144 | resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); 145 | return; 146 | } 147 | 148 | final String rangeHeader = req.getHeader(HttpHeaders.RANGE); 149 | 150 | final int resourceLength = cachedAsset.getResource().length; 151 | ImmutableList ranges = ImmutableList.of(); 152 | 153 | boolean usingRanges = false; 154 | // Support for HTTP Byte Ranges 155 | // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 156 | if (rangeHeader != null) { 157 | 158 | final String ifRange = req.getHeader(HttpHeaders.IF_RANGE); 159 | 160 | if (ifRange == null || cachedAsset.getETag().equals(ifRange)) { 161 | 162 | try { 163 | ranges = parseRangeHeader(rangeHeader, resourceLength); 164 | } catch (NumberFormatException e) { 165 | resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); 166 | return; 167 | } 168 | 169 | if (ranges.isEmpty()) { 170 | resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); 171 | return; 172 | } 173 | 174 | resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); 175 | usingRanges = true; 176 | 177 | resp.addHeader(HttpHeaders.CONTENT_RANGE, "bytes " 178 | + Joiner.on(",").join(ranges) + "/" + resourceLength); 179 | } 180 | } 181 | 182 | resp.setDateHeader(HttpHeaders.LAST_MODIFIED, cachedAsset.getLastModifiedTime()); 183 | resp.setHeader(HttpHeaders.ETAG, cachedAsset.getETag()); 184 | if (cacheControlHeader != null) { 185 | resp.setHeader(HttpHeaders.CACHE_CONTROL, cacheControlHeader); 186 | } 187 | 188 | 189 | String mimeTypeOfExtension = mimeTypes.getMimeByExtension(req.getRequestURI()); 190 | if (mimeTypeOfExtension == null) { 191 | mimeTypeOfExtension = req.getServletContext().getMimeType(req.getRequestURI()); 192 | } 193 | 194 | MediaType mediaType = DEFAULT_MEDIA_TYPE; 195 | 196 | if (mimeTypeOfExtension != null) { 197 | try { 198 | mediaType = MediaType.parse(mimeTypeOfExtension); 199 | if (defaultCharset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) { 200 | mediaType = mediaType.withCharset(defaultCharset); 201 | } 202 | } catch (IllegalArgumentException ignored) { 203 | // Ignored 204 | } 205 | } 206 | 207 | if (mediaType.is(MediaType.ANY_VIDEO_TYPE) 208 | || mediaType.is(MediaType.ANY_AUDIO_TYPE) || usingRanges) { 209 | resp.addHeader(HttpHeaders.ACCEPT_RANGES, "bytes"); 210 | } 211 | 212 | resp.setContentType(mediaType.type() + '/' + mediaType.subtype()); 213 | 214 | if (mediaType.charset().isPresent()) { 215 | resp.setCharacterEncoding(mediaType.charset().get().toString()); 216 | } 217 | 218 | try (ServletOutputStream output = resp.getOutputStream()) { 219 | if (usingRanges) { 220 | for (final ByteRange range : ranges) { 221 | output.write(cachedAsset.getResource(), range.getStart(), 222 | range.getEnd() - range.getStart() + 1); 223 | } 224 | } else { 225 | output.write(cachedAsset.getResource()); 226 | } 227 | } 228 | } catch (RuntimeException ignored) { 229 | resp.sendError(HttpServletResponse.SC_NOT_FOUND); 230 | } 231 | } 232 | 233 | private boolean isCachedClientSide(HttpServletRequest req, Asset cachedAsset) { 234 | return cachedAsset.getETag().equals(req.getHeader(HttpHeaders.IF_NONE_MATCH)) 235 | || (req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE) 236 | >= cachedAsset.getLastModifiedTime()); 237 | } 238 | 239 | /** 240 | * Parses a given Range header for one or more byte ranges. 241 | * 242 | * @param rangeHeader Range header to parse 243 | * @param resourceLength Length of the resource in bytes 244 | * @return List of parsed ranges 245 | */ 246 | private ImmutableList parseRangeHeader(final String rangeHeader, 247 | final int resourceLength) { 248 | final ImmutableList.Builder builder = ImmutableList.builder(); 249 | if (rangeHeader.contains("=")) { 250 | final String[] parts = rangeHeader.split("="); 251 | if (parts.length > 1) { 252 | final List ranges = Splitter.on(",").trimResults().splitToList(parts[1]); 253 | for (final String range : ranges) { 254 | builder.add(ByteRange.parse(range, resourceLength)); 255 | } 256 | } 257 | } 258 | return builder.build(); 259 | } 260 | 261 | private static class AssetLoader extends CacheLoader { 262 | private final String indexFilename; 263 | private final Map resourcePathToUriMappings = Maps.newHashMap(); 264 | private final Iterable> overrides; 265 | 266 | private AssetLoader(Iterable> resourcePathToUriMappings, 267 | String indexFilename, 268 | Iterable> overrides) { 269 | for (Map.Entry mapping : resourcePathToUriMappings) { 270 | final String trimmedPath = SLASHES.trimFrom(mapping.getKey()); 271 | String resourcePath = trimmedPath.isEmpty() ? trimmedPath : trimmedPath + '/'; 272 | final String trimmedUri = SLASHES.trimTrailingFrom(mapping.getValue()); 273 | String uriPath = trimmedUri.isEmpty() ? "/" : trimmedUri; 274 | 275 | if (this.resourcePathToUriMappings.containsKey(resourcePath)) { 276 | throw new IllegalArgumentException("ResourcePathToUriMappings contains multiple mappings " 277 | + "for " + resourcePath); 278 | } 279 | this.resourcePathToUriMappings.put(resourcePath, uriPath); 280 | } 281 | 282 | this.indexFilename = indexFilename; 283 | this.overrides = overrides; 284 | } 285 | 286 | @Override 287 | public Asset load(String key) throws Exception { 288 | for (Map.Entry mapping : resourcePathToUriMappings.entrySet()) { 289 | if (!key.startsWith(mapping.getValue())) { 290 | continue; 291 | } 292 | 293 | Asset asset = loadOverride(key); 294 | if (asset != null) { 295 | return asset; 296 | } 297 | 298 | final String requestedResourcePath = 299 | SLASHES.trimFrom(key.substring(mapping.getValue().length())); 300 | final String absolutePath = SLASHES.trimFrom(mapping.getKey() + requestedResourcePath); 301 | 302 | try { 303 | URL requestedResourceUrl = 304 | UrlUtil.switchFromZipToJarProtocolIfNeeded(Resources.getResource(absolutePath)); 305 | if (ResourceURL.isDirectory(requestedResourceUrl)) { 306 | if (indexFilename != null) { 307 | requestedResourceUrl = Resources.getResource(absolutePath + '/' + indexFilename); 308 | requestedResourceUrl = 309 | UrlUtil.switchFromZipToJarProtocolIfNeeded(requestedResourceUrl); 310 | } else { 311 | // resource mapped to directory but no index file defined 312 | continue; 313 | } 314 | } 315 | 316 | long lastModified = ResourceURL.getLastModified(requestedResourceUrl); 317 | if (lastModified < 1) { 318 | // Something went wrong trying to get the last modified time: just use the current time 319 | lastModified = System.currentTimeMillis(); 320 | } 321 | 322 | // zero out the millis; the If-Modified-Since header will not have them 323 | lastModified = (lastModified / 1000) * 1000; 324 | return new StaticAsset(Resources.toByteArray(requestedResourceUrl), lastModified); 325 | } catch (IllegalArgumentException expected) { 326 | // Try another Mapping. 327 | } 328 | } 329 | 330 | return null; 331 | } 332 | 333 | private Asset loadOverride(String key) throws Exception { 334 | // TODO: Support prefix matches only for directories 335 | for (Map.Entry override : overrides) { 336 | File file = null; 337 | if (override.getKey().equals(key)) { 338 | // We have an exact match 339 | file = new File(override.getValue()); 340 | } else if (key.startsWith(override.getKey())) { 341 | // This resource is in a mapped subdirectory 342 | file = new File(override.getValue(), key.substring(override.getKey().length())); 343 | } 344 | 345 | if (file == null || !file.exists()) { 346 | continue; 347 | } 348 | 349 | if (file.isDirectory()) { 350 | file = new File(file, indexFilename); 351 | } 352 | 353 | if (file.exists()) { 354 | return new FileSystemAsset(file); 355 | } 356 | } 357 | 358 | return null; 359 | } 360 | } 361 | 362 | private static interface Asset { 363 | byte[] getResource(); 364 | 365 | String getETag(); 366 | 367 | long getLastModifiedTime(); 368 | } 369 | 370 | /** 371 | * Weigh an asset according to the number of bytes it contains. 372 | */ 373 | private static final class AssetSizeWeigher implements Weigher { 374 | @Override 375 | public int weigh(String key, Asset asset) { 376 | return asset.getResource().length; 377 | } 378 | } 379 | 380 | /** 381 | * An asset implementation backed by the file-system. If the backing file changes on disk, then 382 | * this asset will automatically reload its contents from disk. 383 | */ 384 | private static class FileSystemAsset implements Asset { 385 | private final File file; 386 | private byte[] bytes; 387 | private String etag; 388 | private long lastModifiedTime; 389 | 390 | public FileSystemAsset(File file) { 391 | this.file = file; 392 | refresh(); 393 | } 394 | 395 | @Override 396 | public byte[] getResource() { 397 | maybeRefresh(); 398 | return bytes; 399 | } 400 | 401 | @Override 402 | public String getETag() { 403 | maybeRefresh(); 404 | return etag; 405 | } 406 | 407 | @Override 408 | public long getLastModifiedTime() { 409 | maybeRefresh(); 410 | return (lastModifiedTime / 1000) * 1000; 411 | } 412 | 413 | private synchronized void maybeRefresh() { 414 | if (lastModifiedTime != file.lastModified()) { 415 | refresh(); 416 | } 417 | } 418 | 419 | private synchronized void refresh() { 420 | try { 421 | byte[] newBytes = Files.toByteArray(file); 422 | String newETag = Hashing.murmur3_128().hashBytes(newBytes).toString(); 423 | 424 | bytes = newBytes; 425 | etag = '"' + newETag + '"'; 426 | lastModifiedTime = file.lastModified(); 427 | } catch (IOException e) { 428 | // Ignored, don't update anything 429 | } 430 | } 431 | } 432 | 433 | /** 434 | * A static asset implementation. This implementation just encapsulates the raw bytes of an 435 | * asset (presumably loaded from the classpath) and will never change. 436 | */ 437 | private static class StaticAsset implements Asset { 438 | private final byte[] resource; 439 | private final String etag; 440 | private final long lastModifiedTime; 441 | 442 | private StaticAsset(byte[] resource, long lastModifiedTime) { 443 | this.resource = resource; 444 | this.etag = '"' + Hashing.murmur3_128().hashBytes(resource).toString() + '"'; 445 | this.lastModifiedTime = lastModifiedTime; 446 | } 447 | 448 | public byte[] getResource() { 449 | return resource; 450 | } 451 | 452 | public String getETag() { 453 | return etag; 454 | } 455 | 456 | public long getLastModifiedTime() { 457 | return lastModifiedTime; 458 | } 459 | } 460 | 461 | 462 | } 463 | -------------------------------------------------------------------------------- /src/main/java/io/dropwizard/bundles/assets/AssetsBundleConfiguration.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | public interface AssetsBundleConfiguration { 4 | /** 5 | * Get the configuration for how the assets should be served. 6 | * 7 | * @return The configuration. 8 | */ 9 | AssetsConfiguration getAssetsConfiguration(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/io/dropwizard/bundles/assets/AssetsConfiguration.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 5 | import com.google.common.base.Preconditions; 6 | import com.google.common.collect.ImmutableMap; 7 | import com.google.common.collect.Maps; 8 | import java.util.Collections; 9 | import java.util.Map; 10 | import javax.validation.constraints.NotNull; 11 | 12 | @JsonDeserialize(builder = AssetsConfiguration.Builder.class) 13 | public class AssetsConfiguration { 14 | public static final String SLASH = "/"; 15 | 16 | private Map mappings = Maps.newHashMap(); 17 | 18 | /** 19 | * Initialize cacheSpec to null so that whatever may be specified by code is able to be 20 | * by configuration. If null the default cache spec of "maximumSize=100" will be used. 21 | * 22 | * @see ConfiguredAssetsBundle#DEFAULT_CACHE_SPEC 23 | */ 24 | 25 | private String cacheSpec = null; 26 | 27 | @NotNull 28 | private Map overrides = Maps.newHashMap(); 29 | 30 | @NotNull 31 | private Map mimeTypes = Maps.newHashMap(); 32 | 33 | private String cacheControlHeader = null; 34 | 35 | private Map resourcePathToUriMappings; 36 | 37 | private AssetsConfiguration( 38 | String cacheControlHeader, 39 | String cacheSpec, 40 | Map mappings, 41 | Map mimeTypes, 42 | Map overrides) { 43 | 44 | this.cacheControlHeader = cacheControlHeader; 45 | this.cacheSpec = cacheSpec; 46 | this.mappings = Collections.unmodifiableMap(mappings); 47 | this.mimeTypes = Collections.unmodifiableMap(mimeTypes); 48 | this.overrides = Collections.unmodifiableMap(overrides); 49 | } 50 | 51 | /** 52 | * A series of mappings from resource paths (in the classpath) 53 | * to the uri path that hosts the resource 54 | * @return The resourcePathToUriMappings. 55 | */ 56 | public Map getResourcePathToUriMappings() { 57 | if (resourcePathToUriMappings == null) { 58 | ImmutableMap.Builder mapBuilder = ImmutableMap.builder(); 59 | // Ensure that resourcePath and uri ends with a '/' 60 | for (Map.Entry mapping : mappings().entrySet()) { 61 | mapBuilder 62 | .put(ensureEndsWithSlash(mapping.getKey()), ensureEndsWithSlash(mapping.getValue())); 63 | } 64 | resourcePathToUriMappings = mapBuilder.build(); 65 | } 66 | return resourcePathToUriMappings; 67 | } 68 | 69 | private String ensureEndsWithSlash(String value) { 70 | return value != null ? (value.endsWith(SLASH) ? value : value + SLASH) : SLASH; 71 | } 72 | 73 | protected Map mappings() { 74 | return mappings; 75 | } 76 | 77 | /** 78 | * The caching specification for how to memoize assets. 79 | * 80 | * @return The cacheSpec. 81 | */ 82 | public String getCacheSpec() { 83 | return cacheSpec; 84 | } 85 | 86 | public Map getOverrides() { 87 | return Collections.unmodifiableMap(overrides); 88 | } 89 | 90 | public Map getMimeTypes() { 91 | return Collections.unmodifiableMap(mimeTypes); 92 | } 93 | 94 | public String getCacheControlHeader() { 95 | return cacheControlHeader; 96 | } 97 | 98 | public static Builder builder() { 99 | return new Builder(); 100 | } 101 | 102 | public static final class Builder { 103 | @JsonProperty 104 | private String cacheControlHeader; 105 | @JsonProperty 106 | private String cacheSpec; 107 | @JsonProperty 108 | private Map mappings = Maps.newHashMap(); 109 | @JsonProperty 110 | private Map mimeTypes = Maps.newHashMap(); 111 | @JsonProperty 112 | private Map overrides = Maps.newHashMap(); 113 | 114 | private Builder() {} 115 | 116 | public Builder cacheControlHeader(String cacheControlHeader) { 117 | this.cacheControlHeader = cacheControlHeader; 118 | return this; 119 | } 120 | 121 | public Builder cacheSpec(String cacheSpec) { 122 | this.cacheSpec = cacheSpec; 123 | return this; 124 | } 125 | 126 | public Builder mappings(Map mappings) { 127 | this.mappings = Preconditions.checkNotNull(mappings); 128 | return this; 129 | } 130 | 131 | public Builder mimeTypes(Map mimeTypes) { 132 | this.mimeTypes = Preconditions.checkNotNull(mimeTypes); 133 | return this; 134 | } 135 | 136 | public Builder overrides(Map overrides) { 137 | this.overrides = Preconditions.checkNotNull(overrides); 138 | return this; 139 | } 140 | 141 | public AssetsConfiguration build() { 142 | return new AssetsConfiguration(cacheControlHeader, cacheSpec, mappings, mimeTypes, overrides); 143 | } 144 | } 145 | 146 | } 147 | -------------------------------------------------------------------------------- /src/main/java/io/dropwizard/bundles/assets/ConfiguredAssetsBundle.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.cache.CacheBuilderSpec; 5 | import com.google.common.collect.ImmutableMap; 6 | import com.google.common.collect.Iterables; 7 | import io.dropwizard.ConfiguredBundle; 8 | import io.dropwizard.setup.Bootstrap; 9 | import io.dropwizard.setup.Environment; 10 | 11 | import java.util.Map; 12 | 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | import static com.google.common.base.Preconditions.checkArgument; 17 | 18 | /** 19 | * An assets bundle (like io.dropwizard.assets.AssetsBundle) that utilizes configuration to provide 20 | * the ability to override how assets are loaded and cached. Specifying an override is useful 21 | * during the development phase to allow assets to be loaded directly out of source directories 22 | * instead of the classpath and to force them to not be cached by the browser or the server. This 23 | * allows developers to edit an asset, save and then immediately refresh the web browser and see the 24 | * updated assets. No compilation or copy steps are necessary. 25 | */ 26 | public class ConfiguredAssetsBundle implements ConfiguredBundle { 27 | private static final Logger LOGGER = LoggerFactory.getLogger(ConfiguredAssetsBundle.class); 28 | 29 | private static final String DEFAULT_PATH = "/assets"; 30 | public static final CacheBuilderSpec DEFAULT_CACHE_SPEC = 31 | CacheBuilderSpec.parse("maximumSize=100"); 32 | private static final String DEFAULT_INDEX_FILE = "index.htm"; 33 | private static final String DEFAULT_SERVLET_MAPPING_NAME = "assets"; 34 | 35 | private final Iterable> resourcePathToUriMappings; 36 | private final CacheBuilderSpec cacheBuilderSpec; 37 | private final String indexFile; 38 | private final String assetsName; 39 | 40 | /** 41 | * Creates a new {@link ConfiguredAssetsBundle} which serves up static assets from 42 | * {@code src/main/resources/assets/*} as {@code /assets/*}. 43 | * 44 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(String, String, String, String, 45 | * CacheBuilderSpec) 46 | */ 47 | public ConfiguredAssetsBundle() { 48 | this(DEFAULT_PATH); 49 | } 50 | 51 | /** 52 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 53 | * static files located in {@code src/main/resources/${path}} as {@code /${path}}. For example, 54 | * given a {@code path} of {@code "/assets"}, {@code src/main/resources/assets/example.js} would 55 | * be served up from {@code /assets/example.js}. 56 | * 57 | * @param path the classpath and URI root of the static asset files 58 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(String, String, String, String, 59 | * CacheBuilderSpec) 60 | */ 61 | public ConfiguredAssetsBundle(String path) { 62 | this(path, path, DEFAULT_INDEX_FILE, DEFAULT_SERVLET_MAPPING_NAME, DEFAULT_CACHE_SPEC); 63 | } 64 | 65 | /** 66 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 67 | * static files located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. For 68 | * example, given a {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 69 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 70 | * 71 | * @param resourcePath the resource path (in the classpath) of the static asset files 72 | * @param uriPath the uri path for the static asset files 73 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(String, String, String, String, 74 | * CacheBuilderSpec) 75 | */ 76 | public ConfiguredAssetsBundle(String resourcePath, String uriPath) { 77 | this(resourcePath, uriPath, DEFAULT_INDEX_FILE, DEFAULT_SERVLET_MAPPING_NAME, 78 | DEFAULT_CACHE_SPEC); 79 | } 80 | 81 | /** 82 | * Creates a new AssetsBundle which will configure the service to serve the static files 83 | * located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. If no file name 84 | * is in ${uriPath}, ${indexFile} is appended before serving. For example, given a 85 | * {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 86 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 87 | * 88 | * @param resourcePath the resource path (in the classpath) of the static asset files 89 | * @param uriPath the uri path for the static asset files 90 | * @param indexFile the name of the index file to use 91 | */ 92 | public ConfiguredAssetsBundle(String resourcePath, String uriPath, String indexFile) { 93 | this(resourcePath, uriPath, indexFile, DEFAULT_SERVLET_MAPPING_NAME, DEFAULT_CACHE_SPEC); 94 | } 95 | 96 | /** 97 | * Creates a new AssetsBundle which will configure the service to serve the static files 98 | * located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. If no file name 99 | * is in ${uriPath}, ${indexFile} is appended before serving. For example, given a 100 | * {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 101 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 102 | * 103 | * @param resourcePath the resource path (in the classpath) of the static asset files 104 | * @param uriPath the uri path for the static asset files 105 | * @param indexFile the name of the index file to use 106 | * @param assetsName the name of servlet mapping used for this assets bundle 107 | */ 108 | public ConfiguredAssetsBundle(String resourcePath, String uriPath, String indexFile, 109 | String assetsName) { 110 | this(resourcePath, uriPath, indexFile, assetsName, DEFAULT_CACHE_SPEC); 111 | } 112 | 113 | /** 114 | * Creates a new {@link ConfiguredAssetsBundle} which serves up static assets from 115 | * {@code src/main/resources/assets/*} as {@code /assets/*}. 116 | * 117 | * @param cacheBuilderSpec the spec for the cache builder 118 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(Map, String, String, CacheBuilderSpec) 119 | */ 120 | public ConfiguredAssetsBundle(CacheBuilderSpec cacheBuilderSpec) { 121 | this(DEFAULT_PATH, DEFAULT_PATH, DEFAULT_INDEX_FILE, DEFAULT_SERVLET_MAPPING_NAME, 122 | cacheBuilderSpec); 123 | } 124 | 125 | /** 126 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 127 | * static files located in {@code src/main/resources/${path}} as {@code /${path}}. For example, 128 | * given a {@code path} of {@code "/assets"}, {@code src/main/resources/assets/example.js} would 129 | * be served up from {@code /assets/example.js}. 130 | * 131 | * @param resourcePath the resource path (in the classpath) of the static asset files 132 | * @param cacheBuilderSpec the spec for the cache builder 133 | */ 134 | public ConfiguredAssetsBundle(String resourcePath, CacheBuilderSpec cacheBuilderSpec) { 135 | this(resourcePath, resourcePath, DEFAULT_INDEX_FILE, DEFAULT_SERVLET_MAPPING_NAME, 136 | cacheBuilderSpec); 137 | } 138 | 139 | /** 140 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 141 | * static files located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. For 142 | * example, given a {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 143 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 144 | * 145 | * @param resourcePath the resource path (in the classpath) of the static asset files 146 | * @param uriPath the uri path for the static asset files 147 | * @param cacheBuilderSpec the spec for the cache builder 148 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(Map, String, String, CacheBuilderSpec) 149 | */ 150 | public ConfiguredAssetsBundle(String resourcePath, String uriPath, 151 | CacheBuilderSpec cacheBuilderSpec) { 152 | this(resourcePath, uriPath, DEFAULT_INDEX_FILE, DEFAULT_SERVLET_MAPPING_NAME, cacheBuilderSpec); 153 | } 154 | 155 | /** 156 | * Creates a new AssetsBundle which will configure the service to serve the static files 157 | * located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. If no file name 158 | * is in ${uriPath}, ${indexFile} is appended before serving. For example, given a 159 | * {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 160 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 161 | * 162 | * @param resourcePath the resource path (in the classpath) of the static asset files 163 | * @param uriPath the uri path for the static asset files 164 | * @param indexFile the name of the index file to use 165 | * @param cacheBuilderSpec the spec for the cache builder 166 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(Map, String, String, CacheBuilderSpec) 167 | */ 168 | public ConfiguredAssetsBundle(String resourcePath, String uriPath, String indexFile, 169 | CacheBuilderSpec cacheBuilderSpec) { 170 | this(resourcePath, uriPath, indexFile, DEFAULT_SERVLET_MAPPING_NAME, cacheBuilderSpec); 171 | } 172 | 173 | /** 174 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 175 | * static files located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. For 176 | * example, given a {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 177 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 178 | * 179 | * @param resourcePath the resource path (in the classpath) of the static asset files 180 | * @param cacheBuilderSpec the spec for the cache builder 181 | * @param uriPath the uri path for the static asset files 182 | * @param indexFile the name of the index file to use 183 | * @param assetsName the name of servlet mapping used for this assets bundle 184 | */ 185 | public ConfiguredAssetsBundle(String resourcePath, String uriPath, String indexFile, 186 | String assetsName, CacheBuilderSpec cacheBuilderSpec) { 187 | this(ImmutableMap.builder().put(resourcePath, uriPath).build(), indexFile, 188 | assetsName, cacheBuilderSpec); 189 | } 190 | 191 | /** 192 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 193 | * static files located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. For 194 | * example, given a {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 195 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 196 | * 197 | * @param resourcePathToUriMappings a series of mappings from resource paths (in the classpath) 198 | * to the uri path that hosts the resource 199 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(String, String, String, String, 200 | * CacheBuilderSpec) 201 | */ 202 | public ConfiguredAssetsBundle(Map resourcePathToUriMappings) { 203 | this(resourcePathToUriMappings, DEFAULT_INDEX_FILE, DEFAULT_SERVLET_MAPPING_NAME, 204 | DEFAULT_CACHE_SPEC); 205 | } 206 | 207 | /** 208 | * Creates a new AssetsBundle which will configure the service to serve the static files 209 | * located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. If no file name 210 | * is in ${uriPath}, ${indexFile} is appended before serving. For example, given a 211 | * {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 212 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 213 | * 214 | * @param resourcePathToUriMappings a series of mappings from resource paths (in the classpath) 215 | * to the uri path that hosts the resource 216 | * @param indexFile the name of the index file to use 217 | */ 218 | public ConfiguredAssetsBundle(Map resourcePathToUriMappings, String indexFile) { 219 | this(resourcePathToUriMappings, indexFile, DEFAULT_SERVLET_MAPPING_NAME, DEFAULT_CACHE_SPEC); 220 | } 221 | 222 | /** 223 | * Creates a new AssetsBundle which will configure the service to serve the static files 224 | * located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. If no file name 225 | * is in ${uriPath}, ${indexFile} is appended before serving. For example, given a 226 | * {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 227 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 228 | * 229 | * @param resourcePathToUriMappings a series of mappings from resource paths (in the classpath) 230 | * to the uri path that hosts the resource 231 | * @param indexFile the name of the index file to use 232 | * @param assetsName the name of servlet mapping used for this assets bundle 233 | */ 234 | public ConfiguredAssetsBundle(Map resourcePathToUriMappings, String indexFile, 235 | String assetsName) { 236 | this(resourcePathToUriMappings, indexFile, assetsName, DEFAULT_CACHE_SPEC); 237 | } 238 | 239 | /** 240 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 241 | * static files located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. For 242 | * example, given a {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 243 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 244 | * 245 | * @param resourcePathToUriMappings a series of mappings from resource paths (in the classpath) 246 | * to the uri path that hosts the resource 247 | * @param cacheBuilderSpec the spec for the cache builder 248 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(Map, String, String, CacheBuilderSpec) 249 | */ 250 | public ConfiguredAssetsBundle(Map resourcePathToUriMappings, 251 | CacheBuilderSpec cacheBuilderSpec) { 252 | this(resourcePathToUriMappings, DEFAULT_INDEX_FILE, DEFAULT_SERVLET_MAPPING_NAME, 253 | cacheBuilderSpec); 254 | } 255 | 256 | /** 257 | * Creates a new AssetsBundle which will configure the service to serve the static files 258 | * located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. If no file name 259 | * is in ${uriPath}, ${indexFile} is appended before serving. For example, given a 260 | * {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 261 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 262 | * 263 | * @param resourcePathToUriMappings a series of mappings from resource paths (in the classpath) 264 | * to the uri path that hosts the resource 265 | * @param indexFile the name of the index file to use 266 | * @param cacheBuilderSpec the spec for the cache builder 267 | * @see ConfiguredAssetsBundle#ConfiguredAssetsBundle(Map, String, String, 268 | * CacheBuilderSpec) 269 | */ 270 | public ConfiguredAssetsBundle(Map resourcePathToUriMappings, String indexFile, 271 | CacheBuilderSpec cacheBuilderSpec) { 272 | this(resourcePathToUriMappings, indexFile, DEFAULT_SERVLET_MAPPING_NAME, cacheBuilderSpec); 273 | } 274 | 275 | /** 276 | * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the 277 | * static files located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. For 278 | * example, given a {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"}, 279 | * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}. 280 | * 281 | * @param resourcePathToUriMappings a series of mappings from resource paths (in the classpath) 282 | * to the uri path that hosts the resource 283 | * @param cacheBuilderSpec the spec for the cache builder 284 | * @param indexFile the name of the index file to use 285 | * @param assetsName the name of servlet mapping used for this assets bundle 286 | */ 287 | public ConfiguredAssetsBundle(Map resourcePathToUriMappings, String indexFile, 288 | String assetsName, CacheBuilderSpec cacheBuilderSpec) { 289 | for (Map.Entry mapping : resourcePathToUriMappings.entrySet()) { 290 | String resourcePath = mapping.getKey(); 291 | checkArgument(resourcePath.startsWith("/"), "%s is not an absolute path", resourcePath); 292 | checkArgument(!"/".equals(resourcePath), "%s is the classpath root", resourcePath); 293 | } 294 | this.resourcePathToUriMappings = 295 | Iterables.unmodifiableIterable(resourcePathToUriMappings.entrySet()); 296 | this.cacheBuilderSpec = cacheBuilderSpec; 297 | this.indexFile = indexFile; 298 | this.assetsName = assetsName; 299 | } 300 | 301 | 302 | @Override 303 | public void initialize(Bootstrap bootstrap) { 304 | // nothing to do 305 | } 306 | 307 | @Override 308 | public void run(AssetsBundleConfiguration bundleConfig, Environment env) throws Exception { 309 | AssetsConfiguration config = bundleConfig.getAssetsConfiguration(); 310 | 311 | // Let the cache spec from the configuration override the one specified in the code 312 | CacheBuilderSpec spec = (config.getCacheSpec() != null) 313 | ? CacheBuilderSpec.parse(config.getCacheSpec()) 314 | : cacheBuilderSpec; 315 | 316 | Iterable> overrides = config.getOverrides().entrySet(); 317 | Iterable> mimeTypes = config.getMimeTypes().entrySet(); 318 | 319 | Iterable> servletResourcePathToUriMappings; 320 | 321 | if (!config.getResourcePathToUriMappings().isEmpty()) { 322 | servletResourcePathToUriMappings = config.getResourcePathToUriMappings().entrySet(); 323 | } else { 324 | servletResourcePathToUriMappings = resourcePathToUriMappings; 325 | } 326 | AssetServlet servlet = new AssetServlet(servletResourcePathToUriMappings, indexFile, 327 | Charsets.UTF_8, spec, overrides, mimeTypes); 328 | 329 | for (Map.Entry mapping : servletResourcePathToUriMappings) { 330 | String mappingPath = mapping.getValue(); 331 | if (!mappingPath.endsWith("/")) { 332 | mappingPath += '/'; 333 | } 334 | mappingPath += "*"; 335 | servlet.setCacheControlHeader(config.getCacheControlHeader()); 336 | LOGGER.info("Registering ConfiguredAssetBundle with name: {} for path {}", assetsName, 337 | mappingPath); 338 | env.servlets().addServlet(assetsName, servlet).addMapping(mappingPath); 339 | } 340 | } 341 | } 342 | -------------------------------------------------------------------------------- /src/main/java/io/dropwizard/bundles/assets/UrlUtil.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | import java.net.MalformedURLException; 4 | import java.net.URL; 5 | 6 | public class UrlUtil { 7 | /* 8 | * Separator between JAR URL and file path within the JAR 9 | */ 10 | private static final String JAR_URL_SEPARATOR = "!/"; 11 | 12 | /** 13 | * Switch zip protocol (used by Weblogic) to jar protocol (supported by DropWizard). 14 | * 15 | * @param resourceUrl the URL to switch protocol eventually 16 | * @return the URL with eventually switched protocol 17 | */ 18 | public static URL switchFromZipToJarProtocolIfNeeded(URL resourceUrl) 19 | throws MalformedURLException { 20 | final String protocol = resourceUrl.getProtocol(); 21 | // If zip protocol switch to jar protocol 22 | if ("zip".equals(protocol) 23 | && resourceUrl.getPath().contains(".jar" + JAR_URL_SEPARATOR)) { 24 | String filePath = resourceUrl.getFile(); 25 | if (!filePath.startsWith("/")) { 26 | filePath = "/" + filePath; 27 | } 28 | return new URL("jar:file:" + filePath); 29 | } 30 | return resourceUrl; 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/io/dropwizard/bundles/assets/AssetServletTest.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.cache.CacheBuilderSpec; 5 | import com.google.common.collect.ImmutableMap; 6 | import com.google.common.net.HttpHeaders; 7 | import java.nio.charset.Charset; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import org.eclipse.jetty.http.HttpHeader; 11 | import org.eclipse.jetty.http.HttpTester; 12 | import org.eclipse.jetty.http.HttpVersion; 13 | import org.eclipse.jetty.http.MimeTypes; 14 | import org.eclipse.jetty.servlet.ServletHolder; 15 | import org.eclipse.jetty.servlet.ServletTester; 16 | import org.junit.After; 17 | import org.junit.Before; 18 | import org.junit.Test; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | 22 | public class AssetServletTest { 23 | private static final Charset DEFAULT_CHARSET = Charsets.UTF_8; 24 | private static final CacheBuilderSpec DEFAULT_CACHE_SPEC = 25 | CacheBuilderSpec.parse("maximumSize=100"); 26 | private static final Iterable> EMPTY_OVERRIDES = 27 | ImmutableMap.builder().build().entrySet(); 28 | private static final Iterable> EMPTY_MIMETYPES = 29 | ImmutableMap.builder().build().entrySet(); 30 | private static final String DUMMY_SERVLET = "/dummy_servlet/"; 31 | private static final String NOINDEX_SERVLET = "/noindex_servlet/"; 32 | private static final String NOCHARSET_SERVLET = "/nocharset_servlet/"; 33 | private static final String MIME_SERVLET = "/mime_servlet/"; 34 | private static final String MM_ASSET_SERVLET = "/mm_assets/"; 35 | private static final String MM_JSON_SERVLET = "/mm_json/"; 36 | private static final String ROOT_SERVLET = "/"; 37 | private static final String CACHE_SERVLET = "/cached/"; 38 | private static final String RESOURCE_PATH = "/assets"; 39 | private static final String JSON_RESOURCE_PATH = "/json"; 40 | 41 | // ServletTester expects to be able to instantiate the servlet with zero arguments 42 | private static Iterable> resourceMapping(String resourcePath, 43 | String uriPath) { 44 | return ImmutableMap.builder() 45 | .put(resourcePath, uriPath) 46 | .build() 47 | .entrySet(); 48 | } 49 | 50 | public static class DummyAssetServlet extends AssetServlet { 51 | private static final long serialVersionUID = -1L; 52 | 53 | public DummyAssetServlet() { 54 | super(resourceMapping(RESOURCE_PATH, DUMMY_SERVLET), "index.htm", DEFAULT_CHARSET, 55 | DEFAULT_CACHE_SPEC, EMPTY_OVERRIDES, EMPTY_MIMETYPES); 56 | } 57 | } 58 | 59 | public static class NoIndexAssetServlet extends AssetServlet { 60 | private static final long serialVersionUID = -1L; 61 | 62 | public NoIndexAssetServlet() { 63 | super(resourceMapping(RESOURCE_PATH, DUMMY_SERVLET), null, DEFAULT_CHARSET, 64 | DEFAULT_CACHE_SPEC, EMPTY_OVERRIDES, EMPTY_MIMETYPES); 65 | } 66 | } 67 | 68 | public static class RootAssetServlet extends AssetServlet { 69 | private static final long serialVersionUID = 1L; 70 | 71 | public RootAssetServlet() { 72 | super(resourceMapping("/", ROOT_SERVLET), null, DEFAULT_CHARSET, DEFAULT_CACHE_SPEC, 73 | EMPTY_OVERRIDES, EMPTY_MIMETYPES); 74 | } 75 | } 76 | 77 | public static class NoCharsetAssetServlet extends AssetServlet { 78 | private static final long serialVersionUID = 1L; 79 | 80 | /** Constructor. */ 81 | public NoCharsetAssetServlet() { 82 | super(resourceMapping(RESOURCE_PATH, NOCHARSET_SERVLET), null, DEFAULT_CHARSET, 83 | DEFAULT_CACHE_SPEC, EMPTY_OVERRIDES, EMPTY_MIMETYPES); 84 | setDefaultCharset(null); 85 | } 86 | } 87 | 88 | public static class MimeMappingsServlet extends AssetServlet { 89 | private static final long serialVersionUID = 1L; 90 | 91 | /** Constructor. */ 92 | public MimeMappingsServlet() { 93 | super(resourceMapping(RESOURCE_PATH, MIME_SERVLET), null, DEFAULT_CHARSET, DEFAULT_CACHE_SPEC, 94 | EMPTY_OVERRIDES, EMPTY_MIMETYPES); 95 | Map mimeMappings = new HashMap<>(); 96 | mimeMappings.put("bar", "application/bar"); 97 | mimeMappings.put("txt", "application/foo"); 98 | setMimeTypes(mimeMappings.entrySet()); 99 | } 100 | } 101 | 102 | public static class MultipleMappingsServlet extends AssetServlet { 103 | private static final long serialVersionUID = 1L; 104 | 105 | /** Constructor. */ 106 | public MultipleMappingsServlet() { 107 | super(ImmutableMap.builder() 108 | .put(RESOURCE_PATH, MM_ASSET_SERVLET) 109 | .put(JSON_RESOURCE_PATH, MM_JSON_SERVLET) 110 | .build().entrySet(), 111 | null, DEFAULT_CHARSET, DEFAULT_CACHE_SPEC, EMPTY_OVERRIDES, EMPTY_MIMETYPES 112 | ); 113 | } 114 | } 115 | 116 | public static class CachingServlet extends AssetServlet { 117 | private static final long serialVersionUID = -1L; 118 | 119 | /** Constructor. */ 120 | public CachingServlet() { 121 | super(resourceMapping(RESOURCE_PATH, CACHE_SERVLET),null, DEFAULT_CHARSET, DEFAULT_CACHE_SPEC, 122 | EMPTY_OVERRIDES, EMPTY_MIMETYPES); 123 | setCacheControlHeader("public"); 124 | } 125 | } 126 | 127 | private final ServletTester servletTester = new ServletTester(); 128 | private final HttpTester.Request request = HttpTester.newRequest(); 129 | private HttpTester.Response response; 130 | 131 | private HttpTester.Response makeRequest(String uri) throws Exception { 132 | request.setURI(uri); 133 | return makeRequest(); 134 | } 135 | 136 | private HttpTester.Response makeRequest() throws Exception { 137 | return HttpTester.parseResponse(servletTester.getResponses(request.generate())); 138 | } 139 | 140 | @Before 141 | public void setup() throws Exception { 142 | servletTester.addServlet(DummyAssetServlet.class, DUMMY_SERVLET + '*'); 143 | servletTester.addServlet(NoIndexAssetServlet.class, NOINDEX_SERVLET + '*'); 144 | servletTester.addServlet(NoCharsetAssetServlet.class, NOCHARSET_SERVLET + '*'); 145 | servletTester.addServlet(RootAssetServlet.class, ROOT_SERVLET + '*'); 146 | servletTester.addServlet(MimeMappingsServlet.class, MIME_SERVLET + '*'); 147 | servletTester.addServlet(CachingServlet.class, CACHE_SERVLET + '*'); 148 | 149 | ServletHolder servlet = new ServletHolder(MultipleMappingsServlet.class); 150 | servletTester.addServlet(servlet, MM_ASSET_SERVLET + '*'); 151 | servletTester.addServlet(servlet, MM_JSON_SERVLET + '*'); 152 | servletTester.start(); 153 | 154 | servletTester.getContext().getMimeTypes().addMimeMapping("mp4", "video/mp4"); 155 | servletTester.getContext().getMimeTypes().addMimeMapping("m4a", "audio/mp4"); 156 | 157 | request.setMethod("GET"); 158 | request.setURI(DUMMY_SERVLET + "example.txt"); 159 | request.setVersion(HttpVersion.HTTP_1_0); 160 | } 161 | 162 | @After 163 | public void tearDown() throws Exception { 164 | servletTester.stop(); 165 | } 166 | 167 | @Test 168 | public void servesFilesMappedToRoot() throws Exception { 169 | response = makeRequest(ROOT_SERVLET + "assets/example.txt"); 170 | assertThat(response.getStatus()) 171 | .isEqualTo(200); 172 | assertThat(response.getContent()) 173 | .isEqualTo("HELLO THERE"); 174 | } 175 | 176 | @Test 177 | public void servesCharset() throws Exception { 178 | response = makeRequest(DUMMY_SERVLET + "example.txt"); 179 | assertThat(response.getStatus()) 180 | .isEqualTo(200); 181 | assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE))) 182 | .isEqualTo(MimeTypes.Type.TEXT_PLAIN_UTF_8); 183 | 184 | response = makeRequest(NOCHARSET_SERVLET + "example.txt"); 185 | assertThat(response.getStatus()) 186 | .isEqualTo(200); 187 | assertThat(response.get(HttpHeader.CONTENT_TYPE)) 188 | .isEqualTo(MimeTypes.Type.TEXT_PLAIN.toString()); 189 | } 190 | 191 | @Test 192 | public void servesFilesFromRootsWithSameName() throws Exception { 193 | response = makeRequest(DUMMY_SERVLET + "example2.txt"); 194 | assertThat(response.getStatus()) 195 | .isEqualTo(200); 196 | assertThat(response.getContent()) 197 | .isEqualTo("HELLO THERE 2"); 198 | } 199 | 200 | @Test 201 | public void servesFilesWithA200() throws Exception { 202 | response = makeRequest(); 203 | assertThat(response.getStatus()) 204 | .isEqualTo(200); 205 | assertThat(response.getContent()) 206 | .isEqualTo("HELLO THERE"); 207 | } 208 | 209 | @Test 210 | public void throws404IfTheAssetIsMissing() throws Exception { 211 | response = makeRequest(DUMMY_SERVLET + "doesnotexist.txt"); 212 | assertThat(response.getStatus()) 213 | .isEqualTo(404); 214 | } 215 | 216 | @Test 217 | public void consistentlyAssignsETags() throws Exception { 218 | response = makeRequest(); 219 | final String firstEtag = response.get(HttpHeaders.ETAG); 220 | 221 | response = makeRequest(); 222 | final String secondEtag = response.get(HttpHeaders.ETAG); 223 | 224 | assertThat(firstEtag) 225 | .isEqualTo("\"174a6dd7325e64c609eab14ab1d30b86\"") 226 | .isEqualTo(secondEtag); 227 | } 228 | 229 | @Test 230 | public void assignsDifferentETagsForDifferentFiles() throws Exception { 231 | response = makeRequest(); 232 | final String firstEtag = response.get(HttpHeaders.ETAG); 233 | 234 | response = makeRequest(DUMMY_SERVLET + "foo.bar"); 235 | final String secondEtag = response.get(HttpHeaders.ETAG); 236 | 237 | assertThat(firstEtag) 238 | .isEqualTo("\"174a6dd7325e64c609eab14ab1d30b86\""); 239 | assertThat(secondEtag.equals("\"26ae56a90cd78c6720c544707d22110b\"") 240 | || secondEtag.equals("\"7a13c3f9f2be8379b5a2fb77a85e1d10\"")); 241 | } 242 | 243 | @Test 244 | public void supportsIfNoneMatchRequests() throws Exception { 245 | response = makeRequest(); 246 | final String correctEtag = response.get(HttpHeaders.ETAG); 247 | 248 | request.setHeader(HttpHeaders.IF_NONE_MATCH, correctEtag); 249 | response = makeRequest(); 250 | final int statusWithMatchingEtag = response.getStatus(); 251 | 252 | request.setHeader(HttpHeaders.IF_NONE_MATCH, correctEtag + "FOO"); 253 | response = makeRequest(); 254 | final int statusWithNonMatchingEtag = response.getStatus(); 255 | 256 | assertThat(statusWithMatchingEtag) 257 | .isEqualTo(304); 258 | assertThat(statusWithNonMatchingEtag) 259 | .isEqualTo(200); 260 | } 261 | 262 | @Test 263 | public void consistentlyAssignsLastModifiedTimes() throws Exception { 264 | response = makeRequest(); 265 | final long firstLastModifiedTime = response.getDateField(HttpHeaders.LAST_MODIFIED); 266 | 267 | response = makeRequest(); 268 | final long secondLastModifiedTime = response.getDateField(HttpHeaders.LAST_MODIFIED); 269 | 270 | assertThat(firstLastModifiedTime) 271 | .isEqualTo(secondLastModifiedTime); 272 | } 273 | 274 | @Test 275 | public void supportsByteRangeForMedia() throws Exception { 276 | response = makeRequest(ROOT_SERVLET + "assets/foo.mp4"); 277 | assertThat(response.getStatus()).isEqualTo(200); 278 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 279 | 280 | response = makeRequest(ROOT_SERVLET + "assets/foo.m4a"); 281 | assertThat(response.getStatus()).isEqualTo(200); 282 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 283 | } 284 | 285 | @Test 286 | public void supportsFullByteRange() throws Exception { 287 | request.setHeader(HttpHeaders.RANGE, "bytes=0-"); 288 | response = makeRequest(ROOT_SERVLET + "assets/example.txt"); 289 | assertThat(response.getStatus()).isEqualTo(206); 290 | assertThat(response.getContent()).isEqualTo("HELLO THERE"); 291 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 292 | assertThat(response.get(HttpHeaders.CONTENT_RANGE)).isEqualTo( 293 | "bytes 0-10/11"); 294 | } 295 | 296 | @Test 297 | public void supportsCentralByteRange() throws Exception { 298 | request.setHeader(HttpHeaders.RANGE, "bytes=4-8"); 299 | response = makeRequest(ROOT_SERVLET + "assets/example.txt"); 300 | assertThat(response.getStatus()).isEqualTo(206); 301 | assertThat(response.getContent()).isEqualTo("O THE"); 302 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 303 | assertThat(response.get(HttpHeaders.CONTENT_RANGE)).isEqualTo( 304 | "bytes 4-8/11"); 305 | assertThat(response.get(HttpHeaders.CONTENT_LENGTH)).isEqualTo("5"); 306 | } 307 | 308 | @Test 309 | public void supportsFinalByteRange() throws Exception { 310 | request.setHeader(HttpHeaders.RANGE, "bytes=10-10"); 311 | response = makeRequest(ROOT_SERVLET + "assets/example.txt"); 312 | assertThat(response.getStatus()).isEqualTo(206); 313 | assertThat(response.getContent()).isEqualTo("E"); 314 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 315 | assertThat(response.get(HttpHeaders.CONTENT_RANGE)).isEqualTo( 316 | "bytes 10-10/11"); 317 | assertThat(response.get(HttpHeaders.CONTENT_LENGTH)).isEqualTo("1"); 318 | 319 | request.setHeader(HttpHeaders.RANGE, "bytes=-1"); 320 | response = makeRequest(); 321 | assertThat(response.getStatus()).isEqualTo(206); 322 | assertThat(response.getContent()).isEqualTo("E"); 323 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 324 | assertThat(response.get(HttpHeaders.CONTENT_RANGE)).isEqualTo( 325 | "bytes 10-10/11"); 326 | assertThat(response.get(HttpHeaders.CONTENT_LENGTH)).isEqualTo("1"); 327 | } 328 | 329 | @Test 330 | public void rejectsInvalidByteRanges() throws Exception { 331 | request.setHeader(HttpHeaders.RANGE, "bytes=test"); 332 | response = makeRequest(ROOT_SERVLET + "assets/example.txt"); 333 | assertThat(response.getStatus()).isEqualTo(416); 334 | 335 | request.setHeader(HttpHeaders.RANGE, "bytes="); 336 | response = makeRequest(); 337 | assertThat(response.getStatus()).isEqualTo(416); 338 | 339 | request.setHeader(HttpHeaders.RANGE, "bytes=1-infinity"); 340 | response = makeRequest(); 341 | assertThat(response.getStatus()).isEqualTo(416); 342 | 343 | request.setHeader(HttpHeaders.RANGE, "test"); 344 | response = makeRequest(); 345 | assertThat(response.getStatus()).isEqualTo(416); 346 | } 347 | 348 | @Test 349 | public void supportsMultipleByteRanges() throws Exception { 350 | request.setHeader(HttpHeaders.RANGE, "bytes=0-0,-1"); 351 | response = makeRequest(ROOT_SERVLET + "assets/example.txt"); 352 | assertThat(response.getStatus()).isEqualTo(206); 353 | assertThat(response.getContent()).isEqualTo("HE"); 354 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 355 | assertThat(response.get(HttpHeaders.CONTENT_RANGE)).isEqualTo( 356 | "bytes 0-0,10-10/11"); 357 | assertThat(response.get(HttpHeaders.CONTENT_LENGTH)).isEqualTo("2"); 358 | 359 | request.setHeader(HttpHeaders.RANGE, "bytes=5-6,7-10"); 360 | response = makeRequest(); 361 | assertThat(response.getStatus()).isEqualTo(206); 362 | assertThat(response.getContent()).isEqualTo(" THERE"); 363 | assertThat(response.get(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); 364 | assertThat(response.get(HttpHeaders.CONTENT_RANGE)).isEqualTo( 365 | "bytes 5-6,7-10/11"); 366 | assertThat(response.get(HttpHeaders.CONTENT_LENGTH)).isEqualTo("6"); 367 | } 368 | 369 | @Test 370 | public void supportsIfRangeMatchRequests() throws Exception { 371 | response = makeRequest(); 372 | final String correctEtag = response.get(HttpHeaders.ETAG); 373 | 374 | request.setHeader(HttpHeaders.RANGE, "bytes=10-10"); 375 | 376 | request.setHeader(HttpHeaders.IF_RANGE, correctEtag); 377 | response = makeRequest(); 378 | final int statusWithMatchingEtag = response.getStatus(); 379 | 380 | request.setHeader(HttpHeaders.IF_RANGE, correctEtag + "FOO"); 381 | response = makeRequest(); 382 | final int statusWithNonMatchingEtag = response.getStatus(); 383 | 384 | assertThat(statusWithMatchingEtag).isEqualTo(206); 385 | assertThat(statusWithNonMatchingEtag).isEqualTo(200); 386 | } 387 | 388 | @Test 389 | public void supportsIfModifiedSinceRequests() throws Exception { 390 | response = makeRequest(); 391 | final long lastModifiedTime = response.getDateField(HttpHeaders.LAST_MODIFIED); 392 | 393 | request.putDateField(HttpHeaders.IF_MODIFIED_SINCE, lastModifiedTime); 394 | response = makeRequest(); 395 | final int statusWithMatchingLastModifiedTime = response.getStatus(); 396 | 397 | request.putDateField(HttpHeaders.IF_MODIFIED_SINCE, lastModifiedTime - 100); 398 | response = makeRequest(); 399 | final int statusWithStaleLastModifiedTime = response.getStatus(); 400 | 401 | request.putDateField(HttpHeaders.IF_MODIFIED_SINCE, lastModifiedTime + 100); 402 | response = makeRequest(); 403 | final int statusWithRecentLastModifiedTime = response.getStatus(); 404 | 405 | assertThat(statusWithMatchingLastModifiedTime) 406 | .isEqualTo(304); 407 | assertThat(statusWithStaleLastModifiedTime) 408 | .isEqualTo(200); 409 | assertThat(statusWithRecentLastModifiedTime) 410 | .isEqualTo(304); 411 | } 412 | 413 | @Test 414 | public void guessesMimeTypes() throws Exception { 415 | response = makeRequest(); 416 | assertThat(response.getStatus()) 417 | .isEqualTo(200); 418 | assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE))) 419 | .isEqualTo(MimeTypes.Type.TEXT_PLAIN_UTF_8); 420 | } 421 | 422 | @Test 423 | public void defaultsToHtml() throws Exception { 424 | response = makeRequest(DUMMY_SERVLET + "foo.bar"); 425 | assertThat(response.getStatus()) 426 | .isEqualTo(200); 427 | assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE))) 428 | .isEqualTo(MimeTypes.Type.TEXT_HTML_UTF_8); 429 | } 430 | 431 | @Test 432 | public void servesIndexFilesByDefault() throws Exception { 433 | // Root directory listing: 434 | response = makeRequest(DUMMY_SERVLET); 435 | assertThat(response.getStatus()) 436 | .isEqualTo(200); 437 | assertThat(response.getContent()) 438 | .contains("/assets Index File"); 439 | 440 | // Subdirectory listing: 441 | response = makeRequest(DUMMY_SERVLET + "some_directory"); 442 | assertThat(response.getStatus()) 443 | .isEqualTo(200); 444 | assertThat(response.getContent()) 445 | .contains("/assets/some_directory Index File"); 446 | 447 | // Subdirectory listing with slash: 448 | response = makeRequest(DUMMY_SERVLET + "some_directory/"); 449 | assertThat(response.getStatus()) 450 | .isEqualTo(200); 451 | assertThat(response.getContent()) 452 | .contains("/assets/some_directory Index File"); 453 | } 454 | 455 | @Test 456 | public void throwsA404IfNoIndexFileIsDefined() throws Exception { 457 | // Root directory listing: 458 | response = makeRequest(NOINDEX_SERVLET + '/'); 459 | assertThat(response.getStatus()) 460 | .isEqualTo(404); 461 | 462 | // Subdirectory listing: 463 | response = makeRequest(NOINDEX_SERVLET + "some_directory"); 464 | assertThat(response.getStatus()) 465 | .isEqualTo(404); 466 | 467 | // Subdirectory listing with slash: 468 | response = makeRequest(NOINDEX_SERVLET + "some_directory/"); 469 | assertThat(response.getStatus()) 470 | .isEqualTo(404); 471 | } 472 | 473 | @Test 474 | public void doesNotAllowOverridingUrls() throws Exception { 475 | response = makeRequest(DUMMY_SERVLET + "file:/etc/passwd"); 476 | assertThat(response.getStatus()) 477 | .isEqualTo(404); 478 | } 479 | 480 | @Test 481 | public void doesNotAllowOverridingPaths() throws Exception { 482 | response = makeRequest(DUMMY_SERVLET + "/etc/passwd"); 483 | assertThat(response.getStatus()) 484 | .isEqualTo(404); 485 | } 486 | 487 | @Test 488 | public void allowsEncodedAssetNames() throws Exception { 489 | response = makeRequest(DUMMY_SERVLET + "encoded%20example.txt"); 490 | assertThat(response.getStatus()) 491 | .isEqualTo(200); 492 | } 493 | 494 | @Test 495 | public void addMimeMappings() throws Exception { 496 | response = makeRequest(MIME_SERVLET + "foo.bar"); 497 | assertThat(response.getStatus()) 498 | .isEqualTo(200); 499 | assertThat(response.get(HttpHeader.CONTENT_TYPE)) 500 | .isEqualTo("application/bar"); 501 | } 502 | 503 | @Test 504 | public void overrideMimeMapping() throws Exception { 505 | response = makeRequest(MIME_SERVLET + "example.txt"); 506 | assertThat(response.getStatus()) 507 | .isEqualTo(200); 508 | assertThat(response.get(HttpHeader.CONTENT_TYPE)) 509 | .isEqualTo("application/foo"); 510 | } 511 | 512 | @Test 513 | public void servesFromMultipleMappings() throws Exception { 514 | response = makeRequest(MM_ASSET_SERVLET + "/example.txt"); 515 | assertThat(response.getStatus()) 516 | .isEqualTo(200); 517 | assertThat(response.getContent()) 518 | .isEqualTo("HELLO THERE"); 519 | 520 | response = makeRequest(MM_JSON_SERVLET + "/example.txt"); 521 | assertThat(response.getStatus()) 522 | .isEqualTo(200); 523 | assertThat(response.getContent()) 524 | .isEqualTo("HELLO JSON"); 525 | } 526 | 527 | @Test 528 | public void noPollutionAcrossMultipleMappings() throws Exception { 529 | response = makeRequest(MM_ASSET_SERVLET + "/json%20only.txt"); 530 | assertThat(response.getStatus()) 531 | .isEqualTo(404); 532 | 533 | response = makeRequest(MM_JSON_SERVLET + "/json%20only.txt"); 534 | assertThat(response.getStatus()) 535 | .isEqualTo(200); 536 | } 537 | 538 | @Test 539 | public void noCacheControlHeaderByDefault() throws Exception { 540 | response = makeRequest(); 541 | assertThat(response.getStatus()).isEqualTo(200); 542 | assertThat(response.get(HttpHeader.CACHE_CONTROL)).isNull(); 543 | } 544 | 545 | @Test 546 | public void servesCacheControlHeader() throws Exception { 547 | response = makeRequest(CACHE_SERVLET + "example.txt"); 548 | assertThat(response.getStatus()).isEqualTo(200); 549 | assertThat(response.get(HttpHeader.CACHE_CONTROL)).isEqualTo("public"); 550 | } 551 | } 552 | -------------------------------------------------------------------------------- /src/test/java/io/dropwizard/bundles/assets/AssetsBundleTest.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; 5 | import com.google.common.cache.CacheBuilderSpec; 6 | import com.google.common.collect.ImmutableMap; 7 | import io.dropwizard.jackson.Jackson; 8 | import io.dropwizard.jetty.setup.ServletEnvironment; 9 | import io.dropwizard.setup.Environment; 10 | import java.io.FileInputStream; 11 | import java.io.IOException; 12 | import java.util.List; 13 | import javax.servlet.ServletRegistration; 14 | import org.junit.Before; 15 | import org.junit.Test; 16 | import org.mockito.ArgumentCaptor; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.junit.Assert.assertEquals; 20 | import static org.junit.Assert.assertNull; 21 | import static org.mockito.Mockito.any; 22 | import static org.mockito.Mockito.anyString; 23 | import static org.mockito.Mockito.atLeastOnce; 24 | import static org.mockito.Mockito.eq; 25 | import static org.mockito.Mockito.mock; 26 | import static org.mockito.Mockito.verify; 27 | import static org.mockito.Mockito.when; 28 | 29 | public class AssetsBundleTest { 30 | private final ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); 31 | private final Environment environment = mock(Environment.class); 32 | 33 | private final AssetsBundleConfiguration defaultConfiguration = new AssetsBundleConfiguration() { 34 | @Override 35 | public AssetsConfiguration getAssetsConfiguration() { 36 | return AssetsConfiguration.builder().build(); 37 | } 38 | }; 39 | 40 | private String servletPath; 41 | private List servletPaths; 42 | private AssetServlet servlet; 43 | 44 | @Before 45 | public void setUp() throws Exception { 46 | when(environment.servlets()).thenReturn(servletEnvironment); 47 | } 48 | 49 | @Test 50 | public void deserialzeAssetsConfiguration() throws IOException { 51 | ObjectMapper mapper = Jackson.newObjectMapper(new YAMLFactory()); 52 | FileInputStream inputStream = new FileInputStream("src/test/resources/assets/config.yml"); 53 | AssetsConfiguration assets = mapper.readValue(inputStream, AssetsConfiguration.class); 54 | assertEquals(assets.getCacheSpec(), "abc"); 55 | assertEquals(assets.getResourcePathToUriMappings(), ImmutableMap.of("/assets/","/dashboard/")); 56 | assertEquals(assets.getMimeTypes(), ImmutableMap.of("woff", "application/font-woff")); 57 | assertEquals(assets.getOverrides(), ImmutableMap.of("/","../example-app/build/src")); 58 | assertNull(assets.getCacheControlHeader()); 59 | } 60 | 61 | @Test 62 | public void hasADefaultPath() throws Exception { 63 | runBundle(new ConfiguredAssetsBundle()); 64 | 65 | assertThat(servletPath) 66 | .isEqualTo("/assets/*"); 67 | } 68 | 69 | @Test 70 | public void canHaveCustomPaths() throws Exception { 71 | runBundle(new ConfiguredAssetsBundle("/json")); 72 | 73 | assertThat(servletPath) 74 | .isEqualTo("/json/*"); 75 | } 76 | 77 | @Test 78 | public void canHaveDifferentUriAndResourcePaths() throws Exception { 79 | runBundle(new ConfiguredAssetsBundle("/json", "/what")); 80 | 81 | assertThat(servletPath) 82 | .isEqualTo("/what/*"); 83 | } 84 | 85 | @Test 86 | public void canSupportDifferentAssetsBundleName() throws Exception { 87 | runBundle(new ConfiguredAssetsBundle("/json", "/what/new", "index.txt", "customAsset1"), 88 | "customAsset1", defaultConfiguration); 89 | 90 | assertThat(servletPath) 91 | .isEqualTo("/what/new/*"); 92 | 93 | runBundle(new ConfiguredAssetsBundle("/json", "/what/old", "index.txt", "customAsset2"), 94 | "customAsset2", defaultConfiguration); 95 | assertThat(servletPath) 96 | .isEqualTo("/what/old/*"); 97 | } 98 | 99 | @Test 100 | public void canHaveDifferentUriAndResourcePathsAndIndexFilename() throws Exception { 101 | runBundle(new ConfiguredAssetsBundle("/json", "/what", "index.txt")); 102 | 103 | assertThat(servletPath) 104 | .isEqualTo("/what/*"); 105 | } 106 | 107 | @Test 108 | public void canHaveMultipleMappings() throws Exception { 109 | runBundle(new ConfiguredAssetsBundle(ImmutableMap.builder() 110 | .put("/risk", "/riskPath") 111 | .put("/catan", "/catanPath") 112 | .build() 113 | )); 114 | 115 | assertThat(servletPaths.size()).isEqualTo(2); 116 | assertThat(servletPaths).contains("/riskPath/*"); 117 | assertThat(servletPaths).contains("/catanPath/*"); 118 | } 119 | 120 | @Test 121 | public void usesDefaultCacheSpec() throws Exception { 122 | runBundle(new ConfiguredAssetsBundle()); 123 | assertThat(servlet.getCacheSpec()).isEqualTo(ConfiguredAssetsBundle.DEFAULT_CACHE_SPEC); 124 | } 125 | 126 | @Test 127 | public void canOverrideCacheSpec() throws Exception { 128 | final String cacheSpec = "expireAfterAccess=20m"; 129 | 130 | AssetsBundleConfiguration config = new AssetsBundleConfiguration() { 131 | @Override 132 | public AssetsConfiguration getAssetsConfiguration() { 133 | return AssetsConfiguration.builder().cacheSpec(cacheSpec).build(); 134 | } 135 | }; 136 | 137 | runBundle(new ConfiguredAssetsBundle(), "assets", config); 138 | assertThat(servlet.getCacheSpec()).isEqualTo(CacheBuilderSpec.parse(cacheSpec)); 139 | } 140 | 141 | private void runBundle(ConfiguredAssetsBundle bundle) throws Exception { 142 | runBundle(bundle, "assets", defaultConfiguration); 143 | } 144 | 145 | private void runBundle(ConfiguredAssetsBundle bundle, String assetName, 146 | AssetsBundleConfiguration config) throws Exception { 147 | final ServletRegistration.Dynamic registration = mock(ServletRegistration.Dynamic.class); 148 | when(servletEnvironment.addServlet(anyString(), any(AssetServlet.class))) 149 | .thenReturn(registration); 150 | 151 | bundle.run(config, environment); 152 | 153 | final ArgumentCaptor servletCaptor = ArgumentCaptor.forClass(AssetServlet.class); 154 | final ArgumentCaptor pathCaptor = ArgumentCaptor.forClass(String.class); 155 | 156 | verify(servletEnvironment, atLeastOnce()).addServlet(eq(assetName), servletCaptor.capture()); 157 | verify(registration, atLeastOnce()).addMapping(pathCaptor.capture()); 158 | 159 | this.servletPath = pathCaptor.getValue(); 160 | this.servletPaths = pathCaptor.getAllValues(); 161 | 162 | // If more than one servlet was captured, let's verify they're the same instance. 163 | List capturedServlets = servletCaptor.getAllValues(); 164 | if (capturedServlets.size() > 1) { 165 | for (AssetServlet servlet : capturedServlets) { 166 | assertThat(servlet == capturedServlets.get(0)); 167 | } 168 | } 169 | 170 | this.servlet = capturedServlets.get(0); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /src/test/java/io/dropwizard/bundles/assets/AssetsConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package io.dropwizard.bundles.assets; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import org.junit.After; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | public class AssetsConfigurationTest { 11 | private AssetsConfiguration config; 12 | 13 | private static final String A_RESOURCE_PATH = "/a/resource/path"; 14 | private static final String AN_URI = "/an/uri"; 15 | 16 | @Before 17 | public void setupConfig() throws Exception { 18 | final Map mappings = new HashMap<>(); 19 | mappings.put(A_RESOURCE_PATH, AN_URI); 20 | config = AssetsConfiguration.builder().mappings(mappings).build(); 21 | } 22 | 23 | @After 24 | public void clearConfig() throws Exception { 25 | config = null; 26 | } 27 | 28 | @Test 29 | public void keysAndValuesInTheResourcePathUriMappinsAlwaysEndWithSlash() { 30 | Map actualMappings = config.getResourcePathToUriMappings(); 31 | Assert.assertNotNull(actualMappings); 32 | Assert.assertEquals(1, actualMappings.size()); 33 | Assert.assertTrue(actualMappings.containsKey(A_RESOURCE_PATH + "/")); 34 | Assert.assertEquals(AN_URI + "/", actualMappings.get(A_RESOURCE_PATH + "/")); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/more-resources/assets/example2.txt: -------------------------------------------------------------------------------- 1 | HELLO THERE 2 -------------------------------------------------------------------------------- /src/test/resources/assets/config.yml: -------------------------------------------------------------------------------- 1 | cacheSpec: abc 2 | mappings: 3 | /assets: /dashboard 4 | mimeTypes: 5 | woff: application/font-woff 6 | overrides: 7 | /: ../example-app/build/src -------------------------------------------------------------------------------- /src/test/resources/assets/encoded example.txt: -------------------------------------------------------------------------------- 1 | yay 2 | -------------------------------------------------------------------------------- /src/test/resources/assets/example.txt: -------------------------------------------------------------------------------- 1 | HELLO THERE -------------------------------------------------------------------------------- /src/test/resources/assets/foo.bar: -------------------------------------------------------------------------------- 1 | BAZOMATIX 2 | -------------------------------------------------------------------------------- /src/test/resources/assets/foo.m4a: -------------------------------------------------------------------------------- 1 | NOT REALLY AN MP4 FILE 2 | -------------------------------------------------------------------------------- /src/test/resources/assets/foo.mp4: -------------------------------------------------------------------------------- 1 | NOT REALLY AN MP4 FILE 2 | -------------------------------------------------------------------------------- /src/test/resources/assets/index.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | /assets Index File 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/test/resources/assets/some_directory/example.txt: -------------------------------------------------------------------------------- 1 | WRONG FILE FELLA! 2 | -------------------------------------------------------------------------------- /src/test/resources/assets/some_directory/index.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | /assets/some_directory Index File 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/test/resources/json/example.txt: -------------------------------------------------------------------------------- 1 | HELLO JSON -------------------------------------------------------------------------------- /src/test/resources/json/json only.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dropwizard-bundles/dropwizard-configurable-assets-bundle/e07f06b80316e1b348d08eba097f923ee3afd3ec/src/test/resources/json/json only.txt --------------------------------------------------------------------------------