001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.rest;
014
015import static org.apache.juneau.internal.CollectionUtils.*;
016
017import java.util.*;
018
019import org.apache.juneau.*;
020import org.apache.juneau.internal.*;
021import org.apache.juneau.parser.*;
022import org.apache.juneau.rest.annotation.*;
023import org.apache.juneau.utils.*;
024
025/**
026 * Static file mapping.
027 *
028 * <p>
029 * Used to define paths and locations of statically-served files such as images or HTML documents.
030 *
031 * <p>
032 * An example where this class is used is in the {@link RestResource#staticFiles} annotation:
033 * <p class='bcode w800'>
034 * <jk>package</jk> com.foo.mypackage;
035 *
036 * <ja>@RestResource</ja>(
037 *    path=<js>"/myresource"</js>,
038 *    staticFiles={<js>"htdocs:docs"</js>}
039 * )
040 * <jk>public class</jk> MyResource <jk>extends</jk> BasicRestServlet {...}
041 * </p>
042 *
043 * <p>
044 * Static files are found by using the {@link ClasspathResourceFinder} defined on the resource.
045 *
046 * <p>
047 * In the example above, given a GET request to <l>/myresource/htdocs/foobar.html</l>, the servlet will attempt to find
048 * the <l>foobar.html</l> file in the following ordered locations:
049 * <ol>
050 *    <li><l>com.foo.mypackage.docs</l> package.
051 *    <li><l>org.apache.juneau.rest.docs</l> package (since <l>BasicRestServlet</l> is in <l>org.apache.juneau.rest</l>).
052 *    <li><l>[working-dir]/docs</l> directory.
053 * </ol>
054 *
055 * <h5 class='section'>Notes:</h5>
056 * <ul class='spaced-list'>
057 *    <li>
058 *       Mappings are cumulative from parent to child.  Child resources can override mappings made on parent resources.
059 *    <li>
060 *       The media type on the response is determined by the {@link org.apache.juneau.rest.RestContext#getMediaTypeForName(String)} method.
061 * </ul>
062 *
063 * <h5 class='section'>See Also:</h5>
064 * <ul>
065 *    <li class='link'>{@doc juneau-rest-server.StaticFiles}
066 * </ul>
067 */
068public class StaticFileMapping {
069
070   final Class<?> resourceClass;
071   final String path, location;
072   final Map<String,Object> responseHeaders;
073
074   /**
075    * Constructor.
076    *
077    * @param resourceClass
078    *    The resource/servlet class which serves as the base location of the location below.
079    * @param path
080    *    The mapped URI path.
081    *    <br>Leading and trailing slashes are trimmed.
082    * @param location
083    *    The location relative to the resource class.
084    *    <br>Leading and trailing slashes are trimmed.
085    * @param responseHeaders
086    *    The response headers.
087    *    Can be <jk>null</jk>.
088    */
089   public StaticFileMapping(Class<?> resourceClass, String path, String location, Map<String,Object> responseHeaders) {
090      this.resourceClass = resourceClass;
091      this.path = StringUtils.trimSlashes(path);
092      this.location = StringUtils.trimSlashes(location);
093      this.responseHeaders = immutableMap(responseHeaders);
094   }
095
096   /**
097    * Constructor using a mapping string to represent a path/location pairing.
098    *
099    * <p>
100    * Mapping string must be one of these formats:
101    * <ul>
102    *    <li><js>"path:location"</js> (e.g. <js>"foodocs:docs/foo"</js>)
103    *    <li><js>"path:location:headers-json"</js> (e.g. <js>"foodocs:docs/foo:{'Cache-Control':'max-age=86400, public'}"</js>)
104    * </ul>
105    *
106    * @param resourceClass
107    *    The resource/servlet class which serves as the base location of the location below.
108    * @param mappingString
109    *    The mapping string that represents the path/location mapping.
110    *    <br>Leading and trailing slashes and whitespace are trimmed from path and location.
111    */
112   public StaticFileMapping(Class<?> resourceClass, String mappingString) {
113      this.resourceClass = resourceClass;
114      String[] parts = StringUtils.split(mappingString, ':', 3);
115      if (parts == null || parts.length <= 1)
116         throw new FormattedRuntimeException("Invalid mapping string format: ''{0}'' on resource class ''{1}''", mappingString, resourceClass.getName());
117      this.path = StringUtils.trimSlashes(parts[0]);
118      this.location = StringUtils.trimSlashes(parts[1]);
119      if (parts.length == 3) {
120         try {
121            responseHeaders = unmodifiableMap(new ObjectMap(parts[2]));
122         } catch (ParseException e) {
123            throw new FormattedRuntimeException(e, "Invalid mapping string format: ''{0}'' on resource class ''{1}''", mappingString, resourceClass.getName());
124         }
125      } else {
126         responseHeaders = null;
127      }
128   }
129}