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
RevLine 
[466]1package eu.clarin.cmdi.mdservice.action;
2
[860]3import java.io.BufferedInputStream;
4import java.io.BufferedReader;
5import java.io.File;
6import java.io.FileInputStream;
[519]7import java.io.IOException;
[466]8import java.io.InputStream;
[860]9import java.io.InputStreamReader;
[519]10import java.net.MalformedURLException;
[849]11import java.net.URISyntaxException;
[466]12import java.net.URL;
[879]13import java.util.HashMap;
[466]14
[627]15import javax.servlet.http.HttpServletRequest;
[860]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;
[1429]23//import net.sf.saxon.Controller;
24//import net.sf.saxon.event.MessageEmitter;
[860]25
26
[627]27import org.apache.struts2.interceptor.ServletRequestAware;
28
[466]29import com.opensymphony.xwork2.ActionSupport;
30
[1187]31import eu.clarin.cmdi.mdservice.model.Diagnostics;
32
[466]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 */
[627]41public class GenericProxyAction extends ActionSupport
42implements ServletRequestAware
43{
[466]44
45        private static final long serialVersionUID = 1L;
46       
[860]47        private static JSONArray repositories = null;
[1491]48        private static JSONObject wp_options = null;
[1187]49       
50        private Diagnostics diagnostics;
[466]51        /**
52         * Properties to be filled by Struts with according request-parameters
53         */     
54        private String actionkey;
55        private String q;
[745]56        private String squery;
[713]57        private String cache = Cache.USE;
[466]58        private String collection;
[690]59        private String columns;
[1046]60        private String startItem;
61        private String maximumItems;
62        private String sort;
[768]63        private String lang="en";
[1046]64        private int maxdepth;   
[466]65        private String format;
[1029]66        private String options;
[890]67        private String actionContentType;
[466]68        private String userMsg;
[1187]69        private String repository;
[627]70        //private Map<String,Object> session;
71         private HttpServletRequest request; 
[870]72         private long duration = 0;
73         
[980]74         public GenericProxyAction(){
75                 super();
76                 initialize();
77         }
78         
[1187]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();
[1488]96                        } catch (NoStylesheetException e) {
97                                // TODO Auto-generated catch block
98                                e.printStackTrace();
[1187]99                        }
100         }
101         
[980]102         protected void  initialize(){
[1187]103                 //repository = 1;
104                 setRepositoryByIndex(0);                               
[980]105         }
[1187]106         
[1215]107         
[1187]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         }
[466]121        public String getQ() {
122                return q;
123        }
124
[764]125        public void setQ(String pq) {
126                if (pq == null) pq="";
127                /*
[762]128                if (q != null){
129                        if (q.trim().length() == 0){
130                                q = null;
131                        }
132                }
[764]133                */
134                this.q = pq;
[466]135        }
136
[745]137        public String getSquery() {
138                return squery;
139        }
140
[764]141        public void setSquery(String psquery) {
142                if (psquery==null) psquery="";
143                this.squery = psquery;
[745]144        }
145       
[689]146        public String getCache() {
147                return cache;
148        }
149
150        public void setCache(String cache) {
151                this.cache = cache;
152        }
153
[466]154        public String getCollection() {
155                return collection;
156        }
157
158        public void setCollection(String collection) {
159                this.collection = collection;
160        }
[690]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        }
[466]171
[690]172        public void setColumns(String columns) {
173                this.columns = columns;
174        }
175       
[466]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        }
[890]191
[1029]192        public String getOptions() {
193                return options;
194        }
195
196        public void setOptions(String options) {
197                this.options = options;
198        }
199
[890]200        public String getActionContentType() {
[1029]201                if (format.toLowerCase().startsWith("html")) {
[1488]202                        this.actionContentType = "text/html";           
203                        //this.actionContentType = "application/xhtml+xml";
[1029]204                } else {
[890]205                        this.actionContentType = "text/xml";
206                }
207               
208                return actionContentType;
209        }
210
211        public void setActionContentType(String actionContentType) {
212                this.actionContentType = actionContentType;
213        }
[466]214       
[890]215
[1187]216        public void setRepository(String repository) {
[832]217                this.repository = repository;
218        }
219       
[1187]220        public String getRepository() {
[862]221                //default repository = 1 (set on init)
[832]222                return repository;
223        }
[466]224        public String getActionkey() {
225                return actionkey;
226        }
227
228        public void setActionkey(String actionKey) {
229                actionkey = actionKey;
230        }
[890]231
[706]232       
[1046]233        public String getStartItem() {
234                return startItem;
[706]235        }
[466]236
[1046]237        public void setStartItem(String startItem) {
238                this.startItem = startItem;
[706]239        }
240
[1046]241        public String getMaximumItems() {
242                return maximumItems;
[706]243        }
244
[1046]245        public void setMaximumItems(String maximumItems) {
246                this.maximumItems = maximumItems;
[706]247        }
248       
[745]249
[1046]250        public String getSort() {
251                return sort;
252        }
253
254        public void setSort(String sort) {
255                this.sort = sort;
256        }
257
[768]258        public String getLang() {
259                return lang;
260        }
261
262        public void setLang(String lang) {
263                this.lang = lang;
264        }
265
[466]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        }
[690]287       
[627]288        @Override
289        public void setServletRequest(HttpServletRequest arg0) {
290                request = arg0;
291        }
[466]292
[627]293        public HttpServletRequest getServletRequest() {
294                return request;
295        }
[466]296
[627]297
[466]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    }
[582]308        public void setResultStream(InputStream _resultStream){
309                resultStream = _resultStream;
310        }
311        public void setSourceStream(InputStream _sourceStream){
312                sourceStream = _sourceStream;
313        }
314       
[466]315        /*
316        public InputStream getSourceStream() throws IOException {
317                return getTargetRequest().openStream();
318    }
319*/
320       
[860]321        public JSONArray getRepositories(){
322                return repositories;
323        }
324       
325        public void setRepositories(JSONArray rep){
[1187]326                GenericProxyAction.repositories = rep;
[860]327        }
328       
[1491]329        public JSONObject getWPOptions(){
330                return wp_options;
331        }
332       
333        public void setWPOptions(JSONObject op){
334                GenericProxyAction.wp_options = op;
335        }
336       
[768]337        protected URL base_url ;
[466]338       
[519]339        public URL getBaseURL() throws MalformedURLException {         
[466]340                if (base_url == null) {
[849]341                        base_url = new URL(getBaseURI());//Admin.getConfig().getProperty(getProxyKey() + ".uri"));
[466]342                }
343                return base_url;
344        }
[849]345       
[795]346        public String getBaseURI() {           
[772]347                String uri =Admin.getConfig().getProperty(getProxyKey() + ".uri");             
348                return uri;
349        }
350
[466]351       
[519]352        public URL getTargetRequest() throws IOException {
[466]353        // URL targetURL =new URL( base_url, compname + ".xml");
354                URL targetURL = getBaseURL();     
355                     
356        return targetURL;
357        }
358       
[849]359        /*
[466]360        public String getRequestKey() {
361                String key="";
362                if (getActionkey()!=null) {
[704]363                        key += getActionkey() + "//-" ;
[466]364                }
365                if (getQ()!=null) {
[704]366                        key += getQ() + "//-" ;
[466]367                }
368                if (getCollection()!=null) {
369                        key += getCollection();
370                }
371                 
372                return key;
373        }
[849]374*/
[466]375
[849]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                        }
[1046]398                        if (getStartItem()!=null) {
399                                key += getStartItem() + "//-";
[849]400                        }
401                                else{
402                                        key +="//-" ;
403                        }
[1046]404                        if (getMaximumItems()!=null) {
405                                key += getMaximumItems() + "//-";
[849]406                        }
407                        else{
408                                key +="//-" ;
409                        }
410                       
[860]411                        key += getRepository()  + "//-";
[849]412                        key += getMaxdepth()  + "//-";
413                       
414                        if (getLang()!=null) {
[870]415                                key += getLang() + "//-";
416                        }else{
417                                key +="//-" ;
[849]418                        }
[870]419                       
[849]420                         
421                        return key;
422        }
[1488]423        public InputStream getSourceStream() throws IOException, NoStylesheetException {               
[519]424                return getTargetRequest().openStream();
425                //      Admin.notifyUser(getProxyKey() + ".getSourceStream() - unable to open stream: " + getTargetRequest(); 
426        }
427       
[860]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
[582]460       
[1488]461        public static JSONArray createRepositories() throws IOException, InterruptedException, TransformerException, NoStylesheetException{
[1417]462                String path = Admin.getConfig().getProperty("workspaceprofile.path") + WorkspaceAction.WORKSPACE_FILENAME;//PROFILENAME_SERVER;
[860]463                File file=new File(path);
464                InputStream in  = new BufferedInputStream( new FileInputStream(path));;
465               
[911]466                MDTransformer transformer = new MDTransformer();
[1488]467                transformer.setSrcFile(file.toURI().toURL());
[911]468                transformer.setParams(MDTransformer.createParamsMap("xml2json"));
469                InputStream jsonstream = transformer.transformXML(in);
[860]470               
471                JSONObject json = JSONObject.fromObject(convertStreamToString(jsonstream));
[1417]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                }       
[860]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       
[1491]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;
[860]518       
[1491]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       
[860]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();
[1488]569                        } catch (NoStylesheetException e) {
570                                // TODO Auto-generated catch block
571                                e.printStackTrace();
[860]572                        }
573                }
574                // static repositories
575                net.sf.json.JSONArray json = getRepositories(); 
576                for(int i=0;i<json.size();i++){
[1187]577                        if (json.getJSONObject(i).getString("name").equals(getRepository())){
[860]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       
[1481]598        public String getRepositoryType(){
599        String typestr = "";
[1455]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();
[1488]613                        } catch (NoStylesheetException e) {
614                                // TODO Auto-generated catch block
615                                e.printStackTrace();
[1455]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())){
[1467]622                                typestr =  json.getJSONObject(i).getString("type");
[1455]623                        }
624                }
625               
[1481]626                return (typestr);
627
628        }
629        public Boolean isSRURepository(){
630                //Boolean issru = false;
631                String typestr = getRepositoryType();
632               
[1467]633                return (typestr.equals("sru"));
[1455]634               
635        }
[870]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       
[879]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());
[1392]656                } else {
657                        hm.put("cols", "");
[879]658                }
[1046]659                if (getStartItem() != null){
660                        hm.put("startItem", getStartItem());
[879]661                }
[1046]662                if (getMaximumItems() != null){
663                        hm.put("maximumItems", getMaximumItems());     
[879]664                }
665                if (getLang() != null){
666                        hm.put("lang", getLang());
667                }
668                if (getQ() != null){
669                        hm.put("q", getQ());
670                }
[1187]671                //if (getRepository() != null){
672                hm.put("repository_name", String.valueOf(getRepository()));     
673                //}
[879]674       
675                return hm;
676               
677        }
678       
[1481]679       
[466]680        public void prepare() throws Exception {               
681               
[789]682                String req_key = getRequestKey();
683                Admin.notifyUser("request_key: " +  req_key); 
[466]684                Admin.notifyUser(getProxyKey() + ".targetURL: " + getTargetRequest() + " .format:" + getFullFormat());
685               
686                // Caching
[582]687                String xcid;
[789]688       
689                // Admin.notifyUser("GPA.prepareSourceStream");
690               
[689]691                if (getCache().equals(Cache.SKIP)) {
692                       
[582]693                        sourceStream = getSourceStream();
[689]694                       
695                } else { 
696                        if (getCache().equals(Cache.USE)) {
[789]697                                        sourceStream = Cache.getCache().getFromCache(req_key);
[689]698                        }
699                        if (sourceStream == null) { // either not in cache or cache_flag=refresh
700                                //sourceStream = getTargetRequest().openStream();
[870]701                                long startMillis = System.currentTimeMillis();
[689]702                                sourceStream = getSourceStream();
[870]703                                duration = System.currentTimeMillis() - startMillis;
704                                req_key = addDurationKey();
705                               
706                                long now = System.currentTimeMillis();
[789]707                                xcid = Cache.getCache().putInCache(req_key,sourceStream);                       
[1076]708                                //Admin.notifyUser("putting in cache: " + req_key);                     
[789]709                                sourceStream = Cache.getCache().getFromCache(req_key);
[1076]710                        } /* else {
[789]711                                Admin.notifyUser("reading from cache: " + req_key);
[1076]712                        } */
[582]713                }
[689]714                       
[466]715                if (format.equals("xml")) {                     
716                        resultStream = sourceStream;   
717                }else {
[911]718                        // set URL as srcFile (for MDTransformer to pass to xsl-scripts)
719                        MDTransformer transformer = new MDTransformer();
720                        transformer.setSrcFile(getTargetRequest());
[862]721                        // getColumns
[1076]722                //      Admin.notifyUser("GPA.getRepository, before xsl:" + getRepository());
[911]723                        transformer.setParams(createTransformerParams());
[1429]724                       
[911]725                        resultStream = transformer.transformXML(sourceStream);//, getFullFormat(), getColumns(), getStartRecord(), getMaximumRecords(),getLang(),getQ(),String.valueOf(getRepository()));
[466]726                }
727                       
728                Admin.notifyUser(getProxyKey() + " success:" + (resultStream!=null));
729        }
730
731        /**
732         * default Action method
733         */
734        public String execute() throws Exception {
[627]735//              HttpServletRequest request = ServletActionContext.getRequest();
736
[466]737               
[1076]738                //Admin.notifyUser("session-attrs:");
739        //Admin.notifyUser(getServletRequest().getRemoteUser() );
[627]740        //Admin.notifyUser(String.valueOf(getSession()));
[762]741       
[870]742        long now = System.currentTimeMillis();
743
[466]744                prepare();
[870]745                long duration = (System.currentTimeMillis() - now);
746                //duration
747
[466]748                if (resultStream == null) {
749                        return ERROR;   
750                } else {
751                        return SUCCESS;
752                }               
753        }
754
[627]755
[466]756}
Note: See TracBrowser for help on using the repository browser.