KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > webdav > protocol > http > SearchMethod


1 /*
2  * (C) Copyright Simulacra Media Ltd, 2004. All rights reserved.
3  *
4  * The program is provided "AS IS" without any warranty express or
5  * implied, including the warranty of non-infringement and the implied
6  * warranties of merchantibility and fitness for a particular purpose.
7  * Simulacra Media Ltd will not be liable for any damages suffered by you as a result
8  * of using the Program. In no event will Simulacra Media Ltd be liable for any
9  * special, indirect or consequential damages or lost profits even if
10  * Simulacra Media Ltd has been advised of the possibility of their occurrence.
11  * Simulacra Media Ltd will not be liable for any third party claims against you.
12  *
13  */

14
15 package com.ibm.webdav.protocol.http;
16
17 import java.io.*;
18 import java.util.logging.*;
19
20 import javax.servlet.http.*;
21 import javax.xml.parsers.*;
22
23 import org.w3c.dom.*;
24
25 import com.ibm.webdav.*;
26 import com.ibm.webdav.impl.*;
27
28
29 /**
30  * Executes the WebDAV DASL Search method.
31  *
32  * @author Michael Bell
33  * @since November 13, 2003
34  */

35 public class SearchMethod extends WebDAVMethod {
36     private static Logger m_logger = Logger.getLogger(SearchMethod.class.getName());
37
38     
39     public static final String JavaDoc TAG_QUERY_SCHEMA_DISCOVERY = "query-schema-discovery";
40     public static final String JavaDoc TAG_SEARCHREQUEST = "searchrequest";
41
42     /** Construct a PropFindMethod.
43     * @param request the servlet request
44     * @param response the servlet response
45     * @exception com.ibm.webdav.WebDAVException
46     */

47     public SearchMethod(HttpServletRequest request,
48                           HttpServletResponse response)
49                    throws WebDAVException {
50         super(request, response);
51         methodName = "SEARCH";
52     }
53
54     /** Execute the method.
55     * @return the result status code
56     */

57     public WebDAVStatus execute() {
58         MultiStatus multiStatus = null;
59
60         try {
61             // get any arguments out of the headers
62
String JavaDoc depth = context.getRequestContext().depth();
63
64             Document contents = null;
65
66             if (context.getRequestContext().contentLength() > 0) {
67                 // get the request entity body and parse it
68
WebDAVErrorHandler errorHandler = new WebDAVErrorHandler(
69                                                           resource.getURL()
70                                                                   .toString());
71
72                 /*Parser xmlParser = new Parser(resource.getURL().toString(), errorListener, null);
73                 xmlParser.setWarningNoDoctypeDecl(false);
74                 xmlParser.setProcessNamespace(true);
75                 contents = xmlParser.readStream(request.getReader());*/

76                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
77                 factory.setNamespaceAware(true);
78
79                 DocumentBuilder docbuilder = factory.newDocumentBuilder();
80                 docbuilder.setErrorHandler(errorHandler);
81                 contents = docbuilder.parse(
82                                    new org.xml.sax.InputSource JavaDoc(
83                                            request.getReader()));
84
85                 if (errorHandler.getErrorCount() > 0) {
86                     throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST,
87                                               "Syntax error in SEARCH request entity body");
88                 }
89             }
90
91             // get the arguments for the getProperties() method, and figure
92
// out which method variant to call.
93
if (ResourceImpl.debug) {
94                 System.err.println("property request entity:");
95
96                 PrintWriter pout = new PrintWriter(System.err);
97                 pout.print(XMLUtility.printNode(contents.getDocumentElement()));
98
99                 //((Document) contents).printWithFormat(pout);
100
}
101
102             Element rootEl = (Element) ((contents == null)
103                                           ? null : contents.getDocumentElement());
104
105             if(rootEl.getNamespaceURI().equals("DAV:") == false) {
106               throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST,
107                                               "Wrong namespace for request");
108             }
109
110
111             if(rootEl.getLocalName().equals(SearchMethod.TAG_QUERY_SCHEMA_DISCOVERY)) {
112               Element searchEl = (Element)rootEl.getElementsByTagName("*").item(0);
113
114               SearchRequest searchReq = SearchRequestFactory.getSearchRequest(searchEl);
115
116               multiStatus = resource.getSearchSchema(context,searchReq);
117
118             } else if(rootEl.getLocalName().equals(SearchMethod.TAG_SEARCHREQUEST)) {
119               Element searchEl = (Element)rootEl.getElementsByTagName("*").item(0);
120
121               SearchRequest searchReq = SearchRequestFactory.getSearchRequest(searchEl);
122               try {
123                 multiStatus = resource.executeSearch(context,searchReq);
124               } catch(WebDAVException e) {
125                 String JavaDoc sMsg = e.getMessage();
126                 if(sMsg != null && sMsg.indexOf("scope") >0) {
127                   setStatusCode(e.getStatusCode());
128                   PrintWriter pout = new PrintWriter(response.getWriter(), false);
129                   pout.print(this.getScopeErrorResponse(searchReq));
130                   pout.close();
131                 }
132                 throw e;
133               }
134             }
135
136
137             context.getResponseContext().contentType("text/xml");
138             setResponseHeaders();
139             setStatusCode(WebDAVStatus.SC_MULTI_STATUS);
140
141             // output the results as an XML document
142
Document results = multiStatus.asXML();
143
144             // set the character encoding for the document to that specified by
145
// the client in the Accept header
146
//((Document) results).setEncoding(getResponseCharset());
147
if (ResourceImpl.debug) {
148                 System.err.println("property results:");
149
150                 PrintWriter pout = new PrintWriter(System.err);
151                 pout.print(XMLUtility.printNode(results.getDocumentElement()));
152
153             }
154
155             PrintWriter pout = new PrintWriter(response.getWriter(), false);
156             pout.print(XMLUtility.printNode(results.getDocumentElement()));
157             pout.close();
158         } catch (WebDAVException exc) {
159             m_logger.log(Level.INFO, exc.getMessage() + " - " + request.getQueryString());
160             setStatusCode(exc.getStatusCode());
161         } catch (Exception JavaDoc exc) {
162             m_logger.log(Level.WARNING, exc.getMessage(), exc);
163             setStatusCode(WebDAVStatus.SC_INTERNAL_SERVER_ERROR);
164         }
165
166        
167         return context.getStatusCode();
168     }
169
170     private String JavaDoc getScopeErrorResponse(SearchRequest searchReq) {
171       String JavaDoc response = "";
172       try {
173             Document document = DocumentBuilderFactory.newInstance()
174                                                .newDocumentBuilder()
175                                                .newDocument();
176
177             Element multiEl = document.createElementNS("DAV:","D:multistatus");
178             multiEl.setAttribute("xmlns:D","DAV:");
179
180             Element respEl = document.createElementNS("DAV:","D:response");
181
182             Element hrefEl = document.createElementNS("DAV:","D:href");
183
184             hrefEl.appendChild(document.createTextNode(searchReq.getScopeURI()));
185
186             respEl.appendChild(hrefEl);
187
188             Element statusEl = document.createElementNS("DAV:","D:status");
189
190             Element scopeErrorEl = document.createElementNS("DAV:","D:scopeerror");
191
192             statusEl.appendChild(document.createTextNode("HTTP/1.1 404 Object Not Found"));
193
194             respEl.appendChild(scopeErrorEl);
195
196             respEl.appendChild(statusEl);
197
198             multiEl.appendChild(respEl);
199
200             response = XMLUtility.printNode(multiEl);
201
202
203         } catch (Exception JavaDoc e) {
204             m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
205         }
206
207       return response;
208     }
209 }
Popular Tags