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

Last change on this file since 1807 was 1807, checked in by gaba, 12 years ago

fcs/scan

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