source: MDService2/branches/MDService_simple3/src/eu/clarin/cmdi/mdservice/action/GenericAction.java @ 1517

Last change on this file since 1517 was 1517, checked in by vronk, 13 years ago

Collection request should work

File size: 10.8 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.util.HashMap;
6import java.util.Map;
7import java.util.Set;
8
9import javax.servlet.http.HttpServletRequest;
10
11import org.apache.log4j.Logger;
12import org.apache.struts2.interceptor.ServletRequestAware;
13
14import com.opensymphony.xwork2.ActionSupport;
15
16import eu.clarin.cmdi.mdservice.internal.Cache;
17import eu.clarin.cmdi.mdservice.internal.MDTransformer;
18import eu.clarin.cmdi.mdservice.internal.NoStylesheetException;
19import eu.clarin.cmdi.mdservice.model.Diagnostics;
20import eu.clarin.cmdi.mdservice.proxy.ProxyInterface;
21
22
23
24/**
25 * main Struts2 controller (ie implemenets the struts' execute()-method), all other Actions are derived from.   
26 * Defines the methods used for retrieving the data
27 * and provides basic implementation where possible.
28 * Also responsible for caching and transformation of the result.
29 * 
30 * @author vronk
31 */
32public class GenericAction extends ActionSupport
33implements ServletRequestAware
34{
35        public static Logger log = Logger.getLogger("GenericAction");
36        private static final long serialVersionUID = 1L;
37       
38       
39        private Diagnostics diagnostics;
40        /**
41         * Properties to be filled by Struts with according request-parameters
42         */     
43        private String actionkey = "generic";
44        private String cache = Cache.SKIP;
45        private String lang="en";
46        private String q;
47        private String format="xml"; // default no transformation
48        private String actionContentType;
49        private String userMsg;
50        private HttpServletRequest request; 
51        private long duration = 0;
52        private String repository;
53        private InputStream resultStream;
54        private InputStream sourceStream;
55       
56        private Map<String,String[]> params;
57       
58//      protected URL base_url ;
59       
60        private ProxyInterface target_proxy;
61               
62                               
63        public ProxyInterface getTargetProxy() {
64                return target_proxy;
65        }
66
67        public void setTargetProxy(ProxyInterface proxy) {
68                target_proxy = proxy;
69                target_proxy.setSourceAction(this);
70        }
71
72/**
73 * Empty implementation, subclasses have to decide themselves, which proxy to take.
74 */     
75        public void setTargetProxy() {
76}
77
78         public Diagnostics getDiagnostics(){
79                 if (diagnostics == null){
80                         diagnostics  = new Diagnostics();
81                 }
82                 return this.diagnostics;
83         }
84         
85         public void setDiagnostics(Diagnostics diagnostics){
86                 this.diagnostics = diagnostics;
87         }
88         
89         public String getCache() {
90                return cache;
91        }
92
93        public void setCache(String cache) {
94                this.cache = cache;
95        }
96
97        public String getFormat() {
98                return format;
99        }
100
101        public void setFormat(String format) {
102                this.format = format;
103        }
104         
105        public String getQ() {
106                return q;
107        }
108
109        public void setQ(String pq) {
110                if (pq == null) pq="";
111                /*
112                if (q != null){
113                        if (q.trim().length() == 0){
114                                q = null;
115                        }
116                }
117                */
118                this.q = pq;
119        }
120
121
122        public void setRepository(String repository) {
123                this.repository = repository;
124        }
125       
126        public String getRepository() {
127                //default repository = 1 (set on init)
128                return repository;
129        }
130       
131        /**
132         * is used in struts.xml to dynamically set the mime-type of the result, depending on the format-parameter
133         * @return
134         */
135        public String getActionContentType() {
136                if (format.toLowerCase().startsWith("html")) {
137                        this.actionContentType = "text/html";           
138                        //this.actionContentType = "application/xhtml+xml";
139                } else {
140                        this.actionContentType = "text/xml";
141                }
142               
143                return actionContentType;
144        }
145
146        public void setActionContentType(String actionContentType) {
147                this.actionContentType = actionContentType;
148        }
149       
150        public String getActionkey() {
151                return actionkey;
152        }
153
154        public void setActionkey(String actionKey) {
155                actionkey = actionKey;
156        }
157
158        public String getLang() {
159                return lang;
160        }
161
162        public void setLang(String lang) {
163                this.lang = lang;
164        }
165
166        public String getFullFormat() {         
167                return actionkey + "2" + format;
168        }
169
170
171        /**
172         * TODO: this should be replaced by the diagnostics-mechanism
173         * @return
174         */
175        public String getUserMsg() {
176                return userMsg;
177        }
178
179        public void setUserMsg(String userMsg) {
180                this.userMsg = this.userMsg + "\n" + userMsg;
181        }
182       
183        /**
184         * TODO: check what this does, where it is used?
185         * @return
186         */
187        @Override
188        public void setServletRequest(HttpServletRequest arg0) {
189                request = arg0;
190        }
191
192        public HttpServletRequest getServletRequest() {
193                return request; 
194        }
195
196        /**
197         * The stream holding the resulting data to be sent back to the user as response
198         * @return
199         */
200        public InputStream getResultStream() {
201                return resultStream;
202    }
203        public void setResultStream(InputStream _resultStream){
204                resultStream = _resultStream;
205        }
206        public void setSourceStream(InputStream _sourceStream){
207                sourceStream = _sourceStream;
208        }
209       
210         
211        /**
212         * Get the sourceStream from the target proxy   
213         * @return
214         * @throws IOException
215         * @throws NoStylesheetException
216         */
217                public InputStream getSourceStream() throws IOException, NoStylesheetException {               
218                        return getTargetProxy().getSourceStream(); 
219                }
220               
221        /**
222         * Reads in all the parameters of the request into an internal structure.
223         * the Map is not Map<String,String>, but rather Map<String,String[]>,
224         * ie the value is an array of Strings!
225         * http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.5/api/javax/servlet/ServletRequest.html#getParameterMap%28%29
226         *
227         * This shall allow more flexibility in using the parameters in the subclasses (and less getter/setter stuff)
228         * at the cost of circumventing the Struts-way.
229         */
230        @SuppressWarnings("unchecked")
231        protected void loadParams() {
232                params = getServletRequest().getParameterMap();
233        }
234
235        public Map<String,String[]> getParams() {               
236                return params;
237        }
238
239       
240        /**
241         * This is for simplified access to the the values of the request-parameters
242         * They are stored in the parameters-map as a String-array,
243         * but in most(?) situations, we expect just a simple string.
244         * @param key
245         * @return
246         */
247        public String getParam(String key) {
248                String v = "";
249                if (!(params.get(key)==null)) v=(String)params.get(key)[0];
250                return v;
251        }
252
253        public String[] getParamArray(String key) {
254                String[] a = null;
255                if (!(params.get(key)==null)) a=(String[])params.get(key);
256                return a;
257        }
258
259        /**
260         * Constructs an unambiguous key for the request (encoding all the parameters).
261         * This is used as identifier for caching
262         * @return key unambiguously encoding the request
263         */
264       
265         public String getRequestKey() {
266                        String key="";
267                        if (getActionkey()!=null) {
268                                key += getActionkey() + "//-" ;
269                        }else {
270                                key +="//-" ;
271                        }
272                        /*if (getQ()!=null) {
273                                key += getQ() + "//-" ;
274                        } else {
275                                key +="//-" ;
276                        }
277                        if (getCollection()!=null) {
278                                key += getCollection() + "//-";
279                        } else {
280                                key +="//-" ;
281                        }
282                        if (getSquery()!=null) {
283                                key += getSquery() + "//-" ;
284                        } else {
285                                key +="//-" ;
286                        }
287                        if (getStartItem()!=null) {
288                                key += getStartItem() + "//-";
289                        }
290                                else{
291                                        key +="//-" ;
292                        }
293                        if (getMaximumItems()!=null) {
294                                key += getMaximumItems() + "//-";
295                        }
296                        else{
297                                key +="//-" ;
298                        }
299                       
300                        key += getRepository()  + "//-";
301                        key += getMaxdepth()  + "//-";
302                       
303                        if (getLang()!=null) {
304                                key += getLang() + "//-";
305                        }else{
306                                key +="//-" ;
307                        }                       
308                         */
309                return key;
310        }
311       
312         
313        public String addDurationKey(){
314                String req_key = getRequestKey();
315       
316                Double duration_d;
317
318            duration_d = (double)duration; 
319            duration_d = duration_d/1000.0;
320                req_key += duration_d + "//-";
321                return req_key;
322        }
323       
324        public HashMap<String,String> createTransformerParams(){
325               
326                HashMap<String,String> hm = new HashMap<String,String>();
327               
328            if (getFullFormat() != null){
329                        hm.put("format", getFullFormat());
330            }
331            /*
332                if (getColumns() != null){
333                        hm.put("cols", getColumns());
334                } else {
335                        hm.put("cols", "");
336                }
337                if (getStartItem() != null){
338                        hm.put("startItem", getStartItem());
339                }
340                if (getMaximumItems() != null){
341                        hm.put("maximumItems", getMaximumItems());     
342                }
343                if (getLang() != null){
344                        hm.put("lang", getLang());
345                }
346                if (getQ() != null){
347                        hm.put("q", getQ());
348                }
349                //if (getRepository() != null){
350                hm.put("repository_name", String.valueOf(getRepository()));
351                hm.put("repository_type", WorkspaceProfile.getRepositoryType(this.getRepository()));
352                //}
353        */
354                return hm;
355               
356        }
357       
358        /**
359         * This is the work-horse function.
360         * It does two things:
361         * a) check if the source data is already in cache (based on cache-key that is constructed from the request parameters)
362         * b) if format-parameter provided, invokes the transformation.
363         * at the end the data to be returned as result is contained in the resultStream
364         * If format is xml, then the data from sourceStream is passed further as resultStream.
365         *   
366         * @throws Exception  This is handled by struts (is mapped to some result in struts.xml based on the Exception-Class)
367         */
368       
369        public void prepare() throws Exception {
370                       
371                loadParams();
372                setTargetProxy();
373                getTargetProxy().checkParams();
374               
375                String req_key = getRequestKey();
376                log.debug("request_key: " +  req_key); 
377                log.debug("params.size: " +  params.size());
378                log.debug(getActionkey() + ".targetURL: " + getTargetProxy().getTargetRequest() + " .format:" + getFullFormat());
379               
380                // Caching
381                String xcid;
382       
383                if (getCache().equals(Cache.SKIP)) {
384                       
385                        sourceStream = getSourceStream();
386                       
387                } else { 
388                        if (getCache().equals(Cache.USE)) {
389                                        sourceStream = Cache.getCache().getFromCache(req_key);
390                        }
391                        if (sourceStream == null) { // either not in cache or cache_flag=refresh
392                                //sourceStream = getTargetRequest().openStream();
393                                long startMillis = System.currentTimeMillis();
394                                sourceStream = getSourceStream();
395                                duration = System.currentTimeMillis() - startMillis;
396                                req_key = addDurationKey();
397                               
398                                long now = System.currentTimeMillis();
399                                xcid = Cache.getCache().putInCache(req_key,sourceStream);                       
400                                //Admin.notifyUser("putting in cache: " + req_key);                     
401                                sourceStream = Cache.getCache().getFromCache(req_key);
402                        } /* else {
403                                Admin.notifyUser("reading from cache: " + req_key);
404                        } */
405                }
406                       
407                if (getFormat().equals("xml")) {                       
408                        resultStream = sourceStream;   
409                }else {
410                        MDTransformer transformer = new MDTransformer();
411                        // set URL as srcFile (for MDTransformer to pass to xsl-scripts)
412                        // TODO: WHY??
413                        transformer.setSrcFile(getTargetProxy().getTargetRequest());
414                        transformer.setParams(createTransformerParams());
415                        // here the transformation is invoked
416                        resultStream = transformer.transformXML(sourceStream);
417                }
418               
419                log.debug(getActionkey() + " success:" + (resultStream!=null));
420        }
421
422        /**
423         * default Action method that gets called by Struts. Everything interesting happens in prepare()
424         */
425        public String execute() throws Exception {
426//              HttpServletRequest request = ServletActionContext.getRequest();
427                //Admin.notifyUser("session-attrs:");
428        //Admin.notifyUser(getServletRequest().getRemoteUser() );
429        //Admin.notifyUser(String.valueOf(getSession()));
430       
431        long now = System.currentTimeMillis();
432
433                prepare();
434                long duration = (System.currentTimeMillis() - now);
435                //duration
436
437                if (resultStream == null) {
438                        return ERROR;   
439                } else {
440                        return SUCCESS;
441                }               
442        }
443
444
445}
Note: See TracBrowser for help on using the repository browser.