3c76e928c6d9bd4151e97d833e590f6c3fb5baf5
[aaf/authz.git] / auth / auth-core / src / main / java / org / onap / aaf / auth / rserv / CachingFileAccess.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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====================================================
19  *
20  */
21
22 package org.onap.aaf.auth.rserv;
23
24
25 import java.io.File;
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;
38 import java.util.Map;
39 import java.util.Map.Entry;
40 import java.util.NavigableMap;
41 import java.util.Set;
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;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
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;
56 /*
57  * CachingFileAccess
58  *
59  * Author: Jonathan Gathman, Gathsys 2010
60  *
61  */
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]));
71             }
72         }
73     }
74
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";
89
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
95     private Timer timer;
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;
102
103     public CachingFileAccess(EnvJAXB env, String ... args) throws IOException {
104         super(null,"Caching File Access");
105         setEnv(env,args);
106         content = new ConcurrentSkipListMap<>(); // multi-thread changes possible
107
108         attachOnly = new HashSet<>();     // short, unchanged
109
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");
121
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");
133
134         // Fonts
135         typeMap.put("ttf","font/ttf");
136         typeMap.put("woff","font/woff");
137         typeMap.put("woff2","font/woff2");
138
139
140         timer = new Timer("Caching Cleanup",true);
141         timer.schedule(new Cleanup(content,500),60000,60000);
142
143         // Property params
144         web_path = env.get(env.staticSlot(CFA_WEB_PATH));
145         env.init().log("CachingFileAccess path: " + new File(web_path).getCanonicalPath());
146         Object obj;
147         obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L);  // Default is 10 mins
148         if (obj instanceof Long) {
149           checkInterval=(Long)obj;
150         } else {
151           checkInterval=Long.parseLong((String)obj);
152         }
153
154         obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000);    // Default is max file 500k
155         if (obj instanceof Integer) {
156           maxItemSize=(Integer)obj;
157         } else {
158           maxItemSize =Integer.parseInt((String)obj);
159         }
160
161          clear_command = env.getProperty(CFA_CLEAR_COMMAND,null);
162     }
163
164
165
166     @Override
167     public void handle(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException {
168         String key = pathParam(req, ":key");
169         int slash = key.indexOf('/');
170         if(key.length()>2 && slash>=0 && key.substring(0,slash).equals(clear_command)) {
171             resp.setHeader("Content-Type",typeMap.get("txt"));
172             if ("clear".equals(key.substring(slash+1))) {
173                 content.clear();
174                 resp.setStatus(200/*HttpStatus.OK_200*/);
175             } else {
176                 resp.setStatus(400/*HttpStatus.BAD_REQUEST_400 */);
177             }
178             return;
179         }
180         Content c = load(logT , web_path,key, null, checkInterval);
181         if (c.attachmentOnly) {
182             resp.setHeader("Content-disposition", "attachment");
183         }
184         c.setHeader(resp);
185         c.write(resp.getOutputStream());
186         trans.checkpoint(req.getPathInfo());
187     }
188
189
190     public String webPath() {
191         return web_path;
192     }
193
194     /**
195      * Reset the Cleanup size and interval
196      *
197      * The size and interval when started are 500 items (memory size unknown) checked every minute in a background thread.
198      *
199      * @param size
200      * @param interval
201      */
202     public void cleanupParams(int size, long interval) {
203         timer.cancel();
204         timer = new Timer();
205         timer.schedule(new Cleanup(content,size), interval, interval);
206     }
207
208
209
210     /**
211      * Load a file, first checking cache
212      *
213      *
214      * @param logTarget - logTarget can be null (won't log)
215      * @param dataRoot - data root storage directory
216      * @param key - relative File Path
217      * @param mediaType - what kind of file is it.  If null, will check via file extension
218      * @param timeCheck - "-1" will take system default - Otherwise, will compare "now" + timeCheck(Millis) before looking at File mod
219      * @return
220      * @throws IOException
221      */
222     public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException {
223         long timeCheck = _timeCheck;
224         if (timeCheck<0) {
225             timeCheck=checkInterval; // if time < 0, then use default
226         }
227         boolean isRoot;
228         String fileName;
229         if ("-".equals(key)) {
230             fileName = dataRoot;
231             isRoot = true;
232         } else {
233             fileName=dataRoot + '/' + key;
234             isRoot = false;
235         }
236         Content c = content.get(key);
237         long systime = System.currentTimeMillis();
238         File f=null;
239         if (c!=null) {
240             // Don't check every hit... only after certain time value
241             if (c.date < systime + timeCheck) {
242                 f = new File(fileName);
243                 if (f.lastModified()>c.date) {
244                     c=null;
245                 }
246             }
247         }
248         if (c==null) {
249             if (logTarget!=null) {
250                 logTarget.log("File Read: ",key);
251             }
252
253             if (f==null){
254                 f = new File(fileName);
255             }
256             boolean cacheMe;
257             if (f.exists()) {
258                 if (f.isDirectory()) {
259                     cacheMe = false;
260                     c = new DirectoryContent(f,isRoot);
261                 } else {
262                     if (f.length() > maxItemSize) {
263                         c = new DirectFileContent(f);
264                         cacheMe = false;
265                     } else {
266                         c = new CachedContent(f);
267                         cacheMe = checkInterval>0;
268                     }
269
270                     if (mediaType==null) { // determine from file Ending
271                         int idx = key.lastIndexOf('.');
272                         String subkey = key.substring(++idx);
273                         if ((c.contentType = idx<0?null:typeMap.get(subkey))==null) {
274                             // if nothing else, just set to default type...
275                             c.contentType = "application/octet-stream";
276                         }
277                         c.attachmentOnly = attachOnly.contains(subkey);
278                     } else {
279                         c.contentType=mediaType;
280                         c.attachmentOnly = false;
281                     }
282
283                     c.date = f.lastModified();
284
285                     if (cacheMe) {
286                         content.put(key, c);
287                     }
288                 }
289             } else {
290                 c=NULL;
291             }
292         } else {
293             if (logTarget!=null)logTarget.log("Cache Read: ",key);
294         }
295
296         // refresh hit time
297         c.access = systime;
298         return c;
299     }
300
301
302     public void invalidate(String key) {
303         content.remove(key);
304     }
305
306     private static final Content NULL=new Content() {
307
308         @Override
309         public void setHeader(HttpServletResponse resp) {
310             resp.setStatus(404/*NOT_FOUND_404*/);
311             resp.setHeader("Content-type","text/plain");
312         }
313
314         @Override
315         public void write(Writer writer) throws IOException {
316         }
317
318         @Override
319         public void write(OutputStream os) throws IOException {
320         }
321
322     };
323
324     private static abstract class Content {
325         private long date;   // date of the actual artifact (i.e. File modified date)
326         private long access; // last accessed
327
328         protected String  contentType;
329         protected boolean attachmentOnly;
330
331         public void setHeader(HttpServletResponse resp) {
332             resp.setStatus(200/*OK_200*/);
333             resp.setHeader("Content-Type",contentType);
334             resp.setHeader("Cache-Control", MAX_AGE);
335         }
336
337         public abstract void write(Writer writer) throws IOException;
338         public abstract void write(OutputStream os) throws IOException;
339
340     }
341
342     private static class DirectFileContent extends Content {
343         private File file;
344         public DirectFileContent(File f) {
345             file = f;
346         }
347
348         public String toString() {
349             return file.getName();
350         }
351
352         public void write(Writer writer) throws IOException {
353             FileReader fr = new FileReader(file);
354             char[] buff = new char[1024];
355             try {
356                 int read;
357                 while ((read = fr.read(buff,0,1024))>=0) {
358                     writer.write(buff,0,read);
359                 }
360             } finally {
361                 fr.close();
362             }
363         }
364
365         public void write(OutputStream os) throws IOException {
366             FileInputStream fis = new FileInputStream(file);
367             byte[] buff = new byte[1024];
368             try {
369                 int read;
370                 while ((read = fis.read(buff,0,1024))>=0) {
371                     os.write(buff,0,read);
372                 }
373             } finally {
374                 fis.close();
375             }
376         }
377
378     }
379     private static class DirectoryContent extends Content {
380         private static final Pattern A_NUMBER = Pattern.compile("\\d");
381         private static final String H1 = "<html><head><title>AAF Fileserver</title></head><body><h1>AAF Fileserver</h1><h2>";
382         private static final String H2 = "</h2><ul>\n";
383         private static final String F = "\n</ul></body></html>";
384         private File[] files;
385         private String name;
386         private boolean notRoot;
387
388         public DirectoryContent(File directory, boolean isRoot) {
389             notRoot = !isRoot;
390
391             files = directory.listFiles();
392             Arrays.sort(files,new Comparator<File>() {
393                 @Override
394                 public int compare(File f1, File f2) {
395                     // See if there are Numbers in the name
396                     Matcher m1 = A_NUMBER.matcher(f1.getName());
397                     Matcher m2 = A_NUMBER.matcher(f2.getName());
398                     if (m1.find() && m2.find()) {
399                         // if numbers, are the numbers in the same start position
400                         int i1 = m1.start();
401                         int i2 = m2.start();
402
403                         // If same start position and the text is the same, then reverse sort
404                         if (i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) {
405                             // reverse sort files that start similarly, but have numbers in them
406                             return f2.compareTo(f1);
407                         }
408                     }
409                     return f1.compareTo(f2);
410                 }
411
412             });
413             name = directory.getName();
414             attachmentOnly = false;
415             contentType = "text/html";
416         }
417
418
419         @Override
420         public void write(Writer w) throws IOException {
421             w.append(H1);
422             w.append(name);
423             w.append(H2);
424             for (File f : files) {
425                 w.append("<li><a href=\"");
426                 if (notRoot) {
427                     w.append(name);
428                     w.append('/');
429                 }
430                 w.append(f.getName());
431                 w.append("\">");
432                 w.append(f.getName());
433                 w.append("</a></li>\n");
434             }
435             w.append(F);
436             w.flush();
437         }
438
439         @Override
440         public void write(OutputStream os) throws IOException {
441             write(new OutputStreamWriter(os));
442         }
443
444     }
445
446     private static class CachedContent extends Content {
447         private byte[] data;
448         private int end;
449         private char[] cdata;
450
451         public CachedContent(File f) throws IOException {
452             // Read and Cache
453             ByteBuffer bb = ByteBuffer.allocate((int)f.length());
454             FileInputStream fis = new FileInputStream(f);
455             try {
456                 fis.getChannel().read(bb);
457             } finally {
458                 fis.close();
459             }
460
461             data = bb.array();
462             end = bb.position();
463             cdata=null;
464         }
465
466         public String toString() {
467             return Arrays.toString(data);
468         }
469
470         public void write(Writer writer) throws IOException {
471             synchronized(this) {
472                 // do the String Transformation once, and only if actually used
473                 if (cdata==null) {
474                     cdata = new char[end];
475                     new String(data).getChars(0, end, cdata, 0);
476                 }
477             }
478             writer.write(cdata,0,end);
479         }
480         public void write(OutputStream os) throws IOException {
481             os.write(data,0,end);
482         }
483
484     }
485
486     public void setEnv(LogTarget env) {
487         logT = env;
488     }
489
490     /**
491      * Cleanup thread to remove older items if max Cache is reached.
492      * @author Jonathan
493      *
494      */
495     private static class Cleanup extends TimerTask {
496         private int maxSize;
497         private NavigableMap<String, Content> content;
498
499         public Cleanup(NavigableMap<String, Content> content, int size) {
500             maxSize = size;
501             this.content = content;
502         }
503
504         private class Comp implements Comparable<Comp> {
505             public Map.Entry<String, Content> entry;
506
507             public Comp(Map.Entry<String, Content> en) {
508                 entry = en;
509             }
510
511             @Override
512             public int compareTo(Comp o) {
513                 return (int)(entry.getValue().access-o.entry.getValue().access);
514             }
515
516         }
517         @SuppressWarnings("unchecked")
518         @Override
519         public void run() {
520             int size = content.size();
521             if (size>maxSize) {
522                 ArrayList<Comp> scont = new ArrayList<>(size);
523                 Object[] entries = content.entrySet().toArray();
524                 for (int i=0;i<size;++i) {
525                     scont.add(i, new Comp((Map.Entry<String,Content>)entries[i]));
526                 }
527                 Collections.sort(scont);
528                 int end = size - ((maxSize/4)*3); // reduce to 3/4 of max size
529                 //System.out.println("------ Cleanup Cycle ------ " + new Date().toString() + " -------");
530                 for (int i=0;i<end;++i) {
531                     Entry<String, Content> entry = scont.get(i).entry;
532                     content.remove(entry.getKey());
533                     //System.out.println("removed Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString());
534                 }
535 //                for (int i=end;i<size;++i) {
536 //                    Entry<String, Content> entry = scont.get(i).entry;
537 //                    //System.out.println("remaining Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString());
538 //                }
539             }
540         }
541     }
542 }