001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.staticfile;
018
019import static org.apache.juneau.commons.utils.CollectionUtils.*;
020import static org.apache.juneau.commons.utils.FileUtils.*;
021import static org.apache.juneau.commons.utils.Shorts.*;
022
023import java.io.*;
024import java.util.*;
025
026import org.apache.juneau.commons.collections.*;
027import org.apache.juneau.commons.inject.*;
028import org.apache.juneau.commons.io.*;
029import org.apache.juneau.http.*;
030import org.apache.juneau.http.entity.*;
031import org.apache.juneau.http.header.*;
032import org.apache.juneau.http.resource.*;
033import org.apache.juneau.http.response.*;
034import org.apache.juneau.marshall.cp.*;
035import org.apache.juneau.rest.server.*;
036
037/**
038 * API for retrieving localized static files from either the classpath or file system.
039 *
040 * <p>
041 * Provides the same functionality as {@link BasicFileFinder} but adds support for returning files as {@link HttpResource}
042 * objects with arbitrary headers.
043 *
044 * <h2 class='section'>See Also:</h2><ul>
045 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/StaticFiles">Static files</a>
046 * </ul>
047 */
048@SuppressWarnings({
049   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
050   "resource" // Resource management handled externally
051})
052public class BasicStaticFiles implements StaticFiles {
053
054   /**
055    * Creates a new builder for this object.
056    *
057    * @param beanStore The bean store to use for creating beans.
058    * @return A new builder for this object.
059    */
060   public static StaticFiles.Builder create(BeanStore beanStore) {
061      return new StaticFiles.Builder(beanStore);
062   }
063
064   // Class files, dotfiles, and common configuration/credential/backup file types are never served.
065   static final String EXCLUDE_PATTERN = "(?i)(.*/)?\\.[^/]*|.*\\.(class|properties|ya?ml|xml|jks|p12|pfx|pem|key|env|cfg|conf|bak)";
066
067   private final HttpHeader[] headers;
068   private final MimeTypeDetector mimeTypes;
069   private final int hashCode;
070
071   private final FileFinder fileFinder;
072
073   /**
074    * Constructor.
075    *
076    * @param beanStore The bean store containing injectable beans for this static files object. Must not be <jk>null</jk>.
077    */
078   public BasicStaticFiles(BeanStore beanStore) {
079      // @formatter:off
080      this(StaticFiles
081         .create(beanStore)
082         .dir("static")
083         .dir("htdocs")
084         .cp(beanStore.getBean(ResourceSupplier.class).orElseThrow(() -> new IllegalStateException("ResourceSupplier not found")).getResourceClass(), "htdocs", true)
085         .cp(beanStore.getBean(ResourceSupplier.class).orElseThrow(() -> new IllegalStateException("ResourceSupplier not found")).getResourceClass(), "/htdocs", true)
086         .caching(1_000_000)
087         .exclude(EXCLUDE_PATTERN)
088         .headers(CacheControl.of("max-age=86400, public"))
089      );
090      // @formatter:on
091   }
092
093   /**
094    * Constructor.
095    *
096    * @param builder The builder object. Must not be <jk>null</jk>.
097    */
098   public BasicStaticFiles(StaticFiles.Builder builder) {
099      this.headers = builder.headers.toArray(new HttpHeader[builder.headers.size()]);
100      this.mimeTypes = builder.mimeTypes;
101      this.hashCode = h(hashCode(), headers);
102      this.fileFinder = builder.fileFinder.build();
103   }
104
105   /**
106    * Constructor.
107    *
108    * <p>
109    * Can be used when subclassing and overriding the {@link #resolve(String, Locale)} method.
110    */
111   protected BasicStaticFiles() {
112      this.headers = new HttpHeader[0];
113      this.mimeTypes = null;
114      this.hashCode = h(hashCode(), headers);
115      this.fileFinder = null;
116   }
117
118   @Override /* Overridden from Object */
119   public boolean equals(Object o) {
120      return this == o || (o instanceof BasicStaticFiles o2 && eq(this, o2, (x, y) -> Arrays.equals(x.headers, y.headers)));
121   }
122
123   @Override /* Overridden from FileFinder */
124   public Optional<InputStream> getStream(String name, Locale locale) throws IOException {
125      return fileFinder.getStream(name, locale);
126   }
127
128   @Override /* Overridden from FileFinder */
129   public Optional<String> getString(String name, Locale locale) throws IOException {
130      return fileFinder.getString(name, locale);
131   }
132
133   @Override
134   public int hashCode() {
135      return hashCode;
136   }
137
138   /**
139    * Resolve the specified path.
140    *
141    * <p>
142    * Subclasses can override this method to provide specialized handling.
143    *
144    * @param path The path to resolve to a static file.
145    * @param locale Optional locale.
146    * @return The resource, or an empty {@link Optional} if not found.
147    */
148   @Override /* Overridden from StaticFiles */
149   public Optional<HttpResource> resolve(String path, Locale locale) {
150      try {
151         Optional<InputStream> is = getStream(path, locale);
152         if (! is.isPresent())
153            return oe();
154         var ct = mimeTypes == null ? null : mimeTypes.getContentType(getFileName(path));
155         var hdrs = new ArrayList<HttpHeader>();
156         if (ct != null)
157            hdrs.add(ContentType.of(ct));
158         Arrays.stream(headers).filter(Objects::nonNull).forEach(hdrs::add);
159         return o(HttpResourceBean.of(StreamBody.of(is.get()), hdrs));
160      } catch (IOException e) {
161         throw new InternalServerError(e);
162      }
163   }
164
165   protected FluentMap<String,Object> properties() {
166      // @formatter:off
167      return filteredBeanPropertyMap()
168         .a("headers", headers);
169      // @formatter:on
170   }
171
172   @Override /* Overridden from Object */
173   public String toString() {
174      return r(properties());
175   }
176}