View Javadoc
1   /*
2    * $Id$
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  
23  package org.apache.struts.webapp.exercise;
24  
25  
26  import java.io.InputStream;
27  import java.io.OutputStream;
28  
29  import jakarta.servlet.http.HttpServletRequest;
30  import jakarta.servlet.http.HttpServletResponse;
31  
32  import org.apache.struts.action.Action;
33  import org.apache.struts.action.ActionForm;
34  import org.apache.struts.action.ActionForward;
35  import org.apache.struts.action.ActionMapping;
36  
37  
38  /**
39   * Read image from resource given as ActionMapping parameter
40   * and copy to output stream.
41   *
42   * @version $Rev$ $Date$
43   */
44  
45  public class ImageAction extends Action {
46      private static final long serialVersionUID = -917797528635967028L;
47  
48  
49      /**
50       * Read image from resource given as ActionMapping parameter
51       * and copy to output stream.
52       *
53       * @exception java.lang.Exception on input/output error
54       */
55      public ActionForward execute(
56              ActionMapping mapping,
57              ActionForm form,
58              HttpServletRequest request,
59              HttpServletResponse response)
60              throws Exception {
61  
62          // e.g. /$module/struts-power.gif
63          // :FIXME: Should compute module
64          String image = mapping.getParameter();
65  
66          byte[] buffer = new byte[2048];
67          int bytesRead;
68  
69          try (InputStream input = getServlet().getServletContext().getResourceAsStream(image)) {
70              final OutputStream out = response.getOutputStream();
71  
72              while ((bytesRead = input.read(buffer)) != -1) {
73                  out.write(buffer, 0, bytesRead);
74              }
75          }
76  
77          return null;
78      }
79  }