source: MDService2/branches/MDService_simple3/src/eu/clarin/cmdi/mdservice/action/GenericProxyAction.java @ 1532

Last change on this file since 1532 was 1532, checked in by gaba, 13 years ago

repository diagnostic

File size: 12.1 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.net.MalformedURLException;
6import java.net.URL;
7import java.util.HashMap;
8
9import javax.servlet.http.HttpServletRequest;
10
11import org.apache.log4j.Logger;
12import org.apache.struts2.interceptor.ServletRequestAware;
13
14import eu.clarin.cmdi.mdservice.internal.Admin;
15import eu.clarin.cmdi.mdservice.internal.Cache;
16import eu.clarin.cmdi.mdservice.internal.MDTransformer;
17import eu.clarin.cmdi.mdservice.internal.NoStylesheetException;
18import eu.clarin.cmdi.mdservice.model.Diagnostics;
19import eu.clarin.cmdi.mdservice.model.WorkspaceProfile;
20
21/**
22 * main Struts2 controller (ie implemenets the struts' execute()-method), all other Actions are derived from.   
23 * Defines the methods used for retrieving the data
24 * and provides basic implementation where possible.
25 * 
26 * @author vronk
27 */
28public class GenericProxyAction extends GenericAction
29implements ServletRequestAware
30{
31
32        private static final long serialVersionUID = 1L;
33        private static Logger log = Logger.getLogger("GenericProxyAction");
34       
35        private Diagnostics diagnostics;
36        /**
37         * Properties to be filled by Struts with according request-parameters
38         */     
39        private String actionkey;
40        private String q;
41        private String squery;
42        private String cache = Cache.USE;
43        private String collection;
44        private String columns;
45        private String startItem;
46        private String maximumItems;
47        private String sort;
48        private String lang="en";
49        private int maxdepth;   
50        private String format;
51        private String options;
52        private String actionContentType;
53        private String userMsg;
54        private String repository;
55        //private Map<String,Object> session;
56        private HttpServletRequest request; 
57        private long duration = 0;
58        private InputStream resultStream;
59        private InputStream sourceStream;
60        protected URL base_url ;
61               
62         public GenericProxyAction(){
63                 super();
64                 initialize();
65         }
66         
67         public void setRepositoryByIndex(int id){
68               
69                                net.sf.json.JSONArray json = WorkspaceProfile.getRepositories();
70                                if (json.size() > 0){
71                                        repository = json.getJSONObject(id).getString("name");
72                                }
73                       
74         }
75         
76         protected void  initialize(){
77                 //repository = 1;
78                 setRepositoryByIndex(0);                               
79         }
80         
81        /*
82         public Diagnostics getDiagnostics(){
83                 return this.diagnostics;
84         }
85         
86         public void setDiagnostics(Diagnostics diagnostics){
87                 this.diagnostics = diagnostics;
88         }
89         public Diagnostics Diagnostics(){
90                 if (diagnostics == null){
91                         diagnostics  = new Diagnostics();
92                 }
93                 return this.diagnostics;
94         }
95        public String getQ() {
96                return q;
97        }
98
99        public void setQ(String pq) {
100                if (pq == null) pq="";
101                /*
102                if (q != null){
103                        if (q.trim().length() == 0){
104                                q = null;
105                        }
106                }
107               
108                this.q = pq;
109        }
110
111        public String getSquery() {
112                return squery;
113        }
114
115        public void setSquery(String psquery) {
116                if (psquery==null) psquery="";
117                this.squery = psquery;
118        }
119       
120        public String getCache() {
121                return cache;
122        }
123
124        public void setCache(String cache) {
125                this.cache = cache;
126        }
127
128        public String getCollection() {
129                return collection;
130        }
131
132        public void setCollection(String collection) {
133                this.collection = collection;
134        }
135       
136        //TODO defaults
137        public String getColumns() {
138                String cols = columns;
139                return cols;
140        }
141
142        public void setColumns(String columns) {
143                this.columns = columns;
144        }
145       
146        public int getMaxdepth() {
147                return maxdepth;
148        }
149
150        public void setMaxdepth(int maxdepth) {
151                this.maxdepth = maxdepth;
152        }
153
154        public String getFormat() {
155                return format;
156        }
157
158        public void setFormat(String format) {
159                this.format = format;
160        }
161
162        public String getOptions() {
163                return options;
164        }
165
166        public void setOptions(String options) {
167                this.options = options;
168        }
169*/
170        /**
171         * is used in struts.xml to dynamically set the mime-type of the result, depending on the format-parameter
172         * @return
173         */
174        public String getActionContentType() {
175                if (format.toLowerCase().startsWith("html")) {
176                        this.actionContentType = "text/html";           
177                        //this.actionContentType = "application/xhtml+xml";
178                } else {
179                        this.actionContentType = "text/xml";
180                }
181               
182                return actionContentType;
183        }
184
185        public void setActionContentType(String actionContentType) {
186                this.actionContentType = actionContentType;
187        }
188       
189
190        public void setRepository(String repository) {
191                this.repository = repository;
192        }
193       
194        public String getRepository() {
195                //default repository = 1 (set on init)
196                return repository;
197        }
198        public String getActionkey() {
199                return actionkey;
200        }
201
202        public void setActionkey(String actionKey) {
203                actionkey = actionKey;
204        }
205
206       
207        public String getStartItem() {
208                return startItem;
209        }
210
211        public void setStartItem(String startItem) {
212                this.startItem = startItem;
213        }
214
215        public String getMaximumItems() {
216                return maximumItems;
217        }
218
219        public void setMaximumItems(String maximumItems) {
220                this.maximumItems = maximumItems;
221        }
222       
223
224        public String getSort() {
225                return sort;
226        }
227
228        public void setSort(String sort) {
229                this.sort = sort;
230        }
231
232        public String getLang() {
233                return lang;
234        }
235
236        public void setLang(String lang) {
237                this.lang = lang;
238        }
239
240        public String getFullFormat() {         
241                return actionkey + "2" + format;
242        }
243
244        /**
245         * internal identification of the target-proxy
246         * base for finding the right base_url in the properties
247         * subclass has to override with its specific proxykey
248         * @return the key identifying this type of proxy
249         */
250        public String getProxyKey() {
251                return "";
252        }
253       
254        /**
255         * TODO: check what this does, where it is used?
256         * @return
257         */
258        public String getUserMsg() {
259                return userMsg;
260        }
261
262        public void setUserMsg(String userMsg) {
263                this.userMsg = this.userMsg + "\n" + userMsg;
264        }
265       
266        /**
267         * TODO: check what this does, where it is used?
268         * @return
269         */
270        @Override
271        public void setServletRequest(HttpServletRequest arg0) {
272                request = arg0;
273        }
274
275        public HttpServletRequest getServletRequest() {
276                return request;
277        }
278
279        /**
280         * The stream holding the resulting data to be sent back to the user as response
281         * @return
282         */
283        public InputStream getResultStream() {
284                return resultStream;
285    }
286        public void setResultStream(InputStream _resultStream){
287                resultStream = _resultStream;
288        }
289        public void setSourceStream(InputStream _sourceStream){
290                sourceStream = _sourceStream;
291        }
292       
293        /*
294        public InputStream getSourceStream() throws IOException {
295                return getTargetRequest().openStream();
296    }
297*/
298       
299       
300        /**
301         * Reads URI from the configuration (mdservice.properties) based on the proxy-key
302         * @return the base-URI of the target repository or registry
303         */
304        public String getBaseURI() {           
305                String uri =Admin.getConfig().getProperty(getProxyKey() + ".uri");             
306                return uri;
307        }
308
309        /**
310         * Provides the base-URL specific to given target repository or registry
311         * @return
312         * @throws MalformedURLException
313         */     
314        public URL getBaseURL() throws MalformedURLException {         
315                if (base_url == null) {
316                        base_url = new URL(getBaseURI());//Admin.getConfig().getProperty(getProxyKey() + ".uri"));
317                }
318                return base_url;
319        }
320       
321        /**
322         * Constructs the actual URL to be send to the target repository/registry
323         * It has to be overridden by the subclasses
324         * as every target service has a different request-pattern. 
325         * @return URL of the target request
326         * @throws IOException
327         */
328        public URL getTargetRequest() throws IOException {
329                URL targetURL = getBaseURL();                     
330        return targetURL;
331        }
332       
333        /**
334         * Constructs an unambiguous key for the request (encoding all the parameters).
335         * This is used as identifier for caching
336         * @return key unambiguously encoding the request
337         */
338       
339         public String getRequestKey() {
340                        String key="";
341                        /*
342                        if (getActionkey()!=null) {
343                                key += getActionkey() + "//-" ;
344                        }else {
345                                key +="//-" ;
346                        }
347                        if (getQ()!=null) {
348                                key += getQ() + "//-" ;
349                        } else {
350                                key +="//-" ;
351                        }
352                        if (getCollection()!=null) {
353                                key += getCollection() + "//-";
354                        } else {
355                                key +="//-" ;
356                        }
357                        if (getSquery()!=null) {
358                                key += getSquery() + "//-" ;
359                        } else {
360                                key +="//-" ;
361                        }
362                        if (getStartItem()!=null) {
363                                key += getStartItem() + "//-";
364                        }
365                                else{
366                                        key +="//-" ;
367                        }
368                        if (getMaximumItems()!=null) {
369                                key += getMaximumItems() + "//-";
370                        }
371                        else{
372                                key +="//-" ;
373                        }
374                       
375                        key += getRepository()  + "//-";
376                        key += getMaxdepth()  + "//-";
377                       
378                        if (getLang()!=null) {
379                                key += getLang() + "//-";
380                        }else{
381                                key +="//-" ;
382                        }                       
383                         */
384                return key;
385        }
386         
387         
388        public InputStream getSourceStream() throws IOException, NoStylesheetException {               
389                return getTargetRequest().openStream();
390 
391        }
392       
393       
394       
395                public String addDurationKey(){
396                String req_key = getRequestKey();
397       
398                Double duration_d;
399
400            duration_d = (double)duration; 
401            duration_d = duration_d/1000.0;
402                req_key += duration_d + "//-";
403                return req_key;
404        }
405       
406                /*
407        public HashMap<String,String> createTransformerParams(){
408               
409                HashMap<String,String> hm = new HashMap<String,String>();
410               
411            if (getFullFormat() != null){
412                        hm.put("format", getFullFormat());
413            }
414                if (getColumns() != null){
415                        hm.put("cols", getColumns());
416                } else {
417                        hm.put("cols", "");
418                }
419                if (getStartItem() != null){
420                        hm.put("startItem", getStartItem());
421                }
422                if (getMaximumItems() != null){
423                        hm.put("maximumItems", getMaximumItems());     
424                }
425                if (getLang() != null){
426                        hm.put("lang", getLang());
427                }
428                if (getQ() != null){
429                        hm.put("q", getQ());
430                }
431                //if (getRepository() != null){
432                hm.put("repository_name", String.valueOf(getRepository()));
433                hm.put("repository_type", WorkspaceProfile.getRepositoryType(this.getRepository()));
434                //}
435       
436                return hm;
437               
438        }
439        */
440        /**
441         * This is the work-horse function.
442         * It does two things:
443         * a) check if the source data is already in cache (based on cache-key that is constructed from the request parameters)
444         * b) if format-parameter provided, invokes the transformation.
445         * at the end the data to be returned as result is contained in the resultStream
446         * If format is xml, then the data from sourceStream is passed further as resultStream.
447         *   
448         * @throws Exception  This is handled by struts (is mapped to some result in struts.xml based on the Exception-Class)
449         */
450       
451        public void prepare() {         
452               
453                try{
454                        String req_key = getRequestKey();
455                        Admin.notifyUser("request_key: " +  req_key); 
456                        Admin.notifyUser(getProxyKey() + ".targetURL: " + getTargetRequest() + " .format:" + getFullFormat());
457                       
458                        // Caching
459                        String xcid;
460               
461                        // Admin.notifyUser("GPA.prepareSourceStream");
462                       
463                        if (getCache().equals(Cache.SKIP)) {
464                               
465                                sourceStream = getSourceStream();
466                               
467                        } else { 
468                                if (getCache().equals(Cache.USE)) {
469                                                sourceStream = Cache.getCache().getFromCache(req_key);
470                                }
471                                if (sourceStream == null) { // either not in cache or cache_flag=refresh
472                                        //sourceStream = getTargetRequest().openStream();
473                                        long startMillis = System.currentTimeMillis();
474                                        sourceStream = getSourceStream();
475                                        duration = System.currentTimeMillis() - startMillis;
476                                        req_key = addDurationKey();
477                                       
478                                        long now = System.currentTimeMillis();
479                                        xcid = Cache.getCache().putInCache(req_key,sourceStream);                       
480                                        //Admin.notifyUser("putting in cache: " + req_key);                     
481                                        sourceStream = Cache.getCache().getFromCache(req_key);
482                                } /* else {
483                                        Admin.notifyUser("reading from cache: " + req_key);
484                                } */
485                        }
486                               
487                        if (format.equals("xml")) {                     
488                                resultStream = sourceStream;   
489                        }else {
490                                MDTransformer transformer = new MDTransformer();
491                                // set URL as srcFile (for MDTransformer to pass to xsl-scripts)
492                                // TODO: WHY??
493                                transformer.setSrcFile(getTargetRequest());
494                                //transformer.setParams(createTransformerParams());
495                                // here the transformation is invoked
496                                resultStream = transformer.transformXML(sourceStream);
497                        }
498                               
499                        log.debug(getProxyKey() + " success:" + (resultStream!=null));
500       
501                } catch (Exception e){
502                       
503                }
504        }
505
506        /**
507         * default Action method that gets called by Struts. Everything interesting happens in prepare()
508         */
509        public String execute() throws Exception {
510//              HttpServletRequest request = ServletActionContext.getRequest();
511
512               
513                //Admin.notifyUser("session-attrs:");
514        //Admin.notifyUser(getServletRequest().getRemoteUser() );
515        //Admin.notifyUser(String.valueOf(getSession()));
516       
517        long now = System.currentTimeMillis();
518
519                prepare();
520                long duration = (System.currentTimeMillis() - now);
521                //duration
522
523                if (resultStream == null) {
524                        return ERROR;   
525                } else {
526                        return SUCCESS;
527                }               
528        }
529
530
531}
Note: See TracBrowser for help on using the repository browser.