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.dam.assetservice.impl;
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.List;
25  
26  import javax.servlet.ServletException;
27  import javax.servlet.http.HttpServletResponse;
28  
29  import org.apache.commons.lang3.CharEncoding;
30  import org.apache.sling.api.SlingHttpServletRequest;
31  import org.apache.sling.api.SlingHttpServletResponse;
32  import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
33  import org.apache.sling.commons.json.JSONArray;
34  import org.apache.sling.commons.json.JSONException;
35  import org.apache.sling.commons.json.JSONObject;
36  import org.slf4j.Logger;
37  import org.slf4j.LoggerFactory;
38  
39  import io.wcm.handler.media.Media;
40  import io.wcm.handler.media.MediaHandler;
41  import io.wcm.handler.media.Rendition;
42  import io.wcm.wcm.commons.contenttype.ContentType;
43  
44  /**
45   * Implements a simple REST interface that allows resolving DAM asset paths to URLs.
46   * For image assets resolving to specific dimensions is supported.
47   */
48  @SuppressWarnings("deprecation")
49  class AssetRequestServlet extends SlingSafeMethodsServlet {
50    private static final long serialVersionUID = 1L;
51  
52    private final DamPathHandler damPathHandler;
53  
54    private static final Logger log = LoggerFactory.getLogger(AssetRequestServlet.class);
55  
56    AssetRequestServlet(DamPathHandler damPathHandler) {
57      this.damPathHandler = damPathHandler;
58    }
59  
60    @SuppressWarnings("null")
61    @Override
62    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
63      String assetPath = request.getResource().getPath();
64  
65      // check if asset path is valid
66      if (!damPathHandler.isAllowedAssetPath(assetPath)) {
67        log.debug("Asset path not allowed {}", assetPath);
68        response.sendError(HttpServletResponse.SC_NOT_FOUND);
69        return;
70      }
71  
72      // get media handler
73      MediaHandler mediaHandler = request.getResource().adaptTo(MediaHandler.class);
74      if (mediaHandler == null) {
75        log.debug("Unable to get media handler for {}", assetPath);
76        response.sendError(HttpServletResponse.SC_NOT_FOUND);
77        return;
78      }
79  
80      // build list of asset service requests with optional input parameters
81      List<AssetRequest> requests = AssetRequestParser.getAssetRequests(assetPath, request);
82  
83      // resolve asset service requests
84      List<Media> mediaList = resolveMedia(requests, mediaHandler);
85      if (mediaList.isEmpty()) {
86        log.debug("No matching assets/renditions found for {}; requests: {}", assetPath, requests);
87        response.sendError(HttpServletResponse.SC_NOT_FOUND);
88        return;
89      }
90  
91      // output result json
92      try {
93        JSONArray resultJson = toResultJson(mediaList);
94        response.setContentType(ContentType.JSON);
95        response.setCharacterEncoding(CharEncoding.UTF_8);
96        response.getWriter().write(resultJson.toString());
97      }
98      catch (JSONException ex) {
99        throw new ServletException("Unable to generate JSON.", ex);
100     }
101   }
102 
103   private List<Media> resolveMedia(List<AssetRequest> requests, MediaHandler mediaHandler) {
104     List<Media> result = new ArrayList<>();
105     for (AssetRequest request : requests) {
106       Media media = request.resolve(mediaHandler);
107       if (media.isValid()) {
108         result.add(media);
109       }
110     }
111     return result;
112   }
113 
114   private JSONArray toResultJson(List<Media> mediaList) throws JSONException {
115     JSONArray array = new JSONArray();
116     for (Media media : mediaList) {
117       Rendition rendition = media.getRendition();
118       JSONObject mediaObject = new JSONObject();
119       mediaObject.put("assetPath", media.getAsset().getPath());
120       mediaObject.put("url", media.getUrl());
121       if (rendition.getWidth() > 0 && rendition.getHeight() > 0) {
122         mediaObject.put("width", rendition.getWidth());
123         mediaObject.put("height", rendition.getHeight());
124       }
125       if (rendition.getFileSize() > 0) {
126         mediaObject.put("fileSize", rendition.getFileSize());
127       }
128       mediaObject.putOpt("fileExtension", rendition.getFileExtension());
129       mediaObject.putOpt("mimeType", rendition.getMimeType());
130       array.put(mediaObject);
131     }
132     return array;
133   }
134 
135 }