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

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