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 MAX_AGE = "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 final static 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 final static String CFA_CACHE_CHECK_INTERVAL = "aaf_cfa_cache_check_interval";
87 private final static String CFA_MAX_SIZE = "aaf_cfa_max_size"; // Cache size limit
88 private final static 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 web_path;
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 clear_command;
103 public CachingFileAccess(EnvJAXB env, String ... args) throws IOException {
104 super(null,"Caching File Access");
106 content = new ConcurrentSkipListMap<>(); // multi-thread changes possible
108 attachOnly = new HashSet<>(); // short, unchanged
110 typeMap = new TreeMap<>(); // Structure unchanged after Construction
111 typeMap.put("ico","image/icon");
112 typeMap.put("html","text/html");
113 typeMap.put("css","text/css");
114 typeMap.put("js","text/javascript");
115 typeMap.put("txt","text/plain");
116 typeMap.put("xml","text/xml");
117 typeMap.put("xsd","text/xml");
118 attachOnly.add("xsd");
119 typeMap.put("crl", "application/x-pkcs7-crl");
120 typeMap.put("appcache","text/cache-manifest");
122 typeMap.put("json","text/json");
123 typeMap.put("ogg", "audio/ogg");
124 typeMap.put("jpg","image/jpeg");
125 typeMap.put("gif","image/gif");
126 typeMap.put("png","image/png");
127 typeMap.put("svg","image/svg+xml");
128 typeMap.put("jar","application/x-java-applet");
129 typeMap.put("jnlp", "application/x-java-jnlp-file");
130 typeMap.put("class", "application/java");
131 typeMap.put("props", "text/plain");
132 typeMap.put("jks", "application/octet-stream");
134 timer = new Timer("Caching Cleanup",true);
135 timer.schedule(new Cleanup(content,500),60000,60000);
138 web_path = env.get(env.staticSlot(CFA_WEB_PATH));
139 env.init().log("CachingFileAccess path: " + new File(web_path).getCanonicalPath());
141 obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L); // Default is 10 mins
142 if (obj instanceof Long) {checkInterval=(Long)obj;
143 } else {checkInterval=Long.parseLong((String)obj);}
145 obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000); // Default is max file 500k
146 if (obj instanceof Integer) {maxItemSize=(Integer)obj;
147 } else {maxItemSize =Integer.parseInt((String)obj);}
149 clear_command = env.getProperty(CFA_CLEAR_COMMAND,null);
155 public void handle(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException {
156 String key = pathParam(req, ":key");
157 String cmd = pathParam(req,":cmd");
158 if (key.equals(clear_command)) {
159 resp.setHeader("Content-Type",typeMap.get("txt"));
160 if ("clear".equals(cmd)) {
162 resp.setStatus(200/*HttpStatus.OK_200*/);
164 resp.setStatus(400/*HttpStatus.BAD_REQUEST_400 */);
168 Content c = load(logT , web_path,cmd!=null && cmd.length()>0?key+'/'+cmd:key, null, checkInterval);
169 if (c.attachmentOnly) {
170 resp.setHeader("Content-disposition", "attachment");
173 c.write(resp.getOutputStream());
174 trans.checkpoint(req.getPathInfo());
178 public String webPath() {
183 * Reset the Cleanup size and interval
185 * The size and interval when started are 500 items (memory size unknown) checked every minute in a background thread.
190 public void cleanupParams(int size, long interval) {
193 timer.schedule(new Cleanup(content,size), interval, interval);
199 * Load a file, first checking cache
202 * @param logTarget - logTarget can be null (won't log)
203 * @param dataRoot - data root storage directory
204 * @param key - relative File Path
205 * @param mediaType - what kind of file is it. If null, will check via file extension
206 * @param timeCheck - "-1" will take system default - Otherwise, will compare "now" + timeCheck(Millis) before looking at File mod
208 * @throws IOException
210 public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException {
211 long timeCheck = _timeCheck;
213 timeCheck=checkInterval; // if time < 0, then use default
217 if ("-".equals(key)) {
221 fileName=dataRoot + '/' + key;
224 Content c = content.get(key);
225 long systime = System.currentTimeMillis();
228 // Don't check every hit... only after certain time value
229 if (c.date < systime + timeCheck) {
230 f = new File(fileName);
231 if (f.lastModified()>c.date) {
237 if (logTarget!=null) {
238 logTarget.log("File Read: ",key);
242 f = new File(fileName);
246 if (f.isDirectory()) {
248 c = new DirectoryContent(f,isRoot);
250 if (f.length() > maxItemSize) {
251 c = new DirectFileContent(f);
254 c = new CachedContent(f);
255 cacheMe = checkInterval>0;
258 if (mediaType==null) { // determine from file Ending
259 int idx = key.lastIndexOf('.');
260 String subkey = key.substring(++idx);
261 if ((c.contentType = idx<0?null:typeMap.get(subkey))==null) {
262 // if nothing else, just set to default type...
263 c.contentType = "application/octet-stream";
265 c.attachmentOnly = attachOnly.contains(subkey);
267 c.contentType=mediaType;
268 c.attachmentOnly = false;
271 c.date = f.lastModified();
281 if (logTarget!=null)logTarget.log("Cache Read: ",key);
290 public void invalidate(String key) {
294 private static final Content NULL=new Content() {
297 public void setHeader(HttpServletResponse resp) {
298 resp.setStatus(404/*NOT_FOUND_404*/);
299 resp.setHeader("Content-type","text/plain");
303 public void write(Writer writer) throws IOException {
307 public void write(OutputStream os) throws IOException {
312 private static abstract class Content {
313 private long date; // date of the actual artifact (i.e. File modified date)
314 private long access; // last accessed
316 protected String contentType;
317 protected boolean attachmentOnly;
319 public void setHeader(HttpServletResponse resp) {
320 resp.setStatus(200/*OK_200*/);
321 resp.setHeader("Content-Type",contentType);
322 resp.setHeader("Cache-Control", MAX_AGE);
325 public abstract void write(Writer writer) throws IOException;
326 public abstract void write(OutputStream os) throws IOException;
330 private static class DirectFileContent extends Content {
332 public DirectFileContent(File f) {
336 public String toString() {
337 return file.getName();
340 public void write(Writer writer) throws IOException {
341 FileReader fr = new FileReader(file);
342 char[] buff = new char[1024];
345 while ((read = fr.read(buff,0,1024))>=0) {
346 writer.write(buff,0,read);
353 public void write(OutputStream os) throws IOException {
354 FileInputStream fis = new FileInputStream(file);
355 byte[] buff = new byte[1024];
358 while ((read = fis.read(buff,0,1024))>=0) {
359 os.write(buff,0,read);
367 private static class DirectoryContent extends Content {
368 private static final Pattern A_NUMBER = Pattern.compile("\\d");
369 private static final String H1 = "<html><head><title>AAF Fileserver</title></head><body><h1>AAF Fileserver</h1><h2>";
370 private static final String H2 = "</h2><ul>\n";
371 private static final String F = "\n</ul></body></html>";
372 private File[] files;
374 private boolean notRoot;
376 public DirectoryContent(File directory, boolean isRoot) {
379 files = directory.listFiles();
380 Arrays.sort(files,new Comparator<File>() {
382 public int compare(File f1, File f2) {
383 // See if there are Numbers in the name
384 Matcher m1 = A_NUMBER.matcher(f1.getName());
385 Matcher m2 = A_NUMBER.matcher(f2.getName());
386 if (m1.find() && m2.find()) {
387 // if numbers, are the numbers in the same start position
391 // If same start position and the text is the same, then reverse sort
392 if (i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) {
393 // reverse sort files that start similarly, but have numbers in them
394 return f2.compareTo(f1);
397 return f1.compareTo(f2);
401 name = directory.getName();
402 attachmentOnly = false;
403 contentType = "text/html";
408 public void write(Writer w) throws IOException {
412 for (File f : files) {
413 w.append("<li><a href=\"");
418 w.append(f.getName());
420 w.append(f.getName());
421 w.append("</a></li>\n");
428 public void write(OutputStream os) throws IOException {
429 write(new OutputStreamWriter(os));
434 private static class CachedContent extends Content {
437 private char[] cdata;
439 public CachedContent(File f) throws IOException {
441 ByteBuffer bb = ByteBuffer.allocate((int)f.length());
442 FileInputStream fis = new FileInputStream(f);
444 fis.getChannel().read(bb);
454 public String toString() {
455 return Arrays.toString(data);
458 public void write(Writer writer) throws IOException {
460 // do the String Transformation once, and only if actually used
462 cdata = new char[end];
463 new String(data).getChars(0, end, cdata, 0);
466 writer.write(cdata,0,end);
468 public void write(OutputStream os) throws IOException {
469 os.write(data,0,end);
474 public void setEnv(LogTarget env) {
479 * Cleanup thread to remove older items if max Cache is reached.
483 private static class Cleanup extends TimerTask {
485 private NavigableMap<String, Content> content;
487 public Cleanup(NavigableMap<String, Content> content, int size) {
489 this.content = content;
492 private class Comp implements Comparable<Comp> {
493 public Map.Entry<String, Content> entry;
495 public Comp(Map.Entry<String, Content> en) {
500 public int compareTo(Comp o) {
501 return (int)(entry.getValue().access-o.entry.getValue().access);
505 @SuppressWarnings("unchecked")
508 int size = content.size();
510 ArrayList<Comp> scont = new ArrayList<>(size);
511 Object[] entries = content.entrySet().toArray();
512 for (int i=0;i<size;++i) {
513 scont.add(i, new Comp((Map.Entry<String,Content>)entries[i]));
515 Collections.sort(scont);
516 int end = size - ((maxSize/4)*3); // reduce to 3/4 of max size
517 //System.out.println("------ Cleanup Cycle ------ " + new Date().toString() + " -------");
518 for (int i=0;i<end;++i) {
519 Entry<String, Content> entry = scont.get(i).entry;
520 content.remove(entry.getKey());
521 //System.out.println("removed Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString());
523 // for (int i=end;i<size;++i) {
524 // Entry<String, Content> entry = scont.get(i).entry;
525 // //System.out.println("remaining Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString());