View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2015 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.caravan.hal.docs.impl;
21  
22  import java.io.IOException;
23  import java.net.URL;
24  import java.util.Map;
25  
26  import javax.servlet.http.HttpServletRequest;
27  import javax.servlet.http.HttpServletResponse;
28  
29  import org.apache.commons.io.FilenameUtils;
30  import org.apache.commons.lang3.CharEncoding;
31  import org.osgi.framework.Bundle;
32  import org.osgi.service.http.HttpContext;
33  
34  import com.google.common.collect.ImmutableMap;
35  
36  /**
37   * Wraps a defaul HTTP context, but redirects all resource requests to the bundle given in contructor.
38   */
39  class HttpContextWrapper implements HttpContext {
40  
41    static final String MIMETYPE_JSON = "application/json";
42    static final String MIMETYPE_HTML = "text/html;charset=" + CharEncoding.UTF_8;
43  
44    /**
45     * List of common mime types we should support always.
46     */
47    private static final Map<String, String> MIME_TYPES = ImmutableMap.<String, String>builder()
48        .put("json", MIMETYPE_JSON)
49        .put("html", MIMETYPE_HTML)
50        .build();
51  
52    private final HttpContext delegate;
53    private final Bundle bundle;
54  
55    HttpContextWrapper(HttpContext httpContext, Bundle bundle) {
56      this.delegate = httpContext;
57      this.bundle = bundle;
58    }
59  
60    @Override
61    public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
62      return delegate.handleSecurity(request, response);
63    }
64  
65    @Override
66    public URL getResource(String name) {
67      return bundle.getResource(name);
68    }
69  
70    @Override
71    public String getMimeType(String name) {
72      String mimeType = delegate.getMimeType(name);
73      if (mimeType == null) {
74        String extension = FilenameUtils.getExtension(name);
75        if (extension != null) {
76          mimeType = MIME_TYPES.get(extension);
77        }
78      }
79      return mimeType;
80    }
81  
82  }