cdda50db48eba07714994cd2a0299a7721a01c09
[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 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";
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 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;
102
103     public static final String TEXT_PLAIN = "text/plain";
104
105     public CachingFileAccess(EnvJAXB env, String ... args) throws IOException {
106         super(null,"Caching File Access");
107         setEnv(env,args);
108         content = new ConcurrentSkipListMap<>(); // multi-thread changes possible
109
110         attachOnly = new HashSet<>();     // short, unchanged
111
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");
123
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");
135
136         // Fonts
137         typeMap.put("ttf","font/ttf");
138         typeMap.put("woff","font/woff");
139         typeMap.put("woff2","font/woff2");
140
141
142         timer = new Timer("Caching Cleanup",true);
143         timer.schedule(new Cleanup(content,500),60000,60000);
144
145         // Property params
146         webPath = env.get(env.staticSlot(CFA_WEB_PATH));
147         env.init().log("CachingFileAccess path: " + new File(webPath).getCanonicalPath());
148         Object obj;
149         obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L);  // Default is 10 mins
150         if (obj instanceof Long) {
151           checkInterval=(Long)obj;
152         } else {
153           checkInterval=Long.parseLong((String)obj);
154         }
155
156         obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000);    // Default is max file 500k
157         if (obj instanceof Integer) {
158           maxItemSize=(Integer)obj;
159         } else {
160           maxItemSize =Integer.parseInt((String)obj);
161         }
162
163          clearCommand = env.getProperty(CFA_CLEAR_COMMAND,null);
164     }
165
166
167
168     @Override
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))) {
175                 content.clear();
176                 resp.setStatus(200/*HttpStatus.OK_200*/);
177             } else {
178                 resp.setStatus(400/*HttpStatus.BAD_REQUEST_400 */);
179             }
180             return;
181         }
182         Content c = load(logT , webPath,key, null, checkInterval);
183         if (c.attachmentOnly) {
184             resp.setHeader("Content-disposition", "attachment");
185         }
186         c.setHeader(resp);
187         c.write(resp.getOutputStream());
188         trans.checkpoint(req.getPathInfo());
189     }
190
191
192     public String webPath() {
193         return webPath;
194     }
195
196     /**
197      * Reset the Cleanup size and interval
198      *
199      * The size and interval when started are 500 items (memory size unknown) checked every minute in a background thread.
200      *
201      * @param size
202      * @param interval
203      */
204     public void cleanupParams(int size, long interval) {
205         timer.cancel();
206         timer = new Timer();
207         timer.schedule(new Cleanup(content,size), interval, interval);
208     }
209
210
211
212     /**
213      * Load a file, first checking cache
214      *
215      *
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
221      * @return
222      * @throws IOException
223      */
224     public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException {
225         long timeCheck = _timeCheck;
226         if (timeCheck<0) {
227             timeCheck=checkInterval; // if time < 0, then use default
228         }
229         boolean isRoot;
230         String fileName;
231         if ("-".equals(key)) {
232             fileName = dataRoot;
233             isRoot = true;
234         } else {
235             fileName=dataRoot + '/' + key;
236             isRoot = false;
237         }
238         Content c = content.get(key);
239         long systime = System.currentTimeMillis();
240         File f=null;
241         if (c!=null) {
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) {
246                     c=null;
247                 }
248             }
249         }
250         if (c==null) {
251             if (logTarget!=null) {
252                 logTarget.log("File Read: ",key);
253             }
254
255             if (f==null){
256                 f = new File(fileName);
257             }
258             boolean cacheMe;
259             if (f.exists()) {
260                 if (f.isDirectory()) {
261                     cacheMe = false;
262                     c = new DirectoryContent(f,isRoot);
263                 } else {
264                     if (f.length() > maxItemSize) {
265                         c = new DirectFileContent(f);
266                         cacheMe = false;
267                     } else {
268                         c = new CachedContent(f);
269                         cacheMe = checkInterval>0;
270                     }
271
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";
278                         }
279                         c.attachmentOnly = attachOnly.contains(subkey);
280                     } else {
281                         c.contentType=mediaType;
282                         c.attachmentOnly = false;
283                     }
284
285                     c.date = f.lastModified();
286
287                     if (cacheMe) {
288                         content.put(key, c);
289                     }
290                 }
291             } else {
292                 c=NULL;
293             }
294         } else {
295             if (logTarget!=null)logTarget.log("Cache Read: ",key);
296         }
297
298         // refresh hit time
299         c.access = systime;
300         return c;
301     }
302
303
304     public void invalidate(String key) {
305         content.remove(key);
306     }
307
308     private static final Content NULL=new Content() {
309
310         @Override
311         public void setHeader(HttpServletResponse resp) {
312             resp.setStatus(404/*NOT_FOUND_404*/);
313             resp.setHeader("Content-type",TEXT_PLAIN);
314         }
315
316         @Override
317         public void write(Writer writer) throws IOException {
318         }
319
320         @Override
321         public void write(OutputStream os) throws IOException {
322         }
323
324     };
325
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
329
330         protected String  contentType;
331         protected boolean attachmentOnly;
332
333         public void setHeader(HttpServletResponse resp) {
334             resp.setStatus(200/*OK_200*/);
335             resp.setHeader("Content-Type",contentType);
336             resp.setHeader("Cache-Control", maxAge);
337         }
338
339         public abstract void write(Writer writer) throws IOException;
340         public abstract void write(OutputStream os) throws IOException;
341
342     }
343
344     private static class DirectFileContent extends Content {
345         private File file;
346         public DirectFileContent(File f) {
347             file = f;
348         }
349
350         public String toString() {
351             return file.getName();
352         }
353
354         public void write(Writer writer) throws IOException {
355             FileReader fr = new FileReader(file);
356             char[] buff = new char[1024];
357             try {
358                 int read;
359                 while ((read = fr.read(buff,0,1024))>=0) {
360                     writer.write(buff,0,read);
361                 }
362             } finally {
363                 fr.close();
364             }
365         }
366
367         public void write(OutputStream os) throws IOException {
368             FileInputStream fis = new FileInputStream(file);
369             byte[] buff = new byte[1024];
370             try {
371                 int read;
372                 while ((read = fis.read(buff,0,1024))>=0) {
373                     os.write(buff,0,read);
374                 }
375             } finally {
376                 fis.close();
377             }
378         }
379
380     }
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;
387         private String name;
388         private boolean notRoot;
389
390         public DirectoryContent(File directory, boolean isRoot) {
391             notRoot = !isRoot;
392
393             files = directory.listFiles();
394             Arrays.sort(files,new Comparator<File>() {
395                 @Override
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
402                         int i1 = m1.start();
403                         int i2 = m2.start();
404
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);
409                         }
410                     }
411                     return f1.compareTo(f2);
412                 }
413
414             });
415             name = directory.getName();
416             attachmentOnly = false;
417             contentType = "text/html";
418         }
419
420
421         @Override
422         public void write(Writer w) throws IOException {
423             w.append(H1);
424             w.append(name);
425             w.append(H2);
426             for (File f : files) {
427                 w.append("<li><a href=\"");
428                 if (notRoot) {
429                     w.append(name);
430                     w.append('/');
431                 }
432                 w.append(f.getName());
433                 w.append("\">");
434                 w.append(f.getName());
435                 w.append("</a></li>\n");
436             }
437             w.append(F);
438             w.flush();
439         }
440
441         @Override
442         public void write(OutputStream os) throws IOException {
443             write(new OutputStreamWriter(os));
444         }
445
446     }
447
448     private static class CachedContent extends Content {
449         private byte[] data;
450         private int end;
451         private char[] cdata;
452
453         public CachedContent(File f) throws IOException {
454             // Read and Cache
455             ByteBuffer bb = ByteBuffer.allocate((int)f.length());
456             FileInputStream fis = new FileInputStream(f);
457             try {
458                 fis.getChannel().read(bb);
459             } finally {
460                 fis.close();
461             }
462
463             data = bb.array();
464             end = bb.position();
465             cdata=null;
466         }
467
468         public String toString() {
469             return Arrays.toString(data);
470         }
471
472         public void write(Writer writer) throws IOException {
473             synchronized(this) {
474                 // do the String Transformation once, and only if actually used
475                 if (cdata==null) {
476                     cdata = new char[end];
477                     new String(data).getChars(0, end, cdata, 0);
478                 }
479             }
480             writer.write(cdata,0,end);
481         }
482         public void write(OutputStream os) throws IOException {
483             os.write(data,0,end);
484         }
485
486     }
487
488     public void setEnv(LogTarget env) {
489         logT = env;
490     }
491
492     /**
493      * Cleanup thread to remove older items if max Cache is reached.
494      * @author Jonathan
495      *
496      */
497     private static class Cleanup extends TimerTask {
498         private int maxSize;
499         private NavigableMap<String, Content> content;
500
501         public Cleanup(NavigableMap<String, Content> content, int size) {
502             maxSize = size;
503             this.content = content;
504         }
505
506         private class Comp implements Comparable<Comp> {
507             public Map.Entry<String, Content> entry;
508
509             public Comp(Map.Entry<String, Content> en) {
510                 entry = en;
511             }
512
513             @Override
514             public int compareTo(Comp o) {
515                 return (int)(entry.getValue().access-o.entry.getValue().access);
516             }
517
518         }
519         @SuppressWarnings("unchecked")
520         @Override
521         public void run() {
522             int size = content.size();
523             if (size>maxSize) {
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]));
528                 }
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());
534                 }
535             }
536         }
537     }
538 }