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.hc.client5.http.impl.cache;
28  
29  import java.io.File;
30  import java.io.FileOutputStream;
31  import java.io.IOException;
32  import java.io.InputStream;
33  import java.io.RandomAccessFile;
34  import java.nio.channels.FileChannel;
35  
36  import org.apache.hc.client5.http.cache.Resource;
37  import org.apache.hc.client5.http.cache.ResourceFactory;
38  import org.apache.hc.client5.http.cache.ResourceIOException;
39  import org.apache.hc.core5.annotation.Contract;
40  import org.apache.hc.core5.annotation.ThreadingBehavior;
41  import org.apache.hc.core5.util.Args;
42  
43  /**
44   * Generates {@link Resource} instances whose body is stored in a temporary file.
45   *
46   * @since 4.1
47   */
48  @Contract(threading = ThreadingBehavior.STATELESS)
49  public class FileResourceFactory implements ResourceFactory {
50  
51      private final File cacheDir;
52      private final BasicIdGenerator idgen;
53  
54      public FileResourceFactory(final File cacheDir) {
55          super();
56          this.cacheDir = cacheDir;
57          this.idgen = new BasicIdGenerator();
58      }
59  
60      private File generateUniqueCacheFile(final String requestId) {
61          final StringBuilder buffer = new StringBuilder();
62          this.idgen.generate(buffer);
63          buffer.append('.');
64          final int len = Math.min(requestId.length(), 100);
65          for (int i = 0; i < len; i++) {
66              final char ch = requestId.charAt(i);
67              if (Character.isLetterOrDigit(ch) || ch == '.') {
68                  buffer.append(ch);
69              } else {
70                  buffer.append('-');
71              }
72          }
73          return new File(this.cacheDir, buffer.toString());
74      }
75  
76      @Override
77      public Resource generate(
78              final String requestId,
79              final byte[] content, final int off, final int len) throws ResourceIOException {
80          Args.notNull(requestId, "Request id");
81          final File file = generateUniqueCacheFile(requestId);
82          try (FileOutputStream outStream = new FileOutputStream(file)) {
83              if (content != null) {
84                  outStream.write(content, off, len);
85              }
86          } catch (final IOException ex) {
87              throw new ResourceIOException(ex.getMessage(), ex);
88          }
89          return new FileResource(file);
90      }
91  
92      @Override
93      public Resource generate(final String requestId, final byte[] content) throws ResourceIOException {
94          Args.notNull(content, "Content");
95          return generate(requestId, content, 0, content.length);
96      }
97  
98      @Override
99      public Resource copy(
100             final String requestId,
101             final Resource resource) throws ResourceIOException {
102         final File file = generateUniqueCacheFile(requestId);
103         try {
104             if (resource instanceof FileResource) {
105                 try (final RandomAccessFile srcFile = new RandomAccessFile(((FileResource) resource).getFile(), "r");
106                      final RandomAccessFile dstFile = new RandomAccessFile(file, "rw");
107                      final FileChannel src = srcFile.getChannel();
108                      final FileChannel dst = dstFile.getChannel()) {
109                     src.transferTo(0, srcFile.length(), dst);
110                 }
111             } else {
112                 try (final FileOutputStream out = new FileOutputStream(file);
113                      final InputStream in = resource.getInputStream()) {
114                     final byte[] buf = new byte[2048];
115                     int len;
116                     while ((len = in.read(buf)) != -1) {
117                         out.write(buf, 0, len);
118                     }
119                 }
120             }
121         } catch (final IOException ex) {
122             throw new ResourceIOException(ex.getMessage(), ex);
123         }
124         return new FileResource(file);
125     }
126 
127 }