1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
42
43
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 }