2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.auth.rserv;
26 import java.io.FileInputStream;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.io.OutputStreamWriter;
31 import java.io.Writer;
32 import java.nio.ByteBuffer;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Collections;
36 import java.util.Comparator;
37 import java.util.HashSet;
39 import java.util.Map.Entry;
40 import java.util.NavigableMap;
42 import java.util.Timer;
43 import java.util.TimerTask;
44 import java.util.TreeMap;
45 import java.util.concurrent.ConcurrentSkipListMap;
46 import java.util.regex.Matcher;
47 import java.util.regex.Pattern;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
52 import org.onap.aaf.misc.env.EnvJAXB;
53 import org.onap.aaf.misc.env.LogTarget;
54 import org.onap.aaf.misc.env.Store;
55 import org.onap.aaf.misc.env.Trans;
59 * Author: Jonathan Gathman, Gathsys 2010
62 public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void> {
63 public static void setEnv(Store store, String[] args) {
64 for (int i=0;i<args.length-1;i+=2) { // cover two parms required for each
65 if (CFA_WEB_PATH.equals(args[i])) {
66 store.put(store.staticSlot(CFA_WEB_PATH), args[i+1]);
67 } else if (CFA_CACHE_CHECK_INTERVAL.equals(args[i])) {
68 store.put(store.staticSlot(CFA_CACHE_CHECK_INTERVAL), Long.parseLong(args[i+1]));
69 } else if (CFA_MAX_SIZE.equals(args[i])) {
70 store.put(store.staticSlot(CFA_MAX_SIZE), Integer.parseInt(args[i+1]));
75 private static String maxAge = "max-age=3600"; // 1 hour Caching
76 private final Map<String,String> typeMap;
77 private final NavigableMap<String,Content> content;
78 private final Set<String> attachOnly;
79 public static final String CFA_WEB_PATH = "aaf_cfa_web_path";
80 // when to re-validate from file
81 // Re validating means comparing the Timestamp on the disk, and seeing it has changed. Cache is not marked
82 // dirty unless file has changed, but it still makes File IO, which for some kinds of cached data, i.e.
83 // deployed GUI elements is unnecessary, and wastes time.
84 // This parameter exists to cover the cases where data can be more volatile, so the user can choose how often the
85 // File IO will be accessed, based on probability of change. "0", of course, means, check every time.
86 private static final String CFA_CACHE_CHECK_INTERVAL = "aaf_cfa_cache_check_interval";
87 private static final String CFA_MAX_SIZE = "aaf_cfa_max_size"; // Cache size limit
88 private static final String CFA_CLEAR_COMMAND = "aaf_cfa_clear_command";
90 // Note: can be null without a problem, but included
91 // to tie in with existing Logging.
92 public LogTarget logT = null;
93 public long checkInterval; // = 600000L; // only check if not hit in 10 mins by default
94 public int maxItemSize; // = 512000; // max file 500k
96 private String webPath;
97 // A command key is set in the Properties, preferably changed on deployment.
98 // it is compared at the beginning of the path, and if so, it is assumed to issue certain commands
99 // It's purpose is to protect, to some degree the command, even though it is HTTP, allowing
100 // local batch files to, for instance, clear caches on resetting of files.
101 private String clearCommand;
103 public static final String TEXT_PLAIN = "text/plain";
105 public CachingFileAccess(EnvJAXB env, String ... args) throws IOException {
106 super(null,"Caching File Access");
108 content = new ConcurrentSkipListMap<>(); // multi-thread changes possible
110 attachOnly = new HashSet<>(); // short, unchanged
112 typeMap = new TreeMap<>(); // Structure unchanged after Construction
113 typeMap.put("ico","image/icon");
114 typeMap.put("html","text/html");
115 typeMap.put("css","text/css");
116 typeMap.put("js","text/javascript");
117 typeMap.put("txt", TEXT_PLAIN);
118 typeMap.put("xml","text/xml");
119 typeMap.put("xsd","text/xml");
120 attachOnly.add("xsd");
121 typeMap.put("crl", "application/x-pkcs7-crl");
122 typeMap.put("appcache","text/cache-manifest");
124 typeMap.put("json","text/json");
125 typeMap.put("ogg", "audio/ogg");
126 typeMap.put("jpg","image/jpeg");
127 typeMap.put("gif","image/gif");
128 typeMap.put("png","image/png");
129 typeMap.put("svg","image/svg+xml");
130 typeMap.put("jar","application/x-java-applet");
131 typeMap.put("jnlp", "application/x-java-jnlp-file");
132 typeMap.put("class", "application/java");
133 typeMap.put("props", TEXT_PLAIN);
134 typeMap.put("jks", "application/octet-stream");
137 typeMap.put("ttf","font/ttf");
138 typeMap.put("woff","font/woff");
139 typeMap.put("woff2","font/woff2");
142 timer = new Timer("Caching Cleanup",true);
143 timer.schedule(new Cleanup(content,500),60000,60000);
146 webPath = env.get(env.staticSlot(CFA_WEB_PATH));
147 env.init().log("CachingFileAccess path: " + new File(webPath).getCanonicalPath());
149 obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L); // Default is 10 mins
150 if (obj instanceof Long) {
151 checkInterval=(Long)obj;
153 checkInterval=Long.parseLong((String)obj);
156 obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000); // Default is max file 500k
157 if (obj instanceof Integer) {
158 maxItemSize=(Integer)obj;
160 maxItemSize =Integer.parseInt((String)obj);
163 clearCommand = env.getProperty(CFA_CLEAR_COMMAND,null);
169 public void handle(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException {
170 String key = pathParam(req, ":key");
171 int slash = key.indexOf('/');
172 if(key.length()>2 && slash>=0 && key.substring(0,slash).equals(clearCommand)) {
173 resp.setHeader("Content-Type",typeMap.get("txt"));
174 if ("clear".equals(key.substring(slash+1))) {
176 resp.setStatus(200/*HttpStatus.OK_200*/);
178 resp.setStatus(400/*HttpStatus.BAD_REQUEST_400 */);
182 Content c = load(logT , webPath,key, null, checkInterval);
183 if (c.attachmentOnly) {
184 resp.setHeader("Content-disposition", "attachment");
187 c.write(resp.getOutputStream());
188 trans.checkpoint(req.getPathInfo());
192 public String webPath() {
197 * Reset the Cleanup size and interval
199 * The size and interval when started are 500 items (memory size unknown) checked every minute in a background thread.
204 public void cleanupParams(int size, long interval) {
207 timer.schedule(new Cleanup(content,size), interval, interval);
213 * Load a file, first checking cache
216 * @param logTarget - logTarget can be null (won't log)
217 * @param dataRoot - data root storage directory
218 * @param key - relative File Path
219 * @param mediaType - what kind of file is it. If null, will check via file extension
220 * @param timeCheck - "-1" will take system default - Otherwise, will compare "now" + timeCheck(Millis) before looking at File mod
222 * @throws IOException
224 public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException {
225 long timeCheck = _timeCheck;
227 timeCheck=checkInterval; // if time < 0, then use default
231 if ("-".equals(key)) {
235 fileName=dataRoot + '/' + key;
238 Content c = content.get(key);
239 long systime = System.currentTimeMillis();
242 // Don't check every hit... only after certain time value
243 if (c.date < systime + timeCheck) {
244 f = new File(fileName);
245 if (f.lastModified()>c.date) {
251 if (logTarget!=null) {
252 logTarget.log("File Read: ",key);
256 f = new File(fileName);
260 if (f.isDirectory()) {
262 c = new DirectoryContent(f,isRoot);
264 if (f.length() > maxItemSize) {
265 c = new DirectFileContent(f);
268 c = new CachedContent(f);
269 cacheMe = checkInterval>0;
272 if (mediaType==null) { // determine from file Ending
273 int idx = key.lastIndexOf('.');
274 String subkey = key.substring(++idx);
275 if ((c.contentType = idx<0?null:typeMap.get(subkey))==null) {
276 // if nothing else, just set to default type...
277 c.contentType = "application/octet-stream";
279 c.attachmentOnly = attachOnly.contains(subkey);
281 c.contentType=mediaType;
282 c.attachmentOnly = false;
285 c.date = f.lastModified();
295 if (logTarget!=null)logTarget.log("Cache Read: ",key);
304 public void invalidate(String key) {
308 private static final Content NULL=new Content() {
311 public void setHeader(HttpServletResponse resp) {
312 resp.setStatus(404/*NOT_FOUND_404*/);
313 resp.setHeader("Content-type",TEXT_PLAIN);
317 public void write(Writer writer) throws IOException {
321 public void write(OutputStream os) throws IOException {
326 private abstract static class Content {
327 private long date; // date of the actual artifact (i.e. File modified date)
328 private long access; // last accessed
330 protected String contentType;
331 protected boolean attachmentOnly;
333 public void setHeader(HttpServletResponse resp) {
334 resp.setStatus(200/*OK_200*/);
335 resp.setHeader("Content-Type",contentType);
336 resp.setHeader("Cache-Control", maxAge);
339 public abstract void write(Writer writer) throws IOException;
340 public abstract void write(OutputStream os) throws IOException;
344 private static class DirectFileContent extends Content {
346 public DirectFileContent(File f) {
350 public String toString() {
351 return file.getName();
354 public void write(Writer writer) throws IOException {
355 FileReader fr = new FileReader(file);
356 char[] buff = new char[1024];
359 while ((read = fr.read(buff,0,1024))>=0) {
360 writer.write(buff,0,read);
367 public void write(OutputStream os) throws IOException {
368 FileInputStream fis = new FileInputStream(file);
369 byte[] buff = new byte[1024];
372 while ((read = fis.read(buff,0,1024))>=0) {
373 os.write(buff,0,read);
381 private static class DirectoryContent extends Content {
382 private static final Pattern A_NUMBER = Pattern.compile("\\d");
383 private static final String H1 = "<html><head><title>AAF Fileserver</title></head><body><h1>AAF Fileserver</h1><h2>";
384 private static final String H2 = "</h2><ul>\n";
385 private static final String F = "\n</ul></body></html>";
386 private File[] files;
388 private boolean notRoot;
390 public DirectoryContent(File directory, boolean isRoot) {
393 files = directory.listFiles();
394 Arrays.sort(files,new Comparator<File>() {
396 public int compare(File f1, File f2) {
397 // See if there are Numbers in the name
398 Matcher m1 = A_NUMBER.matcher(f1.getName());
399 Matcher m2 = A_NUMBER.matcher(f2.getName());
400 if (m1.find() && m2.find()) {
401 // if numbers, are the numbers in the same start position
405 // If same start position and the text is the same, then reverse sort
406 if (i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) {
407 // reverse sort files that start similarly, but have numbers in them
408 return f2.compareTo(f1);
411 return f1.compareTo(f2);
415 name = directory.getName();
416 attachmentOnly = false;
417 contentType = "text/html";
422 public void write(Writer w) throws IOException {
426 for (File f : files) {
427 w.append("<li><a href=\"");
432 w.append(f.getName());
434 w.append(f.getName());
435 w.append("</a></li>\n");
442 public void write(OutputStream os) throws IOException {
443 write(new OutputStreamWriter(os));
448 private static class CachedContent extends Content {
451 private char[] cdata;
453 public CachedContent(File f) throws IOException {
455 ByteBuffer bb = ByteBuffer.allocate((int)f.length());
456 FileInputStream fis = new FileInputStream(f);
458 fis.getChannel().read(bb);
468 public String toString() {
469 return Arrays.toString(data);
472 public void write(Writer writer) throws IOException {
474 // do the String Transformation once, and only if actually used
476 cdata = new char[end];
477 new String(data).getChars(0, end, cdata, 0);
480 writer.write(cdata,0,end);
482 public void write(OutputStream os) throws IOException {
483 os.write(data,0,end);
488 public void setEnv(LogTarget env) {
493 * Cleanup thread to remove older items if max Cache is reached.
497 private static class Cleanup extends TimerTask {
499 private NavigableMap<String, Content> content;
501 public Cleanup(NavigableMap<String, Content> content, int size) {
503 this.content = content;
506 private class Comp implements Comparable<Comp> {
507 public Map.Entry<String, Content> entry;
509 public Comp(Map.Entry<String, Content> en) {
514 public int compareTo(Comp o) {
515 return (int)(entry.getValue().access-o.entry.getValue().access);
519 @SuppressWarnings("unchecked")
522 int size = content.size();
524 ArrayList<Comp> scont = new ArrayList<>(size);
525 Object[] entries = content.entrySet().toArray();
526 for (int i=0;i<size;++i) {
527 scont.add(i, new Comp((Map.Entry<String,Content>)entries[i]));
529 Collections.sort(scont);
530 int end = size - ((maxSize/4)*3); // reduce to 3/4 of max size
531 for (int i=0;i<end;++i) {
532 Entry<String, Content> entry = scont.get(i).entry;
533 content.remove(entry.getKey());