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

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

pazpar server functionality

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