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.FileNotFoundException;
28 import java.io.FileOutputStream;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.io.OutputStream;
32 import java.io.OutputStreamWriter;
33 import java.io.Writer;
34 import java.nio.ByteBuffer;
35 import java.nio.channels.FileChannel;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.HashSet;
42 import java.util.Map.Entry;
43 import java.util.NavigableMap;
45 import java.util.Timer;
46 import java.util.TimerTask;
47 import java.util.TreeMap;
48 import java.util.concurrent.ConcurrentSkipListMap;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpServletResponse;
55 import org.onap.aaf.misc.env.Env;
56 import org.onap.aaf.misc.env.EnvJAXB;
57 import org.onap.aaf.misc.env.LogTarget;
58 import org.onap.aaf.misc.env.Store;
59 import org.onap.aaf.misc.env.TimeTaken;
60 import org.onap.aaf.misc.env.Trans;
64 * Author: Jonathan Gathman, Gathsys 2010
67 public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void> {
68 public static void setEnv(Store store, String[] args) {
69 for(int i=0;i<args.length-1;i+=2) { // cover two parms required for each
70 if(CFA_WEB_PATH.equals(args[i])) {
71 store.put(store.staticSlot(CFA_WEB_PATH), args[i+1]);
72 } else if(CFA_CACHE_CHECK_INTERVAL.equals(args[i])) {
73 store.put(store.staticSlot(CFA_CACHE_CHECK_INTERVAL), Long.parseLong(args[i+1]));
74 } else if(CFA_MAX_SIZE.equals(args[i])) {
75 store.put(store.staticSlot(CFA_MAX_SIZE), Integer.parseInt(args[i+1]));
80 private static String MAX_AGE = "max-age=3600"; // 1 hour Caching
81 private final Map<String,String> typeMap;
82 private final NavigableMap<String,Content> content;
83 private final Set<String> attachOnly;
84 public final static String CFA_WEB_PATH = "aaf_cfa_web_path";
85 // when to re-validate from file
86 // Re validating means comparing the Timestamp on the disk, and seeing it has changed. Cache is not marked
87 // dirty unless file has changed, but it still makes File IO, which for some kinds of cached data, i.e.
88 // deployed GUI elements is unnecessary, and wastes time.
89 // This parameter exists to cover the cases where data can be more volatile, so the user can choose how often the
90 // File IO will be accessed, based on probability of change. "0", of course, means, check every time.
91 private final static String CFA_CACHE_CHECK_INTERVAL = "aaf_cfa_cache_check_interval";
92 private final static String CFA_MAX_SIZE = "aaf_cfa_max_size"; // Cache size limit
93 private final static String CFA_CLEAR_COMMAND = "aaf_cfa_clear_command";
95 // Note: can be null without a problem, but included
96 // to tie in with existing Logging.
97 public LogTarget logT = null;
98 public long checkInterval; // = 600000L; // only check if not hit in 10 mins by default
99 public int maxItemSize; // = 512000; // max file 500k
101 private String web_path;
102 // A command key is set in the Properties, preferably changed on deployment.
103 // it is compared at the beginning of the path, and if so, it is assumed to issue certain commands
104 // It's purpose is to protect, to some degree the command, even though it is HTTP, allowing
105 // local batch files to, for instance, clear caches on resetting of files.
106 private String clear_command;
108 public CachingFileAccess(EnvJAXB env, String ... args) throws IOException {
109 super(null,"Caching File Access");
111 content = new ConcurrentSkipListMap<>(); // multi-thread changes possible
113 attachOnly = new HashSet<>(); // short, unchanged
115 typeMap = new TreeMap<>(); // Structure unchanged after Construction
116 typeMap.put("ico","image/icon");
117 typeMap.put("html","text/html");
118 typeMap.put("css","text/css");
119 typeMap.put("js","text/javascript");
120 typeMap.put("txt","text/plain");
121 typeMap.put("xml","text/xml");
122 typeMap.put("xsd","text/xml");
123 attachOnly.add("xsd");
124 typeMap.put("crl", "application/x-pkcs7-crl");
125 typeMap.put("appcache","text/cache-manifest");
127 typeMap.put("json","text/json");
128 typeMap.put("ogg", "audio/ogg");
129 typeMap.put("jpg","image/jpeg");
130 typeMap.put("gif","image/gif");
131 typeMap.put("png","image/png");
132 typeMap.put("svg","image/svg+xml");
133 typeMap.put("jar","application/x-java-applet");
134 typeMap.put("jnlp", "application/x-java-jnlp-file");
135 typeMap.put("class", "application/java");
136 typeMap.put("props", "text/plain");
137 typeMap.put("jks", "application/octet-stream");
139 timer = new Timer("Caching Cleanup",true);
140 timer.schedule(new Cleanup(content,500),60000,60000);
143 web_path = env.get(env.staticSlot(CFA_WEB_PATH));
144 env.init().log("CachingFileAccess path: " + new File(web_path).getCanonicalPath());
146 obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L); // Default is 10 mins
147 if(obj instanceof Long) {checkInterval=(Long)obj;
148 } else {checkInterval=Long.parseLong((String)obj);}
150 obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000); // Default is max file 500k
151 if(obj instanceof Integer) {maxItemSize=(Integer)obj;
152 } else {maxItemSize =Integer.parseInt((String)obj);}
154 clear_command = env.getProperty(CFA_CLEAR_COMMAND,null);
160 public void handle(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException {
161 String key = pathParam(req, ":key");
162 String cmd = pathParam(req,":cmd");
163 if(key.equals(clear_command)) {
164 resp.setHeader("Content-Type",typeMap.get("txt"));
165 if("clear".equals(cmd)) {
167 resp.setStatus(200/*HttpStatus.OK_200*/);
169 resp.setStatus(400/*HttpStatus.BAD_REQUEST_400 */);
173 Content c = load(logT , web_path,cmd!=null && cmd.length()>0?key+'/'+cmd:key, null, checkInterval);
174 if(c.attachmentOnly) {
175 resp.setHeader("Content-disposition", "attachment");
178 c.write(resp.getOutputStream());
179 trans.checkpoint(req.getPathInfo());
183 public String webPath() {
188 * Reset the Cleanup size and interval
190 * The size and interval when started are 500 items (memory size unknown) checked every minute in a background thread.
195 public void cleanupParams(int size, long interval) {
198 timer.schedule(new Cleanup(content,size), interval, interval);
204 * Load a file, first checking cache
207 * @param logTarget - logTarget can be null (won't log)
208 * @param dataRoot - data root storage directory
209 * @param key - relative File Path
210 * @param mediaType - what kind of file is it. If null, will check via file extension
211 * @param timeCheck - "-1" will take system default - Otherwise, will compare "now" + timeCheck(Millis) before looking at File mod
213 * @throws IOException
215 public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException {
216 long timeCheck = _timeCheck;
218 timeCheck=checkInterval; // if time < 0, then use default
222 if("-".equals(key)) {
226 fileName=dataRoot + '/' + key;
229 Content c = content.get(key);
230 long systime = System.currentTimeMillis();
233 // Don't check every hit... only after certain time value
234 if(c.date < systime + timeCheck) {
235 f = new File(fileName);
236 if(f.lastModified()>c.date) {
242 if(logTarget!=null) {
243 logTarget.log("File Read: ",key);
247 f = new File(fileName);
251 if(f.isDirectory()) {
253 c = new DirectoryContent(f,isRoot);
255 if(f.length() > maxItemSize) {
256 c = new DirectFileContent(f);
259 c = new CachedContent(f);
260 cacheMe = checkInterval>0;
263 if(mediaType==null) { // determine from file Ending
264 int idx = key.lastIndexOf('.');
265 String subkey = key.substring(++idx);
266 if((c.contentType = idx<0?null:typeMap.get(subkey))==null) {
267 // if nothing else, just set to default type...
268 c.contentType = "application/octet-stream";
270 c.attachmentOnly = attachOnly.contains(subkey);
272 c.contentType=mediaType;
273 c.attachmentOnly = false;
276 c.date = f.lastModified();
286 if(logTarget!=null)logTarget.log("Cache Read: ",key);
294 public Content loadOrDefault(Trans trans, String targetDir, String targetFileName, String sourcePath, String mediaType) throws IOException {
296 return load(trans.info(),targetDir,targetFileName,mediaType,0);
297 } catch(FileNotFoundException e) {
298 String targetPath = targetDir + '/' + targetFileName;
299 TimeTaken tt = trans.start("File doesn't exist; copy " + sourcePath + " to " + targetPath, Env.SUB);
301 FileInputStream sourceFIS = new FileInputStream(sourcePath);
302 FileChannel sourceFC = sourceFIS.getChannel();
303 File targetFile = new File(targetPath);
304 targetFile.getParentFile().mkdirs(); // ensure directory exists
305 FileOutputStream targetFOS = new FileOutputStream(targetFile);
307 ByteBuffer bb = ByteBuffer.allocate((int)sourceFC.size());
309 bb.flip(); // ready for reading
310 targetFOS.getChannel().write(bb);
318 return load(trans.info(),targetDir,targetFileName,mediaType,0);
322 public void invalidate(String key) {
326 private static final Content NULL=new Content() {
329 public void setHeader(HttpServletResponse resp) {
330 resp.setStatus(404/*NOT_FOUND_404*/);
331 resp.setHeader("Content-type","text/plain");
335 public void write(Writer writer) throws IOException {
339 public void write(OutputStream os) throws IOException {
344 private static abstract class Content {
345 private long date; // date of the actual artifact (i.e. File modified date)
346 private long access; // last accessed
348 protected String contentType;
349 protected boolean attachmentOnly;
351 public void setHeader(HttpServletResponse resp) {
352 resp.setStatus(200/*OK_200*/);
353 resp.setHeader("Content-Type",contentType);
354 resp.setHeader("Cache-Control", MAX_AGE);
357 public abstract void write(Writer writer) throws IOException;
358 public abstract void write(OutputStream os) throws IOException;
362 private static class DirectFileContent extends Content {
364 public DirectFileContent(File f) {
368 public String toString() {
369 return file.getName();
372 public void write(Writer writer) throws IOException {
373 FileReader fr = new FileReader(file);
374 char[] buff = new char[1024];
377 while((read = fr.read(buff,0,1024))>=0) {
378 writer.write(buff,0,read);
385 public void write(OutputStream os) throws IOException {
386 FileInputStream fis = new FileInputStream(file);
387 byte[] buff = new byte[1024];
390 while((read = fis.read(buff,0,1024))>=0) {
391 os.write(buff,0,read);
399 private static class DirectoryContent extends Content {
400 private static final Pattern A_NUMBER = Pattern.compile("\\d");
401 private static final String H1 = "<html><head><title>AAF Fileserver</title></head><body><h1>AAF Fileserver</h1><h2>";
402 private static final String H2 = "</h2><ul>\n";
403 private static final String F = "\n</ul></body></html>";
404 private File[] files;
406 private boolean notRoot;
408 public DirectoryContent(File directory, boolean isRoot) {
411 files = directory.listFiles();
412 Arrays.sort(files,new Comparator<File>() {
414 public int compare(File f1, File f2) {
415 // See if there are Numbers in the name
416 Matcher m1 = A_NUMBER.matcher(f1.getName());
417 Matcher m2 = A_NUMBER.matcher(f2.getName());
418 if(m1.find() && m2.find()) {
419 // if numbers, are the numbers in the same start position
423 // If same start position and the text is the same, then reverse sort
424 if(i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) {
425 // reverse sort files that start similarly, but have numbers in them
426 return f2.compareTo(f1);
429 return f1.compareTo(f2);
433 name = directory.getName();
434 attachmentOnly = false;
435 contentType = "text/html";
440 public void write(Writer w) throws IOException {
444 for (File f : files) {
445 w.append("<li><a href=\"");
450 w.append(f.getName());
452 w.append(f.getName());
453 w.append("</a></li>\n");
460 public void write(OutputStream os) throws IOException {
461 write(new OutputStreamWriter(os));
466 private static class CachedContent extends Content {
469 private char[] cdata;
471 public CachedContent(File f) throws IOException {
473 ByteBuffer bb = ByteBuffer.allocate((int)f.length());
474 FileInputStream fis = new FileInputStream(f);
476 fis.getChannel().read(bb);
486 public String toString() {
487 return Arrays.toString(data);
490 public void write(Writer writer) throws IOException {
492 // do the String Transformation once, and only if actually used
494 cdata = new char[end];
495 new String(data).getChars(0, end, cdata, 0);
498 writer.write(cdata,0,end);
500 public void write(OutputStream os) throws IOException {
501 os.write(data,0,end);
506 public void setEnv(LogTarget env) {
511 * Cleanup thread to remove older items if max Cache is reached.
515 private static class Cleanup extends TimerTask {
517 private NavigableMap<String, Content> content;
519 public Cleanup(NavigableMap<String, Content> content, int size) {
521 this.content = content;
524 private class Comp implements Comparable<Comp> {
525 public Map.Entry<String, Content> entry;
527 public Comp(Map.Entry<String, Content> en) {
532 public int compareTo(Comp o) {
533 return (int)(entry.getValue().access-o.entry.getValue().access);
537 @SuppressWarnings("unchecked")
540 int size = content.size();
542 ArrayList<Comp> scont = new ArrayList<>(size);
543 Object[] entries = content.entrySet().toArray();
544 for(int i=0;i<size;++i) {
545 scont.add(i, new Comp((Map.Entry<String,Content>)entries[i]));
547 Collections.sort(scont);
548 int end = size - ((maxSize/4)*3); // reduce to 3/4 of max size
549 //System.out.println("------ Cleanup Cycle ------ " + new Date().toString() + " -------");
550 for(int i=0;i<end;++i) {
551 Entry<String, Content> entry = scont.get(i).entry;
552 content.remove(entry.getKey());
553 //System.out.println("removed Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString());
555 // for(int i=end;i<size;++i) {
556 // Entry<String, Content> entry = scont.get(i).entry;
557 // //System.out.println("remaining Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString());