📄 dwservlet.java
字号:
} else { //default is keywords finalQuery.append("&facet.field=keywords"); } String facetQuery = request.getParameter("facet.query"); if (facetQuery != null && facetQuery.equals("") == false) { finalQuery.append("&facet.query=").append(URLEncoder.encode(facetQuery, "UTF-8")); } request.setAttribute("all", all); request.setAttribute("facet.field", facetField); request.setAttribute("facet.query", facetQuery); String getResults = sendGetCommand(finalQuery.toString(), solrLocation + "/solr/select/"); //Build a Dom to manipulate for convenience and put it in the request. Real applications would want to use //something faster, like SAX DocumentBuilder documentBuilder = docFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(new InputSource(new StringReader(getResults))); if (doc != null) { request.setAttribute("resultsDoc", doc); if (doc != null) { List<SearchResult> searchResults = convertDoc(doc); request.setAttribute("searchResults", searchResults); Map<String, Integer> facetCounts = getFacetCounts(doc); request.setAttribute("facetCounts", facetCounts); } } //processQueryCommand(request, response, finalQuery.toString(), FACET_RESULTS_JSP); request.getRequestDispatcher(FACET_RESULTS_JSP).forward(request, response); } else { throw new ServletException("Must specify a query"); } } /** * Extract the Facet counts from the results Document. * @param doc The XML Document * @return */ private Map<String, Integer> getFacetCounts(Document doc) { Map<String, Integer> result = new HashMap<String, Integer>(); NodeList facetList = doc.getElementsByTagName("lst"); if (facetList != null && facetList.getLength() > 0) { for (int i = 0; i < facetList.getLength(); i++) { Element elt = (Element) facetList.item(i); String name = elt.getAttribute("name"); if (name != null && name.equals("facet_fields")) { NodeList counts = elt.getElementsByTagName("int"); for (int j = 0; j < counts.getLength(); j++) { Element count = (Element) counts.item(j); String countName = count.getAttribute("name"); result.put(countName, new Integer(count.getTextContent())); } } } } return result; } /** * Get a list of {@link SearchResult}s from the XML Document. * @param doc * @return */ private List<SearchResult> convertDoc(Document doc) { //Get the results out of the XML NodeList nodes = doc.getElementsByTagName("doc"); List<SearchResult> result = Collections.emptyList(); if (nodes != null) { result = new ArrayList<SearchResult>(nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NodeList children = node.getChildNodes(); SearchResult sr = new SearchResult(); result.add(sr); for (int j = 0; j < children.getLength(); j++) { Element elt = (Element) children.item(j); //The name attribute tells us what property on the Search Result. Again, SAX makes more sense, but this is easier for now String attrib = elt.getAttribute("name"); String text = elt.getTextContent(); if (attrib.equals("content")) { sr.setContent(text); } else if (attrib.equals("creationDate")) { sr.setDate(text); } else if (attrib.equals("score")) { sr.setScore(text); } else if (attrib.equals("keywords")) { sr.setKeywords(text); } else if (attrib.equals("published")) { sr.setPublished(text); } else if (attrib.equals("rating")) { sr.setRating(text); } else if (attrib.equals("title")) { sr.setTitle(text); } else if (attrib.equals("url")) { sr.setUrl(text); } } } } return result; } //Helper methods /** * Either forward the request on to Solr, or send it to be displayed back to the user * @param request * @param response * @param command * @throws ServletException * @throws IOException */ private void processIndexCommand(HttpServletRequest request, HttpServletResponse response, String command) throws ServletException, IOException { System.out.println("Command: " + command); if (isShowCommand(request) == true) { setCommand(request, command); request.getRequestDispatcher(SHOW_INDEX_XML_COMMAND_JSP).forward(request, response); } else { processSubmitCommand(request, response, command); } } /** * Either forward the query on to Solr, or send it to the destination URL * @param request * @param response * @param query * @param destination * @throws ServletException * @throws IOException */ private void processQueryCommand(HttpServletRequest request, HttpServletResponse response, String query, String destination) throws ServletException, IOException { System.out.println("Query: " + query); request.setAttribute("query", query); if (isShowCommand(request) == true) { request.getRequestDispatcher(destination).forward(request, response); } else { processSubmitQuery(request, response); } } /** * Sumbit a Post Command, and then forward to {@link #SHOW_SOLR_RESULTS_JSP} * @param request * @param response * @param command * @throws IOException * @throws ServletException */ private void processSubmitCommand(HttpServletRequest request, HttpServletResponse response, String command) throws IOException, ServletException { String results = sendPostCommand(command, solrLocation + "/solr/update"); //Send the command over HTTP to be handled by Solr request.setAttribute("results", results); request.getRequestDispatcher(SHOW_SOLR_RESULTS_JSP).forward(request, response); } /** * Get the command from the request and send it Solr via {@link #sendPostCommand(String,String)}, then put the results into the request * and forward on to the results page. * * @param request * @param response * @throws IOException * @throws ServletException */ private void processSubmitCommand(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String command = request.getParameter("command"); processSubmitCommand(request, response, command); } /** * Submit a {@link #sendGetCommand(String,String)} and then forward to {@link #SHOW_SOLR_RESULTS_JSP} * @param request * @param response * @throws IOException * @throws ServletException */ private void processSubmitQuery(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String query = request.getParameter("query"); if (query == null || query.equals("") == true) { //We may be getting the query from the request, not the form query = (String) request.getAttribute("query"); } String results = sendGetCommand(query, solrLocation + "/solr/select/"); //Send the command over HTTP to be handled by Solr request.setAttribute("results", results); request.getRequestDispatcher(SHOW_SOLR_RESULTS_JSP).forward(request, response); } /** * Put the XML Command into the request so that it can be displayed * * @param request * @param command */ private void setCommand(HttpServletRequest request, String command) { request.setAttribute("command", command); } /** * Send the command to Solr using a Post * * @param command * @param url * @return * @throws IOException */ private String sendPostCommand(String command, String url) throws IOException { String results = null; HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); RequestEntity re = new StringRequestEntity(command, "text/xml", "UTF-8"); post.setRequestEntity(re); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Read the response body. byte[] responseBody = post.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data results = new String(responseBody); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. post.releaseConnection(); } return results; } /** * Send the command to Solr using a GET * @param queryString * @param url * @return * @throws IOException */ private String sendGetCommand(String queryString, String url) throws IOException { String results = null; HttpClient client = new HttpClient(); GetMethod get = new GetMethod(url); get.setQueryString(queryString.trim()); client.executeMethod(get); try { // Execute the method. int statusCode = client.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + get.getStatusLine()); } // Read the response body. byte[] responseBody = get.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data results = new String(responseBody); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. get.releaseConnection(); } return results; } /** * Only add space to the query if there is already something in the query. * @param query */ private void addSpaceToQuery(StringBuilder query) { if (query.length() > 0) { //Use a + sign for URL Encoding query.append('+'); } } private boolean isShowCommand(HttpServletRequest request) { boolean result = false; String tmp = request.getParameter("showCommand"); result = Boolean.parseBoolean(tmp); return result; } /** * Call {@link #doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)} */ protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { doGet(httpServletRequest, httpServletResponse); } /** * Get the port number from the web.xml. * @param servletConfig * @throws ServletException */ public void init(ServletConfig servletConfig) throws ServletException { String port = servletConfig.getInitParameter("port"); if (port != null && port.equals("") == false) { portNumber = Integer.parseInt(port); } solrLocation = "http://localhost:" + portNumber; solrFormatter.setTimeZone(UTC); System.out.println("Solr must be running at http://localhost:" + portNumber + "/solr for this demo to work"); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -