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

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

changes to columns, terms (unfinished) ; .ui-context-dialog

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