View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  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,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.http.impl.client.cache;
28  
29  import java.io.File;
30  import java.io.FileOutputStream;
31  import java.io.IOException;
32  import java.io.InputStream;
33  
34  import org.apache.http.annotation.Contract;
35  import org.apache.http.annotation.ThreadingBehavior;
36  import org.apache.http.client.cache.InputLimit;
37  import org.apache.http.client.cache.Resource;
38  import org.apache.http.client.cache.ResourceFactory;
39  
40  /**
41   * Generates {@link Resource} instances whose body is stored in a temporary file.
42   *
43   * @since 4.1
44   */
45  @Contract(threading = ThreadingBehavior.IMMUTABLE)
46  public class FileResourceFactory implements ResourceFactory {
47  
48      private final File cacheDir;
49      private final BasicIdGenerator idgen;
50  
51      public FileResourceFactory(final File cacheDir) {
52          super();
53          this.cacheDir = cacheDir;
54          this.idgen = new BasicIdGenerator();
55      }
56  
57      private File generateUniqueCacheFile(final String requestId) {
58          final StringBuilder buffer = new StringBuilder();
59          this.idgen.generate(buffer);
60          buffer.append('.');
61          final int len = Math.min(requestId.length(), 100);
62          for (int i = 0; i < len; i++) {
63              final char ch = requestId.charAt(i);
64              if (Character.isLetterOrDigit(ch) || ch == '.') {
65                  buffer.append(ch);
66              } else {
67                  buffer.append('-');
68              }
69          }
70          return new File(this.cacheDir, buffer.toString());
71      }
72  
73      @Override
74      public Resource generate(
75              final String requestId,
76              final InputStream instream,
77              final InputLimit limit) throws IOException {
78          final File file = generateUniqueCacheFile(requestId);
79          final FileOutputStream outstream = new FileOutputStream(file);
80          try {
81              final byte[] buf = new byte[2048];
82              long total = 0;
83              int l;
84              while ((l = instream.read(buf)) != -1) {
85                  outstream.write(buf, 0, l);
86                  total += l;
87                  if (limit != null && total > limit.getValue()) {
88                      limit.reached();
89                      break;
90                  }
91              }
92          } finally {
93              outstream.close();
94          }
95          return new FileResource(file);
96      }
97  
98      @Override
99      public Resource copy(
100             final String requestId,
101             final Resource resource) throws IOException {
102         final File file = generateUniqueCacheFile(requestId);
103 
104         if (resource instanceof FileResource) {
105             final File src = ((FileResource) resource).getFile();
106             IOUtils.copyFile(src, file);
107         } else {
108             final FileOutputStream out = new FileOutputStream(file);
109             IOUtils.copyAndClose(resource.getInputStream(), out);
110         }
111         return new FileResource(file);
112     }
113 
114 }