source: MDService2/branches/MDService_simple3/src/eu/clarin/cmdi/mdservice/action/SRUAction.java @ 1628

Last change on this file since 1628 was 1628, checked in by gaba, 13 years ago
File size: 13.0 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import java.io.BufferedReader;
4import java.io.ByteArrayInputStream;
5import java.io.IOException;
6import java.io.InputStream;
7import java.io.InputStreamReader;
8import java.io.StringWriter;
9import java.io.UnsupportedEncodingException;
10import java.util.HashMap;
11import javax.xml.parsers.ParserConfigurationException;
12import javax.xml.transform.TransformerConfigurationException;
13import javax.xml.transform.TransformerException;
14import javax.xml.transform.TransformerFactory;
15import javax.xml.transform.TransformerFactoryConfigurationError;
16import javax.xml.transform.dom.DOMSource;
17import javax.xml.transform.stream.StreamResult;
18
19import org.w3c.dom.Document;
20import org.w3c.dom.Node;
21
22import eu.clarin.cmdi.mdservice.internal.Cache;
23import eu.clarin.cmdi.mdservice.internal.Utils;
24import eu.clarin.cmdi.mdservice.model.Diagnostic;
25import eu.clarin.cmdi.mdservice.model.Query;
26import eu.clarin.cmdi.mdservice.model.WorkspaceProfile;
27import eu.clarin.cmdi.mdservice.proxy.MDRepoProxy;
28import eu.clarin.cmdi.mdservice.proxy.Pz2Proxy;
29import eu.clarin.cmdi.mdservice.proxy.SRUProxy;
30
31
32
33
34public class SRUAction extends RepoAction
35{
36
37        private static final long serialVersionUID = 1L;
38       
39        /**
40         * Properties to be filled by Struts with according request-parameters
41         */     
42        /*
43        private String q;
44        private String version;
45        private String operation;
46        private String query;
47        private String scanClause;
48        private int startRecord;
49        private int maximumRecords;
50        private String recordPacking;
51        private String recordSchema;
52        private String recordXPath;
53        private int resultSetTTL;
54        private String sortKeys;
55        private String stylesheet;     
56        private String x_cmd_repository;
57        private String x_cmd_collections;
58        private Set paramSet;
59*/
60       
61        private static int OP_SEARCHRETRIEVE = 1;
62        private static int OP_EXPLAIN = 2;
63        private static int OP_SCAN = 3;
64       
65       
66        //TODO cache after analysis ?
67        @Override
68        public String getCache() {
69                return Cache.SKIP;
70        }
71       
72        @Override
73        public String getRepository() {
74                if (getParams().get("repository") == null){
75                        return getParam("x-cmd-repository");
76                }
77                return getParam("repository");
78        }
79       
80        @Override
81        public String getFormat() {
82                if (getParams().get("format") == null){
83                        if (getParams().get("x-cmd-format") == null){
84                                return "xml";
85                        }
86                        return getParam("x-cmd-format");
87                }
88                return getParam("format");
89        }
90       
91         private final static HashMap<String,Integer> operation_code = new HashMap<String,Integer>();
92         static
93         {       
94                 operation_code.put("searchRetrieve", OP_SEARCHRETRIEVE);
95                 operation_code.put("explain", OP_EXPLAIN);
96                 operation_code.put("scan", OP_SCAN);
97         }
98         
99        /**
100         * primitive identification of the target-proxy
101         * base for finding the right base_url in the props
102         * subclass has to override with its specific proxykey
103         * @return
104         */
105        public String getProxyKey() {
106                return "";
107        }
108/*
109        @Override
110        protected void setDefaultParams() {             
111                // set defaults
112        /*      if ( params.get("version") == null){
113                        addParam("version","1.2");
114                }
115                if ( params.get("operation") == null){
116                        addParam("operation","searchRetrieve");
117                }
118                //q=query                       
119                if (getQ() != null) {
120                        addParam("q",getQ());
121                        addParam("query",getQ());
122                } else {
123                        addParam("q",this.getParam("query"));
124                }
125               
126                if ( params.get("startRecord") == null){
127                        addParam("startRecord","1");
128                }
129                if ( params.get("maximumRecords") == null){
130                        addParam("maximumRecords","50");
131                }
132               
133                if ( params.get("x-cmd-maxdepth") == null){
134                        if (params.get("maxdepth") == null){
135                                addParam("maxdepth","2");
136                        }
137                } else {
138                        addParam("maxdepth",params.get("x-cmd-maxdepth")[0]);
139                }
140               
141                if ( params.get("x-cmd-repository") == null){
142                        if (params.get("repository") == null){
143                                addParam("repository",WorkspaceProfile.getRepositoryByIndex(0));
144                        }
145                } else {
146                        addParam("repository",params.get("x-cmd-repository")[0]);
147                }
148               
149                if ( params.get("x-cmd-cache") == null){
150                        if (params.get("cache") == null){
151                                addParam("cache",Cache.SKIP);
152                        }
153                } else {
154                        addParam("cache",params.get("x-cmd-cache")[0]);
155                }
156               
157                if ( params.get("x-cmd-lang") == null){
158                        if (params.get("lang") == null){
159                                addParam("lang","en");
160                        }
161                } else {
162                        addParam("lang",params.get("x-cmd-lang")[0]);
163                }
164               
165                if ( params.get("x-cmd-format") == null){
166                        if (params.get("format") == null){
167                                if (this.format == null) {
168                                        addParam("format","xml");
169                                } else if (this.format.equals("")){
170                                        addParam("format","xml");
171                                } else {
172                                        addParam("format",this.format);
173                                }
174                        }
175                } else {
176                        addParam("format",params.get("x-cmd-format")[0]);
177                }
178
179                addParam("fullformat",getFullFormat());
180               
181        }
182*/
183        /*
184        public void prepareOperation() throws UnsupportedEncodingException{
185               
186                mdrepoproxyaction = new MDRepoProxyAction();
187                mdrepoproxyaction.setDiagnostics(diagnostics);
188                mdrepoproxyaction.setActionkey(hash_operations.get(this.getOperation()));
189               
190                // set the SRU extern property in proxyaction
191                if (this.getX_cmd_repository() != null ) {
192                        mdrepoproxyaction.setRepository(this.getX_cmd_repository());
193                        //TODO\
194                        if (mdrepoproxyaction.getBaseURI() == null) this.Diagnostics().Add(Diagnostic.UNSUPPORTED_PARAMETERVALUE, "Unknown repository." + getX_cmd_repository());
195                }
196               
197                if (operation.equals("searchRetrieve")){
198                       
199                        //query
200                        mdrepoproxyaction.setSquery("");
201                        if (this.query == null) {
202                                this.Diagnostics().Add(Diagnostic.MANDATORY_NOTSUPPLIED, "query");
203                                //return -1;
204                        }
205                        mdrepoproxyaction.setQ(getQuery());                     
206                        mdrepoproxyaction.setFormat("xml");
207                       
208                        if ((this.startRecord < 0 ) ||((getServletRequest().getParameter("startRecord") != null)&&(getServletRequest().getParameter("startRecord").equals("0")))) {
209                                this.Diagnostics().Add(new Diagnostic(Diagnostic.UNSUPPORTED_PARAMETERVALUE, "startRecord must by grater than 0."));//,Diagnostic.NONFATALNONSURORGATE));
210                                //mdrepoproxyaction.setStartItem("1");
211                        } else {
212                                mdrepoproxyaction.setStartItem(Integer.toString(getStartRecord()));
213                        }
214               
215                        if ((this.maximumRecords < 0 ) ||((getServletRequest().getParameter("maximumRecords") != null) && (getServletRequest().getParameter("maximumRecords").equals("0")))){
216                                   this.Diagnostics().Add(new Diagnostic(Diagnostic.UNSUPPORTED_PARAMETERVALUE,
217                                                   "maximumRecords must by greater than 0."));
218                        } else {
219                                mdrepoproxyaction.setMaximumItems(Integer.toString(this.getMaximumRecords())); 
220                        }
221                       
222                        if (this.getX_cmd_repository() != null ) {
223                                mdrepoproxyaction.setRepository(this.getX_cmd_repository());
224                                //TODO\
225                                if (mdrepoproxyaction.getBaseURI() == null) this.Diagnostics().Add(Diagnostic.UNSUPPORTED_PARAMETERVALUE, "Unknown repository." + getX_cmd_repository());
226                        }
227                        if (this.getX_cmd_collections() != null ) {
228                                mdrepoproxyaction.setCollection(this.getX_cmd_collections());
229                        }
230
231                } else {
232                        if (operation.equals("explain") || operation == null){
233                                log.debug("explaining", "debug");
234                        }else {
235                                if (operation.equals("scan")){
236                                        if (this.scanClause == null) {
237                                                this.Diagnostics().Add(Diagnostic.MANDATORY_NOTSUPPLIED, "scanClause");
238                                                //return -1;
239                                        } else{
240                                                if (this.scanClause.equals("cmd.Collections")){
241                                                       
242                                                } else {
243                                                        if (this.scanClause.equals("cmd.Repository")){
244                                                                XMLSerializer xmlserializer = new XMLSerializer();
245                                                                String xml = xmlserializer.write( WorkspaceProfile.getRepositories());//mdrepoproxyaction.getRepositories() ); 
246                                                                this.setResultStream(new ByteArrayInputStream(xml.getBytes("UTF-8")));
247
248                                                        } else {
249                                                               
250                                                        }
251                                                }
252                                        }
253                                }else {
254                                        this.Diagnostics().Add(Diagnostic.UNSUPPOERTED_OPERATION, "Only searchRetrieve,explain scan supported.");                               }
255                        }
256                }
257        }
258       
259        public void sru2MD() throws UnsupportedEncodingException{
260                // special handling of parameter setting, x-cmd-... not alowed in java
261                this.setX_cmd_collections(getServletRequest().getParameter("x-cmd-collections"));               
262                // root call own SRU SERVER
263                //operation
264                if (operation.equals("explain") || operation == null){
265                        // TODO: version param is mandatory for explain as well, but for root-request not!
266                        //explain
267                        termsproxyaction = new TermsProxyAction();
268                        termsproxyaction.setDiagnostics(diagnostics);
269                        termsproxyaction.setActionkey("terms");
270                       
271                        termsproxyaction.setQ("all");                   
272                        termsproxyaction.setFormat("sru-explain");                     
273                       
274                        //return -1;
275                } else {                               
276                        //version               
277                        if (this.version == null) {
278                                this.Diagnostics().Add(Diagnostic.MANDATORY_NOTSUPPLIED, "version");
279                                //return -1;
280                        } else {
281                                if (!version.equals("1.2")) {
282                                        this.Diagnostics().Add(Diagnostic.UNSUPPORTED_VERSION, "Version 1.2 supported.");
283                                        //return -1;
284                                }
285                        }
286                       
287                        prepareOperation();
288                }
289               
290        }
291       
292        public void  prepareMD() throws Exception{
293                sru2MD();
294                if (Diagnostics().Accepted()){
295                        // root-explain
296                        if (this.termsproxyaction != null) {                   
297                                if (this.termsproxyaction.execute() == SUCCESS){
298                                        this.setResultStream(this.termsproxyaction.getResultStream());
299                                        //return SUCCESS;
300                                }
301                        } else {
302                                //TODO diagnostic                       
303                                if (this.mdrepoproxyaction.getTargetRequest() == null) {
304                                        Diagnostics().Add(Diagnostic.QUERYSYNTAXERROR);
305                                        //return ERROR;
306                                }
307                                if (this.mdrepoproxyaction.execute() == SUCCESS){
308                                        this.setResultStream(this.mdrepoproxyaction.getResultStream());
309                                        postprocess();
310                                        //return SUCCESS;
311                                }
312                        }
313                }
314                //return ERROR;
315        }
316        */
317/** TODO: move to Utils
318 *
319 * @param stream
320 * @return
321 * @throws IOException
322 */
323        /*
324        public static String inputStreamAsString(InputStream stream)
325                throws IOException {
326                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
327                StringBuilder sb = new StringBuilder();
328                String line = null;
329
330                while ((line = br.readLine()) != null) {
331                sb.append(line + "\n");
332                }
333
334                br.close();
335                return sb.toString();
336        }
337
338       
339
340        public void postprocess() throws TransformerConfigurationException, UnsupportedEncodingException, ParserConfigurationException, TransformerException, TransformerFactoryConfigurationError{
341                //recordPacking
342                if (this.getRecordPacking() != null){
343                        if (this.getRecordPacking().toLowerCase().equals("string")){
344                               
345                                try {
346                                        // FIXME: Which package is IOUTils from?
347                                        this.setResultStream(IOUtils.toInputStream(StringEscapeUtils.escapeXml(inputStreamAsString(this.getResultStream()))));
348                                } catch (IOException e) {
349                                        // TODO Auto-generated catch block
350                                        e.printStackTrace();
351                                }
352
353                        }
354                }
355               
356                // add diagnostics
357                if (getDiagnostics().Exists()){
358                        Document doc = Utils.stream2Document(getResultStream());
359                        Node r_element=  doc.getElementsByTagName("searchRetrieveResponse").item(0);
360                        Document ddoc = getDiagnostics().buildXMLDocument();
361                        Node d_element=  ddoc.getElementsByTagName("diagnostics").item(0);
362                        doc.adoptNode(d_element);
363                        r_element.appendChild(d_element);
364                        DOMSource source = new DOMSource(doc);   
365                        StringWriter xmlAsWriter = new StringWriter();   
366                        StreamResult result = new StreamResult(xmlAsWriter);   
367                        TransformerFactory.newInstance().newTransformer().transform(source, result);
368                        this.setResultStream(new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")));
369                }
370        }
371       
372        //TODO create query + query.toURLParams ?
373        public String createURLParams(){
374                String params = "";
375               
376                //TODO params
377                /*
378                if (paramSet == null){
379                        if (!(operation == null)){
380                                params = params + "operation=" + operation;
381                        }
382                        if (!(version == null)){
383                                params = params + "&version=" + version;
384                        }
385                        if (!(query == null)){
386                                params = params + "&query=" + query;
387                        }
388                        if (getStartRecord() > 0){
389                                params = params + "&startRecord=" + String.valueOf(getStartRecord());
390                        }
391                        if (getMaximumRecords()> 0){
392                                params = params + "&numRecords=" + String.valueOf(getMaximumRecords());
393                        }
394                } else {
395                        Iterator i = paramSet.iterator();
396                        params = "";
397                    while(i.hasNext()){
398                              Map.Entry me = (Map.Entry)i.next();
399                              if (!(me.getKey().equals("x-cmd-repository") || me.getKey().equals("x-cmd-collections"))){
400                                      params = params + "&" + me.getKey() + "=" + ((String[])me.getValue())[0]; 
401                              }
402                        }
403                    params = params.substring(1);
404
405                }
406
407                return params;
408        }
409*/     
410
411/*     
412        @Override
413        public void prepare() throws Exception{
414                //this.setX_cmd_repository(getServletRequest().getParameter("x-cmd-repository"));
415                //this.setRepository(this.getX_cmd_repository());
416                //TODO xsl usage according particular repositories ?
417                //this.setActionkey("sru");
418                //this.setFormat("xml");
419               
420                //extern SRU repository
421                if (WorkspaceProfile.isSRURepository(getRepository()) || this.getBaseURI() == null){
422                        super.prepare();
423                }
424                else {
425                         prepareMD();
426                }
427               
428        }
429*/
430        @Override
431        public void setTargetProxy(){
432               
433                //Query query = new Query();
434                switch (WorkspaceProfile.RepositoryType.toRepositoryType(WorkspaceProfile.getRepositoryType(getRepository())))
435                {               
436                    case PAZPAR: 
437                        setTargetProxy(new Pz2Proxy(new Query(getActionkey(), this.getParams())));
438                        return;
439                    case SRU:
440                        setTargetProxy(new SRUProxy(new Query(Query.SRUEXTERN,getParams())));
441                        return;
442                    case MD:
443                        setTargetProxy(new MDRepoProxy(new Query(Query.RECORDSET,getParams())));
444                        return; 
445                    default:
446                        //TODO error  = bad workspaceProfile configuration
447                        getDiagnostics().Add(Diagnostic.SYSTEM_ERROR, "Error in workspaceprofile configuration", "repository=" + getRepository() );
448                }
449}
450}
Note: See TracBrowser for help on using the repository browser.