View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.thumbnail.impl;
17  
18  import java.io.BufferedReader;
19  import java.io.File;
20  import java.io.InputStreamReader;
21  import java.nio.charset.Charset;
22  import java.util.ArrayList;
23  import java.util.List;
24  import java.util.Timer;
25  import java.util.TimerTask;
26  import java.util.concurrent.TimeUnit;
27  
28  import javax.annotation.PostConstruct;
29  
30  import org.codelibs.core.io.CloseableUtil;
31  import org.codelibs.core.io.CopyUtil;
32  import org.codelibs.core.lang.StringUtil;
33  import org.slf4j.Logger;
34  import org.slf4j.LoggerFactory;
35  
36  public class CommandGenerator extends BaseThumbnailGenerator {
37      private static final Logger logger = LoggerFactory.getLogger(CommandGenerator.class);
38  
39      protected List<String> commandList;
40  
41      protected long commandTimeout = 30 * 1000L;// 30sec
42  
43      protected long commandDestroyTimeout = 5 * 1000L;// 5sec
44  
45      protected File baseDir;
46  
47      private volatile Timer destoryTimer;
48  
49      @PostConstruct
50      public void init() {
51          if (baseDir == null) {
52              baseDir = new File(System.getProperty("java.io.tmpdir"));
53          }
54          destoryTimer = new Timer("CommandGeneratorDestoryTimer-" + System.currentTimeMillis(), true);
55      }
56  
57      @Override
58      public void destroy() {
59          destoryTimer.cancel();
60          destoryTimer = null;
61      }
62  
63      @Override
64      public boolean generate(final String thumbnailId, final File outputFile) {
65          if (logger.isDebugEnabled()) {
66              logger.debug("Generate Thumbnail: " + thumbnailId);
67          }
68  
69          if (outputFile.exists()) {
70              if (logger.isDebugEnabled()) {
71                  logger.debug("The thumbnail file exists: " + outputFile.getAbsolutePath());
72              }
73              return true;
74          }
75  
76          final File parentFile = outputFile.getParentFile();
77          if (!parentFile.exists()) {
78              parentFile.mkdirs();
79          }
80          if (!parentFile.isDirectory()) {
81              logger.warn("Not found: " + parentFile.getAbsolutePath());
82              return false;
83          }
84  
85          return process(thumbnailId, responseData -> {
86              File tempFile = null;
87              try {
88                  tempFile = File.createTempFile("thumbnail_", "");
89                  CopyUtil.copy(responseData.getResponseBody(), tempFile);
90  
91                  final String tempPath = tempFile.getAbsolutePath();
92                  final String outputPath = outputFile.getAbsolutePath();
93                  final List<String> cmdList = new ArrayList<>();
94                  for (final String value : commandList) {
95                      cmdList.add(expandPath(value.replace("${url}", tempPath).replace("${outputFile}", outputPath)));
96                  }
97  
98                  executeCommand(thumbnailId, cmdList);
99  
100                 if (outputFile.isFile() && outputFile.length() == 0) {
101                     logger.warn("Thumbnail File is empty. ID is " + thumbnailId);
102                     if (outputFile.delete()) {
103                         logger.info("Deleted: " + outputFile.getAbsolutePath());
104                     }
105                     updateThumbnailField(thumbnailId, StringUtil.EMPTY);
106                     return false;
107                 }
108 
109                 if (logger.isDebugEnabled()) {
110                     logger.debug("Thumbnail File: " + outputPath);
111                 }
112                 return true;
113             } catch (final Exception e) {
114                 logger.warn("Failed to process ", e);
115                 updateThumbnailField(thumbnailId, StringUtil.EMPTY);
116                 return false;
117             } finally {
118                 if (tempFile != null && !tempFile.delete()) {
119                     logger.debug("Failed to delete " + tempFile.getAbsolutePath());
120                 }
121             }
122         });
123 
124     }
125 
126     protected void executeCommand(final String thumbnailId, final List<String> cmdList) {
127         ProcessBuilder pb = null;
128         Process p = null;
129 
130         if (logger.isDebugEnabled()) {
131             logger.debug("Thumbnail Command: " + cmdList);
132         }
133 
134         TimerTask task = null;
135         try {
136             pb = new ProcessBuilder(cmdList);
137             pb.directory(baseDir);
138             pb.redirectErrorStream(true);
139 
140             p = pb.start();
141 
142             task = new ProcessDestroyer(p, cmdList, commandTimeout);
143             try {
144                 destoryTimer.schedule(task, commandTimeout);
145 
146                 String line;
147                 BufferedReader br = null;
148                 try {
149                     br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset()));
150                     while ((line = br.readLine()) != null) {
151                         if (logger.isDebugEnabled()) {
152                             logger.debug(line);
153                         }
154                     }
155                 } finally {
156                     CloseableUtil.closeQuietly(br);
157                 }
158 
159                 p.waitFor();
160             } catch (final Exception e) {
161                 p.destroy();
162             }
163         } catch (final Exception e) {
164             logger.warn("Failed to generate a thumbnail of " + thumbnailId, e);
165         }
166         if (task != null) {
167             task.cancel();
168             task = null;
169         }
170     }
171 
172     protected static class ProcessDestroyer extends TimerTask {
173 
174         private final Process p;
175 
176         private final List<String> commandList;
177 
178         private final long timeout;
179 
180         protected ProcessDestroyer(final Process p, final List<String> commandList, final long timeout) {
181             this.p = p;
182             this.commandList = commandList;
183             this.timeout = timeout;
184         }
185 
186         @Override
187         public void run() {
188             logger.warn("CommandGenerator is timed out: " + commandList);
189             try {
190                 p.destroyForcibly().waitFor(timeout, TimeUnit.MILLISECONDS);
191             } catch (final Exception e) {
192                 logger.warn("Failed to stop destroyer.", e);
193             }
194         }
195     }
196 
197     public void setCommandList(final List<String> commandList) {
198         this.commandList = commandList;
199     }
200 
201     public void setCommandTimeout(final long commandTimeout) {
202         this.commandTimeout = commandTimeout;
203     }
204 
205     public void setBaseDir(final File baseDir) {
206         this.baseDir = baseDir;
207     }
208 
209     public void setCommandDestroyTimeout(final long commandDestroyTimeout) {
210         this.commandDestroyTimeout = commandDestroyTimeout;
211     }
212 
213 }