Java Code Examples for org.apache.solr.response.SolrQueryResponse#getException()

The following examples show how to use org.apache.solr.response.SolrQueryResponse#getException() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpSolrCall.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void handleAdminRequest() throws IOException {
  SolrQueryResponse solrResp = new SolrQueryResponse();
  SolrCore.preDecorateResponse(solrReq, solrResp);
  handleAdmin(solrResp);
  SolrCore.postDecorateResponse(handler, solrReq, solrResp);
  if (solrResp.getToLog().size() > 0) {
    if (log.isInfoEnabled()) { // has to come second and in it's own if to keep ./gradlew check happy.
      log.info(handler != null ? MarkerFactory.getMarker(handler.getClass().getName()) : MarkerFactory.getMarker(HttpSolrCall.class.getName()), solrResp.getToLogAsString("[admin]"));
    }
  }
  QueryResponseWriter respWriter = SolrCore.DEFAULT_RESPONSE_WRITERS.get(solrReq.getParams().get(CommonParams.WT));
  if (respWriter == null) respWriter = getResponseWriter();
  writeResponse(solrResp, respWriter, Method.getMethod(req.getMethod()));
  if (shouldAudit()) {
    EventType eventType = solrResp.getException() == null ? EventType.COMPLETED : EventType.ERROR;
    if (shouldAudit(eventType)) {
      cores.getAuditLoggerPlugin().doAudit(
          new AuditEvent(eventType, req, getAuthCtx(), solrReq.getRequestTimer().getTime(), solrResp.getException()));
    }
  }
}
 
Example 2
Source File: TestCrossCoreJoin.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public String query(SolrCore core, SolrQueryRequest req) throws Exception {
  String handler = "standard";
  if (req.getParams().get("qt") != null) {
    handler = req.getParams().get("qt");
  }
  if (req.getParams().get("wt") == null){
    ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
    params.set("wt", "xml");
    req.setParams(params);
  }
  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);
  req.close();
  SolrRequestInfo.clearRequestInfo();
  return sw.toString();
}
 
Example 3
Source File: IgnoreCommitOptimizeUpdateProcessorFactoryTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testIgnoreCommit() throws Exception {
  // verify that the processor returns an error if it receives a commit
  SolrQueryResponse rsp = processCommit("ignore-commit-from-client-403", false);
  assertNotNull("Sending a commit should have resulted in an exception in the response", rsp.getException());

  rsp = processCommit("ignore-commit-from-client-200", false);
  Exception shouldBeNull = rsp.getException();
  assertNull("Sending a commit should NOT have resulted in an exception in the response: "+shouldBeNull, shouldBeNull);

  rsp = processCommit("ignore-optimize-only-from-client-403", true);
  assertNotNull("Sending an optimize should have resulted in an exception in the response", rsp.getException());
  // commit should happen if DistributedUpdateProcessor.COMMIT_END_POINT == true
  rsp = processCommit("ignore-commit-from-client-403", false, Boolean.TRUE);
  shouldBeNull = rsp.getException();
  assertNull("Sending a commit should NOT have resulted in an exception in the response: "+shouldBeNull, shouldBeNull);
}
 
Example 4
Source File: TestHarness.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a "query" using a user constructed SolrQueryRequest, and closes the request at the end.
 *
 * @param handler the name of the request handler to process the request
 * @param req the Query to process, will be closed.
 * @return The XML response to the query
 * @exception Exception any exception in the response.
 * @exception IOException if there is a problem writing the XML
 * @see LocalSolrQueryRequest
 */
public String query(String handler, SolrQueryRequest req) throws Exception {
  try {
    SolrCore core = req.getCore();
    SolrQueryResponse rsp = new SolrQueryResponse();
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
    core.execute(core.getRequestHandler(handler),req,rsp);
    if (rsp.getException() != null) {
      throw rsp.getException();
    }
    QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
    if (responseWriter instanceof BinaryQueryResponseWriter) {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32000);
      BinaryQueryResponseWriter writer = (BinaryQueryResponseWriter) responseWriter;
      writer.write(byteArrayOutputStream, req, rsp);
      return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    } else {
      StringWriter sw = new StringWriter(32000);
      responseWriter.write(sw,req,rsp);
      return sw.toString();
    }

  } finally {
    req.close();
    SolrRequestInfo.clearRequestInfo();
  }
}
 
Example 5
Source File: TestHarness.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** It is the users responsibility to close the request object when done with it.
 * This method does not set/clear SolrRequestInfo */
public SolrQueryResponse queryAndResponse(String handler, SolrQueryRequest req) throws Exception {
  try (SolrCore core = getCoreInc()) {
    SolrQueryResponse rsp = new SolrQueryResponse();
    core.execute(core.getRequestHandler(handler), req, rsp);
    if (rsp.getException() != null) {
      throw rsp.getException();
    }
    return rsp;
  }
}
 
Example 6
Source File: TestZKPropertiesWriter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Code copied from {@link org.apache.solr.util.TestHarness#query(String, SolrQueryRequest)} because it is not
 * <code>static</code> there (it could have been) and we do not have an instance of {@link org.apache.solr.util.TestHarness}.
 */
private static String localQuery(String handler, SolrQueryRequest req) throws Exception {
  try {
    SolrCore core = req.getCore();
    SolrQueryResponse rsp = new SolrQueryResponse();
    SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
    core.execute(core.getRequestHandler(handler),req,rsp); // TODO the core doesn't have the request handler
    if (rsp.getException() != null) {
      throw rsp.getException();
    }
    QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
    if (responseWriter instanceof BinaryQueryResponseWriter) {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32000);
      BinaryQueryResponseWriter writer = (BinaryQueryResponseWriter) responseWriter;
      writer.write(byteArrayOutputStream, req, rsp);
      return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    } else {
      StringWriter sw = new StringWriter(32000);
      responseWriter.write(sw,req,rsp);
      return sw.toString();
    }

  } finally {
    req.close();
    SolrRequestInfo.clearRequestInfo();
  }
}
 
Example 7
Source File: HttpSolrCall.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void writeResponse(SolrQueryResponse solrRsp, QueryResponseWriter responseWriter, Method reqMethod)
    throws IOException {
  try {
    Object invalidStates = solrReq.getContext().get(CloudSolrClient.STATE_VERSION);
    //This is the last item added to the response 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 response 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) response.setContentType(ct);

    if (solrRsp.getException() != null) {
      @SuppressWarnings({"rawtypes"})
      NamedList info = new SimpleOrderedMap();
      int code = ResponseUtils.getErrorInfo(solrRsp.getException(), info, log);
      solrRsp.add("error", info);
      response.setStatus(code);
    }

    if (Method.HEAD != reqMethod) {
      OutputStream out = response.getOutputStream();
      QueryResponseWriterUtil.writeQueryResponse(out, responseWriter, solrReq, solrRsp, ct);
    }
    //else http HEAD request, nothing to write out, waited this long just to get ContentType
  } catch (EOFException e) {
    log.info("Unable to write response, client closed connection or we are shutting down", e);
  }
}
 
Example 8
Source File: HttpCacheHeaderUtil.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the downstream request handler wants to avoid HTTP caching of
 * the response.
 * 
 * @param solrRsp The Solr response object
 * @param resp The HTTP servlet response object
 * @param reqMethod The HTTP request type
 */
public static void checkHttpCachingVeto(final SolrQueryResponse solrRsp,
    HttpServletResponse resp, final Method reqMethod) {
  // For POST we do nothing. They never get cached
  if (Method.POST == reqMethod || Method.OTHER == reqMethod) {
    return;
  }
  // If the request handler has not vetoed and there is no
  // exception silently return
  if (solrRsp.isHttpCaching() && solrRsp.getException() == null) {
    return;
  }
  
  // Otherwise we tell the caches that we don't want to cache the response
  resp.setHeader("Cache-Control", "no-cache, no-store");

  // For HTTP/1.0 proxy caches
  resp.setHeader("Pragma", "no-cache");

  // This sets the expiry date to a date in the past
  // As long as no time machines get invented this is safe
  resp.setHeader("Expires", "Sat, 01 Jan 2000 01:00:00 GMT");

  long timeNowForHeader = timeNowForHeader();
  // We signal "just modified" just in case some broken
  // proxy cache does not follow the above headers
  resp.setDateHeader("Last-Modified", timeNowForHeader);
  
  // We override the ETag with something different
  resp.setHeader("ETag", '"'+Long.toHexString(timeNowForHeader)+'"');
}
 
Example 9
Source File: CollectionsHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
void invokeAction(SolrQueryRequest req, SolrQueryResponse rsp, CoreContainer cores, CollectionAction action, CollectionOperation operation) throws Exception {
  if (!coreContainer.isZooKeeperAware()) {
    throw new SolrException(BAD_REQUEST,
        "Invalid request. collections can be accessed only in SolrCloud mode");
  }
  Map<String, Object> props = operation.execute(req, rsp, this);
  if (props == null) {
    return;
  }

  String asyncId = req.getParams().get(ASYNC);
  if (asyncId != null) {
    props.put(ASYNC, asyncId);
  }

  props.put(QUEUE_OPERATION, operation.action.toLower());

  if (operation.sendToOCPQueue) {
    ZkNodeProps zkProps = new ZkNodeProps(props);
    SolrResponse overseerResponse = sendToOCPQueue(zkProps, operation.timeOut);
    rsp.getValues().addAll(overseerResponse.getResponse());
    Exception exp = overseerResponse.getException();
    if (exp != null) {
      rsp.setException(exp);
    }

    //TODO yuck; shouldn't create-collection at the overseer do this?  (conditionally perhaps)
    if (action.equals(CollectionAction.CREATE) && asyncId == null) {
      if (rsp.getException() == null) {
        waitForActiveCollection(zkProps.getStr(NAME), cores, overseerResponse);
      }
    }

  } else {
    // submits and doesn't wait for anything (no response)
    coreContainer.getZkController().getOverseer().offerStateUpdate(Utils.toJSON(props));
  }

}
 
Example 10
Source File: EmbeddedSolrServer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static void checkForExceptions(SolrQueryResponse rsp) throws Exception {
  if (rsp.getException() != null) {
    if (rsp.getException() instanceof SolrException) {
      throw rsp.getException();
    }
    throw new SolrServerException(rsp.getException());
  }

}
 
Example 11
Source File: TestWriterPerf.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** make sure to close req after you are done using the response */
public SolrQueryResponse getResponse(SolrQueryRequest req) throws Exception {
  SolrQueryResponse rsp = new SolrQueryResponse();
  h.getCore().execute(h.getCore().getRequestHandler(null),req,rsp);
  if (rsp.getException() != null) {
    throw rsp.getException();
  }
  return rsp;
}
 
Example 12
Source File: KnowledgeGraphResponseWriter.java    From semantic-knowledge-graph with Apache License 2.0 5 votes vote down vote up
public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException
{
    Gson gson = new GsonBuilder().registerTypeAdapter(ResponseValue.class, new ResponseValueSerializer()).create();
    Exception e = response.getException();
    int status = (int)response.getResponseHeader().get("status");
    KnowledgeGraphResponse model = (KnowledgeGraphResponse)response.getValues().get("relatednessResponse");
    if(e != null) {
        if(model == null) {
            model = new KnowledgeGraphResponse();
        }
        model.error = new Error(e.getMessage(), status);
    }
    writer.write(gson.toJson(model, KnowledgeGraphResponse.class));
}
 
Example 13
Source File: SolrCore.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Put status, QTime, and possibly request handler and params, in the response header
 */
public static void postDecorateResponse
(SolrRequestHandler handler, SolrQueryRequest req, SolrQueryResponse rsp) {
  // TODO should check that responseHeader has not been replaced by handler
  NamedList<Object> responseHeader = rsp.getResponseHeader();
  final int qtime = (int) (req.getRequestTimer().getTime());
  int status = 0;
  Exception exception = rsp.getException();
  if (exception != null) {
    if (exception instanceof SolrException)
      status = ((SolrException) exception).code();
    else
      status = 500;
  }
  responseHeader.add("status", status);
  responseHeader.add("QTime", qtime);

  if (rsp.getToLog().size() > 0) {
    rsp.getToLog().add("status", status);
    rsp.getToLog().add("QTime", qtime);
  }

  SolrParams params = req.getParams();
  if (null != handler && params.getBool(CommonParams.HEADER_ECHO_HANDLER, false)) {
    responseHeader.add("handler", handler.getName());
  }

  // Values for echoParams... false/true/all or false/explicit/all ???
  String ep = params.get(CommonParams.HEADER_ECHO_PARAMS, null);
  if (ep != null) {
    EchoParamStyle echoParams = EchoParamStyle.get(ep);
    if (echoParams == null) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid value '" + ep + "' for " + CommonParams.HEADER_ECHO_PARAMS
          + " parameter, use '" + EchoParamStyle.EXPLICIT + "' or '" + EchoParamStyle.ALL + "'");
    }
    if (echoParams == EchoParamStyle.EXPLICIT) {
      responseHeader.add("params", req.getOriginalParams().toNamedList());
    } else if (echoParams == EchoParamStyle.ALL) {
      responseHeader.add("params", req.getParams().toNamedList());
    }
  }
}
 
Example 14
Source File: BaseTestCase.java    From BioSolr with Apache License 2.0 4 votes vote down vote up
public static void queryThrow(SolrCore core, String handlerName, SolrParams params) throws Exception {
  SolrQueryResponse rsp = query(core, handlerName, params);
  if (rsp.getException() != null) {
    throw rsp.getException();
  }
}
 
Example 15
Source File: PingRequestHandlerTest.java    From lucene-solr with Apache License 2.0 3 votes vote down vote up
public void testEnablingServer() throws Exception {

    assertTrue(!healthcheckFile.exists());

    // first make sure that ping responds back that the service is disabled
    SolrQueryResponse sqr = makeRequest(handler, req());
    SolrException se = (SolrException) sqr.getException();
    assertEquals(
      "Response should have been replaced with a 503 SolrException.",
      se.code(), SolrException.ErrorCode.SERVICE_UNAVAILABLE.code);

    // now enable

    makeRequest(handler, req("action", "enable"));

    assertTrue(healthcheckFile.exists());
    assertNotNull(FileUtils.readFileToString(healthcheckFile, "UTF-8"));

    // now verify that the handler response with success

    SolrQueryResponse rsp = makeRequest(handler, req());
    assertEquals("OK", rsp.getValues().get("status"));

    // enable when already enabled shouldn't cause any problems
    makeRequest(handler, req("action", "enable"));
    assertTrue(healthcheckFile.exists());

  }
 
Example 16
Source File: PingRequestHandlerTest.java    From lucene-solr with Apache License 2.0 3 votes vote down vote up
public void testDisablingServer() throws Exception {

    assertTrue(! healthcheckFile.exists());
        
    healthcheckFile.createNewFile();

    // first make sure that ping responds back that the service is enabled

    SolrQueryResponse rsp = makeRequest(handler, req());
    assertEquals("OK", rsp.getValues().get("status"));

    // now disable
    
    makeRequest(handler, req("action", "disable"));
    
    assertFalse(healthcheckFile.exists());

    // now make sure that ping responds back that the service is disabled    
    SolrQueryResponse sqr = makeRequest(handler, req());
    SolrException se = (SolrException) sqr.getException();
    assertEquals(
      "Response should have been replaced with a 503 SolrException.",
      se.code(), SolrException.ErrorCode.SERVICE_UNAVAILABLE.code);
    
    // disable when already disabled shouldn't cause any problems
    makeRequest(handler, req("action", "disable"));
    assertFalse(healthcheckFile.exists());
    
  }