List of usage examples for org.apache.solr.response SolrQueryResponse getException
public Exception getException()
From source file:lux.solr.LuxResponseWriter.java
License:Mozilla Public License
@Override public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException { String xsl = request.getParams().get("lux.xml-xsl-stylesheet"); @SuppressWarnings("unchecked") List<String> errors = response.getValues().getAll("xpath-error"); String contentType = getContentType(request, response); NamedList<?> values = (NamedList<?>) response.getValues().get("xpath-results"); if (values == null && !errors.isEmpty()) { StringBuilder buf = new StringBuilder(); for (String e : errors) { buf.append(e).append("\n"); }//from w ww . jav a2 s . c om throw new SolrException(ErrorCode.BAD_REQUEST, buf.toString()); // writeError(writer, error); } else if (response.getException() != null) { String error = (String) ((NamedList<?>) response.getValues().get("error")).get("msg"); if (error == null) { error = response.getException().toString(); } writeError(writer, error); } else { if (values != null) { if (xsl != null) { writer.write("<?xml-stylesheet type='text/xsl' href='" + xsl + "' ?>\n"); // css? } boolean wrapResults = isXML(contentType) && (values.size() == 0 || values.size() > 1 || !errors.isEmpty() || (!(values.getName(0).equals("document") || values.getName(0).equals("element")))); if (wrapResults) { writer.write("<results>"); } for (int i = 0; i < values.size(); i++) { Object val = values.getVal(i); writer.write(val.toString()); } if (!errors.isEmpty()) { writer.write("<errors>"); for (String error : errors) { writer.write("<error>"); writer.write(error.replace("&", "&").replace("<", "<")); writer.write("</error>"); } writer.write("</errors>"); } if (wrapResults) { writer.write("</results>"); } } } }
From source file:net.yacy.cora.federate.solr.connector.EmbeddedSolrConnector.java
License:Open Source License
public SolrQueryResponse query(SolrQueryRequest req) throws SolrException { final long startTime = System.currentTimeMillis(); // during the solr query we set the thread name to the query string to get more debugging info in thread dumps String q = req.getParams().get(CommonParams.Q); String fq = req.getParams().get(CommonParams.FQ); String sort = req.getParams().get(CommonParams.SORT); String threadname = Thread.currentThread().getName(); if (q != null) Thread.currentThread().setName("solr query: q = " + q + (fq == null ? "" : ", fq = " + fq) + (sort == null ? "" : ", sort = " + sort)); // for debugging in Threaddump SolrQueryResponse rsp = new SolrQueryResponse(); NamedList<Object> responseHeader = new SimpleOrderedMap<Object>(); responseHeader.add("params", req.getOriginalParams().toNamedList()); rsp.add("responseHeader", responseHeader); //SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp)); // send request to solr and create a result this.requestHandler.handleRequest(req, rsp); // get statistics and add a header with that Exception exception = rsp.getException(); int status = exception == null ? 0 : exception instanceof SolrException ? ((SolrException) exception).code() : 500; responseHeader.add("status", status); responseHeader.add("QTime", (int) (System.currentTimeMillis() - startTime)); if (q != null) Thread.currentThread().setName(threadname); // return result return rsp;/* w w w. j av a 2s . com*/ }
From source file:net.yacy.http.servlets.GSAsearchServlet.java
License:Open Source License
/** * from here copy of htroot/gsa/gsasearchresult.java * with modification to use HttpServletRequest instead of (yacy) RequestHeader *///w w w. ja v a 2 s . c o m public static void respond(final HttpServletRequest header, final Switchboard sb, final OutputStream out) { // remember the peer contact for peer statistics String clientip = header.getHeader(HeaderFramework.CONNECTION_PROP_CLIENTIP); if (clientip == null) clientip = "<unknown>"; // read an artificial header addendum String userAgent = header.getHeader(HeaderFramework.USER_AGENT); if (userAgent == null) userAgent = "<unknown>"; sb.peers.peerActions.setUserAgent(clientip, userAgent); // --- handled by Servlet securityHandler // check if user is allowed to search (can be switched in /ConfigPortal.html) boolean authenticated = header.isUserInRole(UserDB.AccessRight.ADMIN_RIGHT.toString()); //sb.adminAuthenticated(header) >= 2; // final boolean searchAllowed = authenticated || sb.getConfigBool(SwitchboardConstants.PUBLIC_SEARCHPAGE, true); // if (!searchAllowed) return null; // create post serverObjects post = new serverObjects(); post.put(CommonParams.Q, ""); post.put("num", "0"); // convert servletrequest parameter to old style serverObjects map Map<String, String[]> map = header.getParameterMap(); Iterator<Map.Entry<String, String[]>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String[]> param = it.next(); post.put(param.getKey(), param.getValue()); // hint: post.put uses String[] for String value anyways } ConcurrentLog.info("GSA Query", post.toString()); sb.intermissionAllThreads(3000); // tell all threads to do nothing for a specific time // rename post fields according to result style //post.put(CommonParams.Q, post.remove("q")); // same as solr //post.put(CommonParams.START, post.remove("start")); // same as solr //post.put(, post.remove("client"));//required, example: myfrontend //post.put(, post.remove("output"));//required, example: xml,xml_no_dtd String originalQuery = post.get(CommonParams.Q, ""); post.put("originalQuery", originalQuery); // get a solr query string QueryGoal qg = new QueryGoal(originalQuery); List<String> solrFQ = qg.collectionTextFilterQuery(false); StringBuilder solrQ = qg.collectionTextQuery(); post.put("defType", "edismax"); for (String fq : solrFQ) post.add(CommonParams.FQ, fq); post.put(CommonParams.Q, solrQ.toString()); post.put(CommonParams.ROWS, post.remove("num")); post.put(CommonParams.ROWS, Math.min(post.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100)); // set ranking final Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(0); final String qf = ranking.getQueryFields(); if (!qf.isEmpty()) post.put(DisMaxParams.QF, qf); if (post.containsKey(CommonParams.SORT)) { // if a gsa-style sort attribute is given, use this to set the solr sort attribute GSAResponseWriter.Sort sort = new GSAResponseWriter.Sort(post.get(CommonParams.SORT, "")); String sorts = sort.toSolr(); if (sorts == null) { post.remove(CommonParams.SORT); } else { post.put(CommonParams.SORT, sorts); } } else { // if no such sort attribute is given, use the ranking as configured for YaCy String fq = ranking.getFilterQuery(); String bq = ranking.getBoostQuery(); String bf = ranking.getBoostFunction(); if (fq.length() > 0) post.put(CommonParams.FQ, fq); if (bq.length() > 0) post.put(DisMaxParams.BQ, bq); if (bf.length() > 0) post.put("boost", bf); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29 } String daterange[] = post.remove("daterange"); if (daterange != null) { String origfq = post.get(CommonParams.FQ); String datefq = ""; for (String dr : daterange) { String from_to[] = dr.endsWith("..") ? new String[] { dr.substring(0, dr.length() - 2), "" } : dr.startsWith("..") ? new String[] { "", dr.substring(2) } : dr.split("\\.\\."); if (from_to.length != 2) continue; Date from = HeaderFramework.parseGSAFS(from_to[0]); if (from == null) from = new Date(0); Date to = HeaderFramework.parseGSAFS(from_to[1]); if (to == null) to = new Date(); to.setTime(to.getTime() + 24L * 60L * 60L * 1000L); // we add a day because the day is inclusive String z = CollectionSchema.last_modified.getSolrFieldName() + ":[" + ISO8601Formatter.FORMATTER.format(from) + " TO " + ISO8601Formatter.FORMATTER.format(to) + "]"; datefq = datefq.length() == 0 ? z : " OR " + z; } if (datefq.length() > 0) post.put(CommonParams.FQ, origfq == null || origfq.length() == 0 ? datefq : "(" + origfq + ") AND (" + datefq + ")"); } post.put(CommonParams.FL, CollectionSchema.content_type.getSolrFieldName() + ',' + CollectionSchema.id.getSolrFieldName() + ',' + CollectionSchema.sku.getSolrFieldName() + ',' + CollectionSchema.title.getSolrFieldName() + ',' + CollectionSchema.description_txt.getSolrFieldName() + ',' + CollectionSchema.load_date_dt.getSolrFieldName() + ',' + CollectionSchema.last_modified.getSolrFieldName() + ',' + CollectionSchema.size_i.getSolrFieldName()); post.put("hl", "true"); post.put("hl.q", originalQuery); post.put("hl.fl", CollectionSchema.description_txt + "," + CollectionSchema.h4_txt.getSolrFieldName() + "," + CollectionSchema.h3_txt.getSolrFieldName() + "," + CollectionSchema.h2_txt.getSolrFieldName() + "," + CollectionSchema.h1_txt.getSolrFieldName() + "," + CollectionSchema.text_t.getSolrFieldName()); post.put("hl.alternateField", CollectionSchema.description_txt.getSolrFieldName()); post.put("hl.simple.pre", "<b>"); post.put("hl.simple.post", "</b>"); post.put("hl.fragsize", Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH)); //String[] access = post.remove("access"); //String[] entqr = post.remove("entqr"); // add sites operator String[] site = post.remove("site"); // example: col1|col2 if (site != null && site[0].length() > 0) { String origfq = post.get(CommonParams.FQ); String sitefq = QueryModifier.parseCollectionExpression(site[0]); post.put(CommonParams.FQ, origfq == null || origfq.length() == 0 ? sitefq : "(" + origfq + ") AND (" + sitefq + ")"); } // get the embedded connector EmbeddedSolrConnector connector = sb.index.fulltext().getDefaultEmbeddedConnector(); if (connector == null) return; // do the solr request SolrQueryRequest req = connector.request(post.toSolrParams(null)); SolrQueryResponse response = null; Exception e = null; try { response = connector.query(req); } catch (final SolrException ee) { e = ee; } if (response != null) e = response.getException(); if (e != null) { ConcurrentLog.logException(e); if (req != null) req.close(); SolrRequestInfo.clearRequestInfo(); return; } // set some context for the writer /* Map<Object,Object> context = req.getContext(); context.put("ip", header.get("CLIENTIP", "")); context.put("client", "vsm_frontent"); context.put("sort", sort.sort); context.put("site", site == null ? "" : site); context.put("access", access == null ? "p" : access[0]); context.put("entqr", entqr == null ? "3" : entqr[0]); */ // write the result directly to the output stream Writer ow = new FastWriter(new OutputStreamWriter(out, UTF8.charset)); try { responseWriter.write(ow, req, response); ow.flush(); } catch (final IOException e1) { } finally { req.close(); SolrRequestInfo.clearRequestInfo(); try { ow.close(); } catch (final IOException e1) { } } // log result Object rv = response.getValues().get("response"); int matches = 0; if (rv != null && rv instanceof ResultContext) { matches = ((ResultContext) rv).docs.matches(); } else if (rv != null && rv instanceof SolrDocumentList) { matches = (int) ((SolrDocumentList) rv).getNumFound(); } AccessTracker.addToDump(originalQuery, Integer.toString(matches)); ConcurrentLog.info("GSA Query", "results: " + matches + ", for query:" + post.toString()); }
From source file:net.yacy.http.servlets.SolrSelectServlet.java
License:Open Source License
@Override public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { HttpServletRequest hrequest = (HttpServletRequest) request; HttpServletResponse hresponse = (HttpServletResponse) response; SolrQueryRequest req = null;//from w w w. j a v a 2 s . c o m final Method reqMethod = Method.getMethod(hrequest.getMethod()); Writer out = null; try { // prepare request to solr MultiMapSolrParams mmsp = SolrRequestParsers.parseQueryString(hrequest.getQueryString()); Switchboard sb = Switchboard.getSwitchboard(); boolean authenticated = true; // count remote searches if this was part of a p2p search if (mmsp.getMap().containsKey("partitions")) { final int partitions = mmsp.getInt("partitions", 30); sb.searchQueriesGlobal += 1.0f / partitions; // increase query counter } // get the ranking profile id int profileNr = mmsp.getInt("profileNr", 0); // rename post fields according to result style String querystring = ""; if (!mmsp.getMap().containsKey(CommonParams.Q) && mmsp.getMap().containsKey(CommonParams.QUERY)) { querystring = mmsp.get(CommonParams.QUERY, ""); mmsp.getMap().remove(CommonParams.QUERY); QueryModifier modifier = new QueryModifier(0); querystring = modifier.parse(querystring); modifier.apply(mmsp); QueryGoal qg = new QueryGoal(querystring); StringBuilder solrQ = qg.collectionTextQuery(); mmsp.getMap().put(CommonParams.Q, new String[] { solrQ.toString() }); // sru patch } String q = mmsp.get(CommonParams.Q, ""); if (querystring.length() == 0) querystring = q; if (!mmsp.getMap().containsKey(CommonParams.START)) { int startRecord = mmsp.getFieldInt("startRecord", null, 0); mmsp.getMap().remove("startRecord"); mmsp.getMap().put(CommonParams.START, new String[] { Integer.toString(startRecord) }); // sru patch } if (!mmsp.getMap().containsKey(CommonParams.ROWS)) { int maximumRecords = mmsp.getFieldInt("maximumRecords", null, 10); mmsp.getMap().remove("maximumRecords"); mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer.toString(maximumRecords) }); // sru patch } mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer .toString(Math.min(mmsp.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100)) }); // set ranking according to profile number if ranking attributes are not given in the request Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr); if (!mmsp.getMap().containsKey(CommonParams.SORT) && !mmsp.getMap().containsKey(DisMaxParams.BQ) && !mmsp.getMap().containsKey(DisMaxParams.BF) && !mmsp.getMap().containsKey("boost")) { if (!mmsp.getMap().containsKey("defType")) mmsp.getMap().put("defType", new String[] { "edismax" }); String fq = ranking.getFilterQuery(); String bq = ranking.getBoostQuery(); String bf = ranking.getBoostFunction(); if (fq.length() > 0) mmsp.getMap().put(CommonParams.FQ, new String[] { fq }); if (bq.length() > 0) mmsp.getMap().put(DisMaxParams.BQ, new String[] { bq }); if (bf.length() > 0) mmsp.getMap().put("boost", new String[] { bf }); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29 } // get a response writer for the result String wt = mmsp.get(CommonParams.WT, "xml"); // maybe use /solr/select?q=*:*&start=0&rows=10&wt=exml QueryResponseWriter responseWriter = RESPONSE_WRITER.get(wt); if (responseWriter == null) throw new ServletException("no response writer"); if (responseWriter instanceof OpensearchResponseWriter) { // set the title every time, it is possible that it has changed final String promoteSearchPageGreeting = (sb .getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false)) ? sb.getConfig("network.unit.description", "") : sb.getConfig(SwitchboardConstants.GREETING, ""); ((OpensearchResponseWriter) responseWriter).setTitle(promoteSearchPageGreeting); } // if this is a call to YaCys special search formats, enhance the query with field assignments if ((responseWriter instanceof YJsonResponseWriter || responseWriter instanceof OpensearchResponseWriter) && "true".equals(mmsp.get("hl", "true"))) { // add options for snippet generation if (!mmsp.getMap().containsKey("hl.q")) mmsp.getMap().put("hl.q", new String[] { q }); if (!mmsp.getMap().containsKey("hl.fl")) mmsp.getMap().put("hl.fl", new String[] { CollectionSchema.description_txt + "," + CollectionSchema.h4_txt.getSolrFieldName() + "," + CollectionSchema.h3_txt.getSolrFieldName() + "," + CollectionSchema.h2_txt.getSolrFieldName() + "," + CollectionSchema.h1_txt.getSolrFieldName() + "," + CollectionSchema.text_t.getSolrFieldName() }); if (!mmsp.getMap().containsKey("hl.alternateField")) mmsp.getMap().put("hl.alternateField", new String[] { CollectionSchema.description_txt.getSolrFieldName() }); if (!mmsp.getMap().containsKey("hl.simple.pre")) mmsp.getMap().put("hl.simple.pre", new String[] { "<b>" }); if (!mmsp.getMap().containsKey("hl.simple.post")) mmsp.getMap().put("hl.simple.post", new String[] { "</b>" }); if (!mmsp.getMap().containsKey("hl.fragsize")) mmsp.getMap().put("hl.fragsize", new String[] { Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH) }); } // get the embedded connector String requestURI = hrequest.getRequestURI(); boolean defaultConnector = (requestURI.startsWith("/solr/" + WebgraphSchema.CORE_NAME)) ? false : requestURI.startsWith("/solr/" + CollectionSchema.CORE_NAME) || mmsp.get("core", CollectionSchema.CORE_NAME).equals(CollectionSchema.CORE_NAME); mmsp.getMap().remove("core"); SolrConnector connector = defaultConnector ? sb.index.fulltext().getDefaultEmbeddedConnector() : sb.index.fulltext().getEmbeddedConnector(WebgraphSchema.CORE_NAME); if (connector == null) { connector = defaultConnector ? sb.index.fulltext().getDefaultConnector() : sb.index.fulltext().getConnectorForRead(WebgraphSchema.CORE_NAME); } if (connector == null) throw new ServletException("no core"); // add default queryfield parameter according to local ranking config (or defaultfield) if (ranking != null) { // ranking normally never null final String qf = ranking.getQueryFields(); if (qf.length() > 4) { // make sure qf has content (else use df) addParam(DisMaxParams.QF, qf, mmsp.getMap()); // add QF that we set to be best suited for our index // TODO: if every peer applies a decent QF itself, this can be reverted to getMap().put() } else { mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() }); } } else { mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() }); } // do the solr request, generate facets if we use a special YaCy format final SolrQueryResponse rsp; if (connector instanceof EmbeddedSolrConnector) { req = ((EmbeddedSolrConnector) connector).request(mmsp); rsp = ((EmbeddedSolrConnector) connector).query(req); // prepare response hresponse.setHeader("Cache-Control", "no-cache, no-store"); HttpCacheHeaderUtil.checkHttpCachingVeto(rsp, hresponse, reqMethod); // check error if (rsp.getException() != null) { AccessTracker.addToDump(querystring, "0", new Date()); sendError(hresponse, rsp.getException()); return; } NamedList<?> values = rsp.getValues(); DocList r = ((ResultContext) values.get("response")).docs; int numFound = r.matches(); AccessTracker.addToDump(querystring, Integer.toString(numFound), new Date()); // write response header final String contentType = responseWriter.getContentType(req, rsp); if (null != contentType) response.setContentType(contentType); if (Method.HEAD == reqMethod) { return; } // write response body if (responseWriter instanceof BinaryResponseWriter) { ((BinaryResponseWriter) responseWriter).write(response.getOutputStream(), req, rsp); } else { out = new FastWriter(new OutputStreamWriter(response.getOutputStream(), UTF8.charset)); responseWriter.write(out, req, rsp); out.flush(); } } else { // write a 'faked' response using a call to the backend SolrDocumentList sdl = connector.getDocumentListByQuery(mmsp.getMap().get(CommonParams.Q)[0], mmsp.getMap().get(CommonParams.SORT) == null ? null : mmsp.getMap().get(CommonParams.SORT)[0], Integer.parseInt(mmsp.getMap().get(CommonParams.START)[0]), Integer.parseInt(mmsp.getMap().get(CommonParams.ROWS)[0]), mmsp.getMap().get(CommonParams.FL)); OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream()); EnhancedXMLResponseWriter.write(osw, req, sdl); osw.close(); } } catch (final Throwable ex) { sendError(hresponse, ex); } finally { if (req != null) { req.close(); } SolrRequestInfo.clearRequestInfo(); if (out != null) try { out.close(); } catch (final IOException e1) { } } }
From source file:org.codeexample.jeffery.solr.ThreadedUpdateRequestHandler.java
License:Apache License
private void submitTask(final SolrQueryRequest req, final SolrQueryResponse rsp, final UpdateRequestProcessorChain processorChain, ExecutorService executor, final ContentStream stream, final List<Map<String, Object>> rspResult) { Thread thread = new Thread() { public void run() { Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("start_time", new Date().toString()); if (stream instanceof ContentStreamBase.FileStream) { map.put("Import File: ", ((ContentStreamBase.FileStream) stream).getName()); }/*from w w w . j a va 2s . c o m*/ try { UpdateRequestProcessor processor = null; try { processor = processorChain.createProcessor(req, rsp); ContentStreamLoader documentLoader = newLoader(req, processor); documentLoader.load(req, rsp, stream, processor); System.err.println(rsp); } finally { if (processor != null) { // finish the request processor.finish(); } } } catch (Exception e) { rsp.setException(e); } finally { map.put("end_time", new Date().toString()); if (rsp.getException() != null) { map.put("exception", rsp.getException()); } rspResult.add(map); } }; }; executor.execute(thread); }
From source file:org.restlet.ext.lucene.SolrClientHelper.java
License:Open Source License
@Override public void handle(Request request, Response response) { super.handle(request, response); Reference resRef = request.getResourceRef(); String path = resRef.getPath(); if (path != null) { path = resRef.getPath(true);// w w w . ja v a 2 s .co m } String coreName = request.getResourceRef().getHostDomain(); if (coreName == null || "".equals(coreName)) { coreName = getContext().getParameters().getFirstValue("DefaultCore"); } SolrCore core = coreContainer.getCore(coreName); if (core == null) { response.setStatus(Status.SERVER_ERROR_INTERNAL, "No such core: " + coreName); return; } // Extract the handler from the path or params SolrRequestHandler handler = core.getRequestHandler(path); if (handler == null) { if ("/select".equals(path) || "/select/".equalsIgnoreCase(path)) { String qt = request.getResourceRef().getQueryAsForm().getFirstValue(CommonParams.QT); handler = core.getRequestHandler(qt); if (handler == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "unknown handler: " + qt); return; } } // Perhaps the path is to manage the cores if (handler == null && coreContainer != null && path.equals(coreContainer.getAdminPath())) { handler = coreContainer.getMultiCoreHandler(); } } if (handler == null) { core.close(); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "unknown handler: " + path); return; } try { SolrQueryRequest solrReq = new SolrRestletQueryRequest(request, core); SolrQueryResponse solrResp = new SolrQueryResponse(); core.execute(handler, solrReq, solrResp); if (solrResp.getException() != null) { response.setStatus(Status.SERVER_ERROR_INTERNAL, solrResp.getException()); } else { response.setEntity(new SolrRepresentation(MediaType.APPLICATION_XML, solrReq, solrResp)); response.setStatus(Status.SUCCESS_OK); } } catch (Exception e) { getLogger().log(Level.WARNING, "Unable to evaluate " + resRef.toString(), e); response.setStatus(Status.SERVER_ERROR_INTERNAL, e); } finally { core.close(); } }
From source file:org.restlet.ext.solr.SolrClientHelper.java
License:LGPL
@Override public void handle(Request request, Response response) { super.handle(request, response); Reference resRef = request.getResourceRef(); String path = resRef.getPath(); if (path != null) { path = resRef.getPath(true);//from w ww . jav a 2 s.com } String coreName = request.getResourceRef().getHostDomain(); if (coreName == null || "".equals(coreName)) { coreName = getContext().getParameters().getFirstValue("DefaultCore"); } SolrCore core = coreContainer.getCore(coreName); if (core == null) { response.setStatus(Status.SERVER_ERROR_INTERNAL, "No such core: " + coreName); return; } // Extract the handler from the path or params SolrRequestHandler handler = core.getRequestHandler(path); if (handler == null) { if ("/select".equals(path) || "/select/".equalsIgnoreCase(path)) { String qt = request.getResourceRef().getQueryAsForm().getFirstValue(CommonParams.QT); handler = core.getRequestHandler(qt); if (handler == null) { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "unknown handler: " + qt); return; } } // Perhaps the path is to manage the cores if (handler == null && coreContainer != null && path.equals(coreContainer.getAdminPath())) { handler = coreContainer.getMultiCoreHandler(); } } if (handler == null) { core.close(); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "unknown handler: " + path); return; } try { SolrQueryRequest solrReq = new SolrRestletQueryRequest(request, core); SolrQueryResponse solrResp = new SolrQueryResponse(); core.execute(handler, solrReq, solrResp); if (solrResp.getException() != null) { response.setStatus(Status.SERVER_ERROR_INTERNAL, solrResp.getException()); } else { response.setEntity(new SolrRepresentation(solrReq, solrResp, core)); response.setStatus(Status.SUCCESS_OK); } } catch (Exception e) { getLogger().log(Level.WARNING, "Unable to evaluate " + resRef.toString(), e); response.setStatus(Status.SERVER_ERROR_INTERNAL, e); } finally { core.close(); } }
From source file:org.vootoo.schema.CrossCoreFieldTest.java
License:Apache License
public String query(String coreName, String... query) throws Exception { String handler = "/select"; SolrQueryRequest req = null;// ww w .j a va2 s. c o m try (SolrCore core = coreContainer.getCore(coreName)) { req = makeRequest(handler, core, 0, 10, query); SolrQueryResponse rsp = new SolrQueryResponse(); SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp)); core.execute(core.getRequestHandler(handler), req, rsp); if (rsp.getException() != null) { throw rsp.getException(); } StringWriter sw = new StringWriter(32000); QueryResponseWriter responseWriter = core.getQueryResponseWriter(req); responseWriter.write(sw, req, rsp); return sw.toString(); } finally { if (req != null) { req.close(); } SolrRequestInfo.clearRequestInfo(); } }
From source file:org.vootoo.server.RequestProcesser.java
License:Apache License
protected void writeResponse(SolrQueryResponse solrRsp, QueryResponseWriter responseWriter, SolrQueryRequest solrReq) throws IOException { Object invalidStates = solrReq.getContext().get(CloudSolrClient.STATE_VERSION); //This is the last item added to the applyResult and the client would expect it that way. //If that assumption is changed , it would fail. This is done to avoid an O(n) scan on // the applyResult for each request if (invalidStates != null) solrRsp.add(CloudSolrClient.STATE_VERSION, invalidStates); // Now write it out final String ct = responseWriter.getContentType(solrReq, solrRsp); // don't call setContentType on null if (null != ct) { responseSetter.setContentType(ct); }/*from ww w. j ava 2 s. c om*/ if (solrRsp.getException() != null) { NamedList info = new SimpleOrderedMap(); int code = ResponseUtils.getErrorInfo(solrRsp.getException(), info, logger); //solrRsp.add("error", info); // use protocol response exception instead of set 'error' response return to client, responseSetter.setSolrResponseException(code, info); } QueryResponseWriterUtil.writeQueryResponse(responseSetter.getResponseOutputStream(), responseWriter, solrReq, solrRsp, ct); //fire QueryResponse write Complete responseSetter.writeQueryResponseComplete(solrRsp); }