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

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

workspaceprofile options

File size: 18.0 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//import net.sf.saxon.Controller;
24//import net.sf.saxon.event.MessageEmitter;
25
26
27import org.apache.struts2.interceptor.ServletRequestAware;
28
29import com.opensymphony.xwork2.ActionSupport;
30
31import eu.clarin.cmdi.mdservice.model.Diagnostics;
32
33/**
34 * main Struts 2 controller
35 * responds to requests (collections, model, recordset)
36 * by dispatching the requests to appropriate internal methods and filling the inputStream with the result
37 * 
38 * @author vronk
39 *
40 */
41public class GenericProxyAction extends ActionSupport
42implements ServletRequestAware
43{
44
45        private static final long serialVersionUID = 1L;
46       
47        private static JSONArray repositories = null;
48        private static JSONObject wp_options = null;
49       
50        private Diagnostics diagnostics;
51        /**
52         * Properties to be filled by Struts with according request-parameters
53         */     
54        private String actionkey;
55        private String q;
56        private String squery;
57        private String cache = Cache.USE;
58        private String collection;
59        private String columns;
60        private String startItem;
61        private String maximumItems;
62        private String sort;
63        private String lang="en";
64        private int maxdepth;   
65        private String format;
66        private String options;
67        private String actionContentType;
68        private String userMsg;
69        private String repository;
70        //private Map<String,Object> session;
71         private HttpServletRequest request; 
72         private long duration = 0;
73         
74         public GenericProxyAction(){
75                 super();
76                 initialize();
77         }
78         
79         public void setRepositoryByIndex(int id){
80                 try {
81                                setRepositories(GenericProxyAction.createRepositories());
82                                // static repositories
83                                net.sf.json.JSONArray json = getRepositories();
84                                if (json.size() > 0){
85                                        repository = json.getJSONObject(id).getString("name");
86                                }
87                        } catch (IOException e) {
88                                // TODO Auto-generated catch block
89                                e.printStackTrace();
90                        } catch (InterruptedException e) {
91                                // TODO Auto-generated catch block
92                                e.printStackTrace();
93                        } catch (TransformerException e) {
94                                // TODO Auto-generated catch block
95                                e.printStackTrace();
96                        } catch (NoStylesheetException e) {
97                                // TODO Auto-generated catch block
98                                e.printStackTrace();
99                        }
100         }
101         
102         protected void  initialize(){
103                 //repository = 1;
104                 setRepositoryByIndex(0);                               
105         }
106         
107         
108         public Diagnostics getDiagnostics(){
109                 return this.diagnostics;
110         }
111         
112         public void setDiagnostics(Diagnostics diagnostics){
113                 this.diagnostics = diagnostics;
114         }
115         public Diagnostics Diagnostics(){
116                 if (diagnostics == null){
117                         diagnostics  = new Diagnostics();
118                 }
119                 return this.diagnostics;
120         }
121        public String getQ() {
122                return q;
123        }
124
125        public void setQ(String pq) {
126                if (pq == null) pq="";
127                /*
128                if (q != null){
129                        if (q.trim().length() == 0){
130                                q = null;
131                        }
132                }
133                */
134                this.q = pq;
135        }
136
137        public String getSquery() {
138                return squery;
139        }
140
141        public void setSquery(String psquery) {
142                if (psquery==null) psquery="";
143                this.squery = psquery;
144        }
145       
146        public String getCache() {
147                return cache;
148        }
149
150        public void setCache(String cache) {
151                this.cache = cache;
152        }
153
154        public String getCollection() {
155                return collection;
156        }
157
158        public void setCollection(String collection) {
159                this.collection = collection;
160        }
161       
162        //TODO defaults
163        public String getColumns() {
164                String cols = columns;
165                /*if (columns == null){
166                        cols = "Id,Name,Title";
167                }
168                */
169                return cols;
170        }
171
172        public void setColumns(String columns) {
173                this.columns = columns;
174        }
175       
176        public int getMaxdepth() {
177                return maxdepth;
178        }
179
180        public void setMaxdepth(int maxdepth) {
181                this.maxdepth = maxdepth;
182        }
183
184        public String getFormat() {
185                return format;
186        }
187
188        public void setFormat(String format) {
189                this.format = format;
190        }
191
192        public String getOptions() {
193                return options;
194        }
195
196        public void setOptions(String options) {
197                this.options = options;
198        }
199
200        public String getActionContentType() {
201                if (format.toLowerCase().startsWith("html")) {
202                        this.actionContentType = "text/html";           
203                        //this.actionContentType = "application/xhtml+xml";
204                } else {
205                        this.actionContentType = "text/xml";
206                }
207               
208                return actionContentType;
209        }
210
211        public void setActionContentType(String actionContentType) {
212                this.actionContentType = actionContentType;
213        }
214       
215
216        public void setRepository(String repository) {
217                this.repository = repository;
218        }
219       
220        public String getRepository() {
221                //default repository = 1 (set on init)
222                return repository;
223        }
224        public String getActionkey() {
225                return actionkey;
226        }
227
228        public void setActionkey(String actionKey) {
229                actionkey = actionKey;
230        }
231
232       
233        public String getStartItem() {
234                return startItem;
235        }
236
237        public void setStartItem(String startItem) {
238                this.startItem = startItem;
239        }
240
241        public String getMaximumItems() {
242                return maximumItems;
243        }
244
245        public void setMaximumItems(String maximumItems) {
246                this.maximumItems = maximumItems;
247        }
248       
249
250        public String getSort() {
251                return sort;
252        }
253
254        public void setSort(String sort) {
255                this.sort = sort;
256        }
257
258        public String getLang() {
259                return lang;
260        }
261
262        public void setLang(String lang) {
263                this.lang = lang;
264        }
265
266        public String getFullFormat() {         
267                return actionkey + "2" + format;
268        }
269
270        /**
271         * primitive identification of the target-proxy
272         * base for finding the right base_url in the props
273         * subclass has to override with its specific proxykey
274         * @return
275         */
276        public String getProxyKey() {
277                return "";
278        }
279       
280        public String getUserMsg() {
281                return userMsg;
282        }
283
284        public void setUserMsg(String userMsg) {
285                this.userMsg = this.userMsg + "\n" + userMsg;
286        }
287       
288        @Override
289        public void setServletRequest(HttpServletRequest arg0) {
290                request = arg0;
291        }
292
293        public HttpServletRequest getServletRequest() {
294                return request;
295        }
296
297
298        private InputStream resultStream;
299        private InputStream sourceStream;
300
301        /**
302         * The stream holding the resulting data to be sent back to the user as response
303         * @return
304         */
305        public InputStream getResultStream() {
306                return resultStream;
307    }
308        public void setResultStream(InputStream _resultStream){
309                resultStream = _resultStream;
310        }
311        public void setSourceStream(InputStream _sourceStream){
312                sourceStream = _sourceStream;
313        }
314       
315        /*
316        public InputStream getSourceStream() throws IOException {
317                return getTargetRequest().openStream();
318    }
319*/
320       
321        public JSONArray getRepositories(){
322                return repositories;
323        }
324       
325        public void setRepositories(JSONArray rep){
326                GenericProxyAction.repositories = rep;
327        }
328       
329        public JSONObject getWPOptions(){
330                return wp_options;
331        }
332       
333        public void setWPOptions(JSONObject op){
334                GenericProxyAction.wp_options = op;
335        }
336       
337        protected URL base_url ;
338       
339        public URL getBaseURL() throws MalformedURLException {         
340                if (base_url == null) {
341                        base_url = new URL(getBaseURI());//Admin.getConfig().getProperty(getProxyKey() + ".uri"));
342                }
343                return base_url;
344        }
345       
346        public String getBaseURI() {           
347                String uri =Admin.getConfig().getProperty(getProxyKey() + ".uri");             
348                return uri;
349        }
350
351       
352        public URL getTargetRequest() throws IOException {
353        // URL targetURL =new URL( base_url, compname + ".xml");
354                URL targetURL = getBaseURL();     
355                     
356        return targetURL;
357        }
358       
359        /*
360        public String getRequestKey() {
361                String key="";
362                if (getActionkey()!=null) {
363                        key += getActionkey() + "//-" ;
364                }
365                if (getQ()!=null) {
366                        key += getQ() + "//-" ;
367                }
368                if (getCollection()!=null) {
369                        key += getCollection();
370                }
371                 
372                return key;
373        }
374*/
375
376         public String getRequestKey() {
377                        String key="";
378                        if (getActionkey()!=null) {
379                                key += getActionkey() + "//-" ;
380                        }else {
381                                key +="//-" ;
382                        }
383                        if (getQ()!=null) {
384                                key += getQ() + "//-" ;
385                        } else {
386                                key +="//-" ;
387                        }
388                        if (getCollection()!=null) {
389                                key += getCollection() + "//-";
390                        } else {
391                                key +="//-" ;
392                        }
393                        if (getSquery()!=null) {
394                                key += getSquery() + "//-" ;
395                        } else {
396                                key +="//-" ;
397                        }
398                        if (getStartItem()!=null) {
399                                key += getStartItem() + "//-";
400                        }
401                                else{
402                                        key +="//-" ;
403                        }
404                        if (getMaximumItems()!=null) {
405                                key += getMaximumItems() + "//-";
406                        }
407                        else{
408                                key +="//-" ;
409                        }
410                       
411                        key += getRepository()  + "//-";
412                        key += getMaxdepth()  + "//-";
413                       
414                        if (getLang()!=null) {
415                                key += getLang() + "//-";
416                        }else{
417                                key +="//-" ;
418                        }
419                       
420                         
421                        return key;
422        }
423        public InputStream getSourceStream() throws IOException, NoStylesheetException {               
424                return getTargetRequest().openStream();
425                //      Admin.notifyUser(getProxyKey() + ".getSourceStream() - unable to open stream: " + getTargetRequest(); 
426        }
427       
428        public  static String convertStreamToString(InputStream is) { 
429               
430                BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
431                StringBuilder sb = new StringBuilder(); 
432                String line = null; 
433               
434                try {
435                        while ((line = reader.readLine()) != null) { 
436                                         sb.append(line + "\n"); 
437                        }
438                } catch (IOException e) {
439                        // TODO Auto-generated catch block
440                        e.printStackTrace();
441                }  finally {
442                        try {
443                                is.close();
444                        } catch (IOException e) {
445                                // TODO Auto-generated catch block
446                                e.printStackTrace();
447                        }
448                        try {
449                                is.reset();
450                        } catch (IOException e) {
451                                // TODO Auto-generated catch block
452                                e.printStackTrace();
453                        }
454                }
455                 
456               
457                return sb.toString(); 
458        }
459
460       
461        public static JSONArray createRepositories() throws IOException, InterruptedException, TransformerException, NoStylesheetException{
462                String path = Admin.getConfig().getProperty("workspaceprofile.path") + WorkspaceAction.WORKSPACE_FILENAME;//PROFILENAME_SERVER;
463                File file=new File(path);
464                InputStream in  = new BufferedInputStream( new FileInputStream(path));;
465               
466                MDTransformer transformer = new MDTransformer();
467                transformer.setSrcFile(file.toURI().toURL());
468                transformer.setParams(MDTransformer.createParamsMap("xml2json"));
469                InputStream jsonstream = transformer.transformXML(in);
470               
471                JSONObject json = JSONObject.fromObject(convertStreamToString(jsonstream));
472                JSONArray wparray = json.getJSONObject("Profiles").getJSONArray("WorkspaceProfiles");
473                JSONArray array = null;
474                for (int i = 0; i < wparray.size(); ++i) {     
475                        JSONObject wp = wparray.getJSONObject(i); 
476                        if (wp.get("Repositories") != null){
477                                array = wp.getJSONArray("Repositories");
478                                break;
479                        }
480                }       
481               
482                // repository as static variable
483                return array;
484       
485                // repository as session attribute
486                /*
487                HttpSession session = getServletRequest().getSession();
488                //JSONArray param = (JSONArray) session.getAttribute("repositories");
489                JSONArray param = new JSONArray();
490        param.add(array);
491        session.setAttribute("repositories", param);
492                 */
493        }
494       
495        public static JSONObject createWPOptions() throws IOException, InterruptedException, TransformerException, NoStylesheetException{
496                String path = Admin.getConfig().getProperty("workspaceprofile.path") + WorkspaceAction.WORKSPACE_FILENAME;//PROFILENAME_SERVER;
497                File file=new File(path);
498                InputStream in  = new BufferedInputStream( new FileInputStream(path));;
499               
500                MDTransformer transformer = new MDTransformer();
501                transformer.setSrcFile(file.toURI().toURL());
502                transformer.setParams(MDTransformer.createParamsMap("xml2json"));
503                InputStream jsonstream = transformer.transformXML(in);
504               
505                JSONObject json = JSONObject.fromObject(convertStreamToString(jsonstream));
506                JSONArray wparray = json.getJSONObject("Profiles").getJSONArray("WorkspaceProfiles");
507                JSONObject obj = null;
508                for (int i = 0; i < wparray.size(); ++i) {     
509                        JSONObject wp = wparray.getJSONObject(i); 
510                        if (wp.get("Options") != null){
511                                obj = wp.getJSONObject("Options");
512                                break;
513                        }
514                }       
515               
516                // options as static variable
517                return obj;
518       
519        }
520       
521        public String getWPOption(String opt_key){
522                String option_val = null;
523               
524               
525                if (wp_options == null ) {
526                        try {
527                                setWPOptions(GenericProxyAction.createWPOptions());
528                        } catch (IOException e) {
529                                // TODO Auto-generated catch block
530                                e.printStackTrace();
531                        } catch (InterruptedException e) {
532                                // TODO Auto-generated catch block
533                                e.printStackTrace();
534                        } catch (TransformerException e) {
535                                // TODO Auto-generated catch block
536                                e.printStackTrace();
537                        } catch (NoStylesheetException e) {
538                                // TODO Auto-generated catch block
539                                e.printStackTrace();
540                        }
541                }
542                // static options
543                if (wp_options != null){
544                        net.sf.json.JSONObject json = getWPOptions(); 
545                        option_val = json.getString(opt_key);
546                }
547               
548               
549                return option_val;
550               
551        }
552       
553        public String getRepositoryPath(){
554                String repository_path = null;
555               
556               
557                if (repositories == null ) {
558                        try {
559                                setRepositories(GenericProxyAction.createRepositories());
560                        } catch (IOException e) {
561                                // TODO Auto-generated catch block
562                                e.printStackTrace();
563                        } catch (InterruptedException e) {
564                                // TODO Auto-generated catch block
565                                e.printStackTrace();
566                        } catch (TransformerException e) {
567                                // TODO Auto-generated catch block
568                                e.printStackTrace();
569                        } catch (NoStylesheetException e) {
570                                // TODO Auto-generated catch block
571                                e.printStackTrace();
572                        }
573                }
574                // static repositories
575                net.sf.json.JSONArray json = getRepositories(); 
576                for(int i=0;i<json.size();i++){
577                        if (json.getJSONObject(i).getString("name").equals(getRepository())){
578                                repository_path =  json.getJSONObject(i).getString("uri");
579                        }
580                }
581                //Admin.notifyUser("REPOSITORY_PATH:" + repository_path);
582               
583                //session repositories
584                /*
585                HttpSession session = getServletRequest().getSession();
586                json = (net.sf.json.JSONArray) session.getAttribute("repositories");
587                for(int i=0;i<json.size();i++){
588                        if (json.getJSONObject(i).getInt("id") == getRepository()){
589                                repository_path =  json.getJSONObject(i).getString("uri");
590                        }
591                }
592                Admin.notifyUser("REPOSITORY_PATH-SESSIONATTR:" + repository_path);
593                */
594                return repository_path;
595               
596        }
597       
598        public String getRepositoryType(){
599        String typestr = "";
600               
601                if (repositories == null ) {
602                        try {
603                                setRepositories(GenericProxyAction.createRepositories());
604                        } catch (IOException e) {
605                                // TODO Auto-generated catch block
606                                e.printStackTrace();
607                        } catch (InterruptedException e) {
608                                // TODO Auto-generated catch block
609                                e.printStackTrace();
610                        } catch (TransformerException e) {
611                                // TODO Auto-generated catch block
612                                e.printStackTrace();
613                        } catch (NoStylesheetException e) {
614                                // TODO Auto-generated catch block
615                                e.printStackTrace();
616                        }
617                }
618                // static repositories
619                net.sf.json.JSONArray json = getRepositories(); 
620                for(int i=0;i<json.size();i++){
621                        if (json.getJSONObject(i).getString("name").equals(getRepository())){
622                                typestr =  json.getJSONObject(i).getString("type");
623                        }
624                }
625               
626                return (typestr);
627
628        }
629        public Boolean isSRURepository(){
630                //Boolean issru = false;
631                String typestr = getRepositoryType();
632               
633                return (typestr.equals("sru"));
634               
635        }
636        public String addDurationKey(){
637                String req_key = getRequestKey();
638       
639                Double duration_d;
640
641            duration_d = (double)duration; 
642            duration_d = duration_d/1000.0;
643                req_key += duration_d + "//-";
644                return req_key;
645        }
646       
647        public HashMap<String,String> createTransformerParams(){
648               
649                HashMap<String,String> hm = new HashMap<String,String>();
650               
651            if (getFullFormat() != null){
652                        hm.put("format", getFullFormat());
653            }
654                if (getColumns() != null){
655                        hm.put("cols", getColumns());
656                } else {
657                        hm.put("cols", "");
658                }
659                if (getStartItem() != null){
660                        hm.put("startItem", getStartItem());
661                }
662                if (getMaximumItems() != null){
663                        hm.put("maximumItems", getMaximumItems());     
664                }
665                if (getLang() != null){
666                        hm.put("lang", getLang());
667                }
668                if (getQ() != null){
669                        hm.put("q", getQ());
670                }
671                //if (getRepository() != null){
672                hm.put("repository_name", String.valueOf(getRepository()));     
673                //}
674       
675                return hm;
676               
677        }
678       
679       
680        public void prepare() throws Exception {               
681               
682                String req_key = getRequestKey();
683                Admin.notifyUser("request_key: " +  req_key); 
684                Admin.notifyUser(getProxyKey() + ".targetURL: " + getTargetRequest() + " .format:" + getFullFormat());
685               
686                // Caching
687                String xcid;
688       
689                // Admin.notifyUser("GPA.prepareSourceStream");
690               
691                if (getCache().equals(Cache.SKIP)) {
692                       
693                        sourceStream = getSourceStream();
694                       
695                } else { 
696                        if (getCache().equals(Cache.USE)) {
697                                        sourceStream = Cache.getCache().getFromCache(req_key);
698                        }
699                        if (sourceStream == null) { // either not in cache or cache_flag=refresh
700                                //sourceStream = getTargetRequest().openStream();
701                                long startMillis = System.currentTimeMillis();
702                                sourceStream = getSourceStream();
703                                duration = System.currentTimeMillis() - startMillis;
704                                req_key = addDurationKey();
705                               
706                                long now = System.currentTimeMillis();
707                                xcid = Cache.getCache().putInCache(req_key,sourceStream);                       
708                                //Admin.notifyUser("putting in cache: " + req_key);                     
709                                sourceStream = Cache.getCache().getFromCache(req_key);
710                        } /* else {
711                                Admin.notifyUser("reading from cache: " + req_key);
712                        } */
713                }
714                       
715                if (format.equals("xml")) {                     
716                        resultStream = sourceStream;   
717                }else {
718                        // set URL as srcFile (for MDTransformer to pass to xsl-scripts)
719                        MDTransformer transformer = new MDTransformer();
720                        transformer.setSrcFile(getTargetRequest());
721                        // getColumns
722                //      Admin.notifyUser("GPA.getRepository, before xsl:" + getRepository());
723                        transformer.setParams(createTransformerParams());
724                       
725                        resultStream = transformer.transformXML(sourceStream);//, getFullFormat(), getColumns(), getStartRecord(), getMaximumRecords(),getLang(),getQ(),String.valueOf(getRepository()));
726                }
727                       
728                Admin.notifyUser(getProxyKey() + " success:" + (resultStream!=null));
729        }
730
731        /**
732         * default Action method
733         */
734        public String execute() throws Exception {
735//              HttpServletRequest request = ServletActionContext.getRequest();
736
737               
738                //Admin.notifyUser("session-attrs:");
739        //Admin.notifyUser(getServletRequest().getRemoteUser() );
740        //Admin.notifyUser(String.valueOf(getSession()));
741       
742        long now = System.currentTimeMillis();
743
744                prepare();
745                long duration = (System.currentTimeMillis() - now);
746                //duration
747
748                if (resultStream == null) {
749                        return ERROR;   
750                } else {
751                        return SUCCESS;
752                }               
753        }
754
755
756}
Note: See TracBrowser for help on using the repository browser.