source: MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/GenericProxyAction.java @ 1070

Last change on this file since 1070 was 1070, checked in by gaba, 13 years ago
File size: 13.4 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import java.io.BufferedInputStream;
4import java.io.BufferedReader;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.IOException;
8import java.io.InputStream;
9import java.io.InputStreamReader;
10import java.net.MalformedURLException;
11import java.net.URISyntaxException;
12import java.net.URL;
13import java.util.HashMap;
14
15import javax.servlet.http.HttpServletRequest;
16import javax.servlet.http.HttpSession;
17import javax.xml.transform.TransformerException;
18
19import net.sf.json.JSON;
20import net.sf.json.JSONArray;
21import net.sf.json.JSONObject;
22import net.sf.json.JSONSerializer;
23
24
25import org.apache.struts2.interceptor.ServletRequestAware;
26
27import com.opensymphony.xwork2.ActionSupport;
28
29/**
30 * main Struts 2 controller
31 * responds to requests (collections, model, recordset)
32 * by dispatching the requests to appropriate internal methods and filling the inputStream with the result
33 * 
34 * @author vronk
35 *
36 */
37public class GenericProxyAction extends ActionSupport
38implements ServletRequestAware
39{
40
41        private static final long serialVersionUID = 1L;
42       
43        private static JSONArray repositories = null;
44        /**
45         * Properties to be filled by Struts with according request-parameters
46         */     
47        private String actionkey;
48        private String q;
49        private String squery;
50        private String cache = Cache.USE;
51        private String collection;
52        private String columns;
53        private String startItem;
54        private String maximumItems;
55        private String sort;
56        private String lang="en";
57        private int maxdepth;   
58        private String format;
59        private String options;
60        private String actionContentType;
61        private String userMsg;
62        private int repository;
63        //private Map<String,Object> session;
64         private HttpServletRequest request; 
65         private long duration = 0;
66         
67         public GenericProxyAction(){
68                 super();
69                 initialize();
70         }
71         
72         protected void  initialize(){
73                 repository = 1;
74         }
75        public String getQ() {
76                return q;
77        }
78
79        public void setQ(String pq) {
80                if (pq == null) pq="";
81                /*
82                if (q != null){
83                        if (q.trim().length() == 0){
84                                q = null;
85                        }
86                }
87                */
88                this.q = pq;
89        }
90
91        public String getSquery() {
92                return squery;
93        }
94
95        public void setSquery(String psquery) {
96                if (psquery==null) psquery="";
97                this.squery = psquery;
98        }
99       
100        public String getCache() {
101                return cache;
102        }
103
104        public void setCache(String cache) {
105                this.cache = cache;
106        }
107
108        public String getCollection() {
109                return collection;
110        }
111
112        public void setCollection(String collection) {
113                this.collection = collection;
114        }
115       
116        //TODO defaults
117        public String getColumns() {
118                String cols = columns;
119                /*if (columns == null){
120                        cols = "Id,Name,Title";
121                }
122                */
123                return cols;
124        }
125
126        public void setColumns(String columns) {
127                this.columns = columns;
128        }
129       
130        public int getMaxdepth() {
131                return maxdepth;
132        }
133
134        public void setMaxdepth(int maxdepth) {
135                this.maxdepth = maxdepth;
136        }
137
138        public String getFormat() {
139                return format;
140        }
141
142        public void setFormat(String format) {
143                this.format = format;
144        }
145
146        public String getOptions() {
147                return options;
148        }
149
150        public void setOptions(String options) {
151                this.options = options;
152        }
153
154        public String getActionContentType() {
155                if (format.toLowerCase().startsWith("html")) {
156                        this.actionContentType = "text/html";
157                } else {
158                        this.actionContentType = "text/xml";
159                }
160               
161                return actionContentType;
162        }
163
164        public void setActionContentType(String actionContentType) {
165                this.actionContentType = actionContentType;
166        }
167       
168
169        public void setRepository(int repository) {
170                this.repository = repository;
171        }
172       
173        public int getRepository() {
174                //default repository = 1 (set on init)
175               
176                return repository;
177        }
178        public String getActionkey() {
179                return actionkey;
180        }
181
182        public void setActionkey(String actionKey) {
183                actionkey = actionKey;
184        }
185
186       
187        public String getStartItem() {
188                return startItem;
189        }
190
191        public void setStartItem(String startItem) {
192                this.startItem = startItem;
193        }
194
195        public String getMaximumItems() {
196                return maximumItems;
197        }
198
199        public void setMaximumItems(String maximumItems) {
200                this.maximumItems = maximumItems;
201        }
202       
203
204        public String getSort() {
205                return sort;
206        }
207
208        public void setSort(String sort) {
209                this.sort = sort;
210        }
211
212        public String getLang() {
213                return lang;
214        }
215
216        public void setLang(String lang) {
217                this.lang = lang;
218        }
219
220        public String getFullFormat() {         
221                return actionkey + "2" + format;
222        }
223
224        /**
225         * primitive identification of the target-proxy
226         * base for finding the right base_url in the props
227         * subclass has to override with its specific proxykey
228         * @return
229         */
230        public String getProxyKey() {
231                return "";
232        }
233       
234        public String getUserMsg() {
235                return userMsg;
236        }
237
238        public void setUserMsg(String userMsg) {
239                this.userMsg = this.userMsg + "\n" + userMsg;
240        }
241       
242        @Override
243        public void setServletRequest(HttpServletRequest arg0) {
244                request = arg0;
245        }
246
247        public HttpServletRequest getServletRequest() {
248                return request;
249        }
250
251
252        private InputStream resultStream;
253        private InputStream sourceStream;
254
255        /**
256         * The stream holding the resulting data to be sent back to the user as response
257         * @return
258         */
259        public InputStream getResultStream() {
260                return resultStream;
261    }
262        public void setResultStream(InputStream _resultStream){
263                resultStream = _resultStream;
264        }
265        public void setSourceStream(InputStream _sourceStream){
266                sourceStream = _sourceStream;
267        }
268       
269        /*
270        public InputStream getSourceStream() throws IOException {
271                return getTargetRequest().openStream();
272    }
273*/
274       
275        public JSONArray getRepositories(){
276                return repositories;
277        }
278       
279        public void setRepositories(JSONArray rep){
280                this.repositories = rep;
281        }
282       
283        protected URL base_url ;
284       
285        public URL getBaseURL() throws MalformedURLException {         
286                if (base_url == null) {
287                        base_url = new URL(getBaseURI());//Admin.getConfig().getProperty(getProxyKey() + ".uri"));
288                }
289                return base_url;
290        }
291       
292        public String getBaseURI() {           
293                String uri =Admin.getConfig().getProperty(getProxyKey() + ".uri");             
294                return uri;
295        }
296
297       
298        public URL getTargetRequest() throws IOException {
299        // URL targetURL =new URL( base_url, compname + ".xml");
300                URL targetURL = getBaseURL();     
301                     
302        return targetURL;
303        }
304       
305        /*
306        public String getRequestKey() {
307                String key="";
308                if (getActionkey()!=null) {
309                        key += getActionkey() + "//-" ;
310                }
311                if (getQ()!=null) {
312                        key += getQ() + "//-" ;
313                }
314                if (getCollection()!=null) {
315                        key += getCollection();
316                }
317                 
318                return key;
319        }
320*/
321
322         public String getRequestKey() {
323                        String key="";
324                        if (getActionkey()!=null) {
325                                key += getActionkey() + "//-" ;
326                        }else {
327                                key +="//-" ;
328                        }
329                        if (getQ()!=null) {
330                                key += getQ() + "//-" ;
331                        } else {
332                                key +="//-" ;
333                        }
334                        if (getCollection()!=null) {
335                                key += getCollection() + "//-";
336                        } else {
337                                key +="//-" ;
338                        }
339                        if (getSquery()!=null) {
340                                key += getSquery() + "//-" ;
341                        } else {
342                                key +="//-" ;
343                        }
344                        if (getStartItem()!=null) {
345                                key += getStartItem() + "//-";
346                        }
347                                else{
348                                        key +="//-" ;
349                        }
350                        if (getMaximumItems()!=null) {
351                                key += getMaximumItems() + "//-";
352                        }
353                        else{
354                                key +="//-" ;
355                        }
356                       
357                        key += getRepository()  + "//-";
358                        key += getMaxdepth()  + "//-";
359                       
360                        if (getLang()!=null) {
361                                key += getLang() + "//-";
362                        }else{
363                                key +="//-" ;
364                        }
365                       
366                         
367                        return key;
368        }
369        public InputStream getSourceStream() throws IOException {               
370                return getTargetRequest().openStream();
371                //      Admin.notifyUser(getProxyKey() + ".getSourceStream() - unable to open stream: " + getTargetRequest(); 
372        }
373       
374        public  static String convertStreamToString(InputStream is) { 
375               
376                BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
377                StringBuilder sb = new StringBuilder(); 
378                String line = null; 
379               
380                try {
381                        while ((line = reader.readLine()) != null) { 
382                                         sb.append(line + "\n"); 
383                        }
384                } catch (IOException e) {
385                        // TODO Auto-generated catch block
386                        e.printStackTrace();
387                }  finally {
388                        try {
389                                is.close();
390                        } catch (IOException e) {
391                                // TODO Auto-generated catch block
392                                e.printStackTrace();
393                        }
394                        try {
395                                is.reset();
396                        } catch (IOException e) {
397                                // TODO Auto-generated catch block
398                                e.printStackTrace();
399                        }
400                }
401                 
402               
403                return sb.toString(); 
404        }
405
406       
407        public static JSONArray createRepositories() throws IOException, InterruptedException, TransformerException{
408                String path = Admin.getConfig().getProperty("workspaceprofile.path") + WorkspaceAction.PROFILENAME_SERVER;
409                File file=new File(path);
410                InputStream in  = new BufferedInputStream( new FileInputStream(path));;
411               
412                MDTransformer transformer = new MDTransformer();
413                transformer.setSrcFile(file.toURL());
414                transformer.setParams(MDTransformer.createParamsMap("xml2json"));
415                InputStream jsonstream = transformer.transformXML(in);
416               
417                JSONObject json = JSONObject.fromObject(convertStreamToString(jsonstream));
418                JSONArray array = json.getJSONObject("WorkspaceProfile").getJSONArray("Repositories"); 
419               
420                // repository as static variable
421                return array;
422       
423                // repository as session attribute
424                /*
425                HttpSession session = getServletRequest().getSession();
426                //JSONArray param = (JSONArray) session.getAttribute("repositories");
427                JSONArray param = new JSONArray();
428        param.add(array);
429        session.setAttribute("repositories", param);
430                 */
431        }
432       
433       
434        public String getRepositoryPath(){
435                String repository_path = null;
436               
437               
438                if (repositories == null ) {
439                        try {
440                                setRepositories(GenericProxyAction.createRepositories());
441                        } catch (IOException e) {
442                                // TODO Auto-generated catch block
443                                e.printStackTrace();
444                        } catch (InterruptedException e) {
445                                // TODO Auto-generated catch block
446                                e.printStackTrace();
447                        } catch (TransformerException e) {
448                                // TODO Auto-generated catch block
449                                e.printStackTrace();
450                        }
451                }
452                // static repositories
453                net.sf.json.JSONArray json = getRepositories(); 
454                for(int i=0;i<json.size();i++){
455                        if (json.getJSONObject(i).getInt("id") == getRepository()){
456                                repository_path =  json.getJSONObject(i).getString("uri");
457                        }
458                }
459                //Admin.notifyUser("REPOSITORY_PATH:" + repository_path);
460               
461                //session repositories
462                /*
463                HttpSession session = getServletRequest().getSession();
464                json = (net.sf.json.JSONArray) session.getAttribute("repositories");
465                for(int i=0;i<json.size();i++){
466                        if (json.getJSONObject(i).getInt("id") == getRepository()){
467                                repository_path =  json.getJSONObject(i).getString("uri");
468                        }
469                }
470                Admin.notifyUser("REPOSITORY_PATH-SESSIONATTR:" + repository_path);
471                */
472                return repository_path;
473               
474        }
475       
476        public String addDurationKey(){
477                String req_key = getRequestKey();
478       
479                Double duration_d;
480
481            duration_d = (double)duration; 
482            duration_d = duration_d/1000.0;
483                req_key += duration_d + "//-";
484                return req_key;
485        }
486       
487        public HashMap<String,String> createTransformerParams(){
488               
489                HashMap<String,String> hm = new HashMap<String,String>();
490               
491            if (getFullFormat() != null){
492                        hm.put("format", getFullFormat());
493            }
494                if (getColumns() != null){
495                        hm.put("cols", getColumns());
496                }
497                if (getStartItem() != null){
498                        hm.put("startItem", getStartItem());
499                }
500                if (getMaximumItems() != null){
501                        hm.put("maximumItems", getMaximumItems());     
502                }
503                if (getLang() != null){
504                        hm.put("lang", getLang());
505                }
506                if (getQ() != null){
507                        hm.put("q", getQ());
508                }
509                if (getRepository() != 0){
510                hm.put("repository_uri", String.valueOf(getRepository()));     
511                }
512       
513                return hm;
514               
515        }
516       
517        public void prepare() throws Exception {               
518               
519                String req_key = getRequestKey();
520                Admin.notifyUser("request_key: " +  req_key); 
521                Admin.notifyUser(getProxyKey() + ".targetURL: " + getTargetRequest() + " .format:" + getFullFormat());
522               
523                // Caching
524                String xcid;
525       
526                // Admin.notifyUser("GPA.prepareSourceStream");
527               
528                if (getCache().equals(Cache.SKIP)) {
529                       
530                        sourceStream = getSourceStream();
531                       
532                } else { 
533                        if (getCache().equals(Cache.USE)) {
534                                        sourceStream = Cache.getCache().getFromCache(req_key);
535                        }
536                        if (sourceStream == null) { // either not in cache or cache_flag=refresh
537                                //sourceStream = getTargetRequest().openStream();
538                                long startMillis = System.currentTimeMillis();
539                                sourceStream = getSourceStream();
540                                duration = System.currentTimeMillis() - startMillis;
541                                req_key = addDurationKey();
542                               
543                                long now = System.currentTimeMillis();
544                                xcid = Cache.getCache().putInCache(req_key,sourceStream);                       
545                                Admin.notifyUser("putting in cache: " + req_key);                       
546                                sourceStream = Cache.getCache().getFromCache(req_key);
547                        }  else {
548                                Admin.notifyUser("reading from cache: " + req_key);
549                        }
550                }
551                       
552                if (format.equals("xml")) {                     
553                        resultStream = sourceStream;   
554                }else {
555                        // set URL as srcFile (for MDTransformer to pass to xsl-scripts)
556                        MDTransformer transformer = new MDTransformer();
557                        transformer.setSrcFile(getTargetRequest());
558                        // getColumns
559                        Admin.notifyUser("GPA.getRepository, before xsl:" + getRepository());
560                        transformer.setParams(createTransformerParams());
561                        resultStream = transformer.transformXML(sourceStream);//, getFullFormat(), getColumns(), getStartRecord(), getMaximumRecords(),getLang(),getQ(),String.valueOf(getRepository()));
562                }
563                       
564                Admin.notifyUser(getProxyKey() + " success:" + (resultStream!=null));
565        }
566
567        /**
568         * default Action method
569         */
570        public String execute() throws Exception {
571//              HttpServletRequest request = ServletActionContext.getRequest();
572
573               
574                Admin.notifyUser("session-attrs:");
575        Admin.notifyUser(getServletRequest().getRemoteUser() );
576        //Admin.notifyUser(String.valueOf(getSession()));
577       
578        long now = System.currentTimeMillis();
579
580                prepare();
581                long duration = (System.currentTimeMillis() - now);
582                //duration
583
584                if (resultStream == null) {
585                        return ERROR;   
586                } else {
587                        return SUCCESS;
588                }               
589        }
590
591
592}
Note: See TracBrowser for help on using the repository browser.