Java Code Examples for org.apache.solr.response.SolrQueryResponse

The following examples show how to use org.apache.solr.response.SolrQueryResponse. These examples are extracted from open source projects. 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 Project: lucene-solr   Source File: JsonLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDecimalValuesInAdd() throws Exception {
  String str = "{'add':[{'id':'1','d1':256.78,'d2':-5123456789.0,'d3':0.0,'d3':1.0,'d4':1.7E-10}]}".replace('\'', '"');
  SolrQueryRequest req = req();
  SolrQueryResponse rsp = new SolrQueryResponse();
  BufferingRequestProcessor p = new BufferingRequestProcessor(null);
  JsonLoader loader = new JsonLoader();
  loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);

  assertEquals(1, p.addCommands.size());

  AddUpdateCommand add = p.addCommands.get(0);
  SolrInputDocument d = add.solrDoc;
  SolrInputField f = d.getField("d1");
  assertEquals(256.78, f.getValue());
  f = d.getField("d2");
  assertEquals(-5123456789.0, f.getValue());
  f = d.getField("d3");
  assertEquals(2, ((List)f.getValue()).size());
  assertTrue(((List)f.getValue()).contains(0.0));
  assertTrue(((List) f.getValue()).contains(1.0));
  f = d.getField("d4");
  assertEquals(1.7E-10, f.getValue());

  req.close();
}
 
Example 2
Source Project: lucene-solr   Source File: XmlInterpolationTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void assertXmlTag(String docText, boolean expected) throws Exception {
  final SolrQueryRequest req = reqDoc(docText);
  try { // 5.4 and beyond we can use try-with-resources
    final SolrQueryResponse rsp = h.queryAndResponse(req.getParams().get("qt"), req);
    final TestTag[] testTags = pullTagsFromResponse(req, rsp);
    if (!expected) {
      assertEquals(0, testTags.length);
    } else {
      assertEquals(1, testTags.length);
      final TestTag tag = testTags[0];
      validateXml(insertAnchorAtOffsets(docText, tag.startOffset, tag.endOffset, tag.docName));
    }
  } finally {
    req.close();
  }
}
 
Example 3
Source Project: vind   Source File: SuggestionService.java    License: Apache License 2.0 6 votes vote down vote up
protected SuggestionResult[] createResults(SolrQueryResponse rsp, String[] singleValueFields, String[] multiValueFields, String query, String op, String df, SuggestionRequestHandler.Type type, int termLimit, int limit, SuggestionRequestHandler.LimitType limitType, SuggestionRequestHandler.Strategy strategy, String sugestionField, Map<String, Map<String,Object>> intervals) {
    SuggestionResult[] result = new SuggestionResult[2];
    switch (type) {
        case single:
            result[0] = SuggestionResultFactory.createSingleValueResult(solrCore, rsp, singleValueFields, query, op, df, termLimit, limit, limitType, strategy,sugestionField,intervals);
            break;
        case multi:
            result[1] = SuggestionResultFactory.createMultiValueResult(solrCore, rsp, multiValueFields, query, df,termLimit, limit, limitType); //TODO consider strategy
            break;
        case mixed:
            result[0] = SuggestionResultFactory.createSingleValueResult(solrCore, rsp, singleValueFields, query, op, df,termLimit, limit, limitType, strategy,sugestionField,intervals);
            result[1] = SuggestionResultFactory.createMultiValueResult(solrCore, rsp, multiValueFields, query, df, termLimit, limit, limitType);
    }

    if ((result[0] == null || result[0].getCount() ==0) && (result[1] == null || ((SuggestionResultMulti) result[1]).getCount() == 0)) {
        result = null;
    }
    return result;
}
 
Example 4
@SuppressWarnings({ "unchecked", "rawtypes" })
private NamedList<Integer> getFacets(SolrQueryRequest request, String query, String field, int minCount)
{
    ModifiableSolrParams params =
            new ModifiableSolrParams(request.getParams())
                    .set(CommonParams.Q, query)
                    .set(CommonParams.ROWS, 0)
                    .set(FacetParams.FACET, true)
                    .set(FacetParams.FACET_FIELD, field)
                    .set(FacetParams.FACET_MINCOUNT, minCount);

    SolrQueryResponse response = cloud.getResponse(nativeRequestHandler, request, params);
    NamedList facetCounts = (NamedList) response.getValues().get("facet_counts");
    NamedList facetFields = (NamedList) facetCounts.get("facet_fields");
    return (NamedList) facetFields.get(field);
}
 
Example 5
Source Project: lucene-solr   Source File: DebugComponentTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void ensureRidPresent(ResponseBuilder rb, String expectedRid) {
  SolrQueryRequest req = rb.req;
  SolrQueryResponse resp = rb.rsp;
  //a generated request ID should be added to the request
  String rid = req.getParams().get(CommonParams.REQUEST_ID);
  if(expectedRid == null) {
    assertTrue(rid + " Doesn't match expected pattern.", Pattern.matches(".*-collection1-[0-9]*-[0-9]+", rid));
  } else {
    assertEquals("Expecting " + expectedRid + " but found " + rid, expectedRid, rid);
  }
  //The request ID is added to the debug/track section
  assertEquals(rid, ((NamedList<Object>) rb.getDebugInfo().get("track")).get(CommonParams.REQUEST_ID));
  //RID must be added to the toLog, so that it's included in the main request log
  assertEquals(rid, resp.getToLog().get(CommonParams.REQUEST_ID));
}
 
Example 6
Source Project: lucene-solr   Source File: ResponseLogComponentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testToLogIds() throws Exception {
  SolrQueryRequest req = null;
  try {
    String handler="/withlog";
    req = req("indent","true", "qt","/withlog",  "q","aa", "rows","2",
        "fl","id,subject", "responseLog","true");
    SolrQueryResponse qr = h.queryAndResponse(handler, req);
    NamedList<Object> entries = qr.getToLog();
    String responseLog = (String) entries.get("responseLog");
    assertNotNull(responseLog);
    assertTrue(responseLog.matches("\\w+,\\w+"));
  } finally {
    req.close();
  }
}
 
Example 7
public void testProcessorPrefixReqParam() throws Exception {
  List<UpdateRequestProcessorFactory> processors = UpdateRequestProcessorChain.getReqProcessors("uuid", h.getCore());
  UpdateRequestProcessorFactory processorFactory = processors.get(0);
  assertTrue(processorFactory instanceof UUIDUpdateProcessorFactory);

  SolrQueryResponse rsp = new SolrQueryResponse();
  SolrQueryRequest req = new LocalSolrQueryRequest(h.getCore(), new ModifiableSolrParams());
  AddUpdateCommand cmd = new AddUpdateCommand(req);
  cmd.solrDoc = new SolrInputDocument();
  cmd.solrDoc.addField("random_s", "random_val");

  processorFactory.getInstance(req, rsp, null).processAdd(cmd);
  assertNotNull(cmd.solrDoc);
  assertNotNull(cmd.solrDoc.get("id"));
  assertNotNull(cmd.solrDoc.get("id").getValue());
}
 
Example 8
Source Project: lucene-solr   Source File: XmlUpdateRequestHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExternalEntities() throws Exception
{
  String file = getFile("mailing_lists.pdf").toURI().toASCIIString();
  String xml = 
    "<?xml version=\"1.0\"?>" +
    // check that external entities are not resolved!
    "<!DOCTYPE foo [<!ENTITY bar SYSTEM \""+file+"\">]>" +
    "<add>" +
    "  &bar;" +
    "  <doc>" +
    "    <field name=\"id\">12345</field>" +
    "    <field name=\"name\">kitten</field>" +
    "  </doc>" +
    "</add>";
  SolrQueryRequest req = req();
  SolrQueryResponse rsp = new SolrQueryResponse();
  BufferingRequestProcessor p = new BufferingRequestProcessor(null);
  XMLLoader loader = new XMLLoader().init(null);
  loader.load(req, rsp, new ContentStreamBase.StringStream(xml), p);

  AddUpdateCommand add = p.addCommands.get(0);
  assertEquals("12345", add.solrDoc.getField("id").getFirstValue());
  req.close();
}
 
Example 9
public void testWrongAtomicOpPassed() throws Exception {
  ModifiableSolrParams params = new ModifiableSolrParams()
      .add("processor", "Atomic")
      .add("atomic.cat", "delete")
      .add("commit", "true");
  try (SolrQueryRequest req = new LocalSolrQueryRequest(h.getCore(), params)) {
    AddUpdateCommand cmd = new AddUpdateCommand(req);
    AtomicUpdateProcessorFactory factory = new AtomicUpdateProcessorFactory();
    factory.inform(h.getCore());
    factory.getInstance(cmd.getReq(), new SolrQueryResponse(),
        null).processAdd(cmd);
  } catch (SolrException e) {
    assertEquals("Unexpected param(s) for AtomicUpdateProcessor, invalid atomic op passed: 'delete'",
        e.getMessage());
  }
}
 
Example 10
Source Project: lucene-solr   Source File: MaxSizeAutoCommitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeletes() throws Exception {

  Assert.assertEquals("There have been no updates yet, so there shouldn't have been any commits", 0,
                      hardCommitTracker.getCommitCount());

  long tlogSizePreUpdates = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
  Assert.assertEquals("There have been no updates yet, so tlog should be empty", 0, tlogSizePreUpdates);
  
  // Add docs
  int numDocsToAdd = 500;
  SolrQueryResponse updateResp = new SolrQueryResponse();
  
  monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
      updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
    });
  
  // Delete all documents - should trigger a commit
  
  monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
      updateRequestHandler.handleRequest(constructBatchDeleteDocRequest(0, numDocsToAdd), updateResp);
    });
  
}
 
Example 11
Source Project: lucene-solr   Source File: JsonLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testAtomicUpdateFieldValue() throws Exception {
  String str = "[{'id':'1', 'val_s':{'add':'foo'}}]".replace('\'', '"');
  SolrQueryRequest req = req();
  SolrQueryResponse rsp = new SolrQueryResponse();
  BufferingRequestProcessor p = new BufferingRequestProcessor(null);
  JsonLoader loader = new JsonLoader();
  loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);

  assertEquals( 1, p.addCommands.size() );

  AddUpdateCommand add = p.addCommands.get(0);
  assertEquals(add.commitWithin, -1);
  assertEquals(add.overwrite, true);
  assertEquals("SolrInputDocument(fields: [id=1, val_s={add=foo}])", add.solrDoc.toString());

  req.close();
}
 
Example 12
Source Project: lucene-solr   Source File: ManagedFeatureStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called to retrieve a named part (the given childId) of the resource at the
 * given endpoint. Note: since we have a unique child feature store we ignore
 * the childId.
 */
@Override
public void doGet(BaseSolrResource endpoint, String childId) {
  final SolrQueryResponse response = endpoint.getSolrResponse();

  // If no feature store specified, show all the feature stores available
  if (childId == null) {
    response.add(FEATURE_STORE_JSON_FIELD, stores.keySet());
  } else {
    final FeatureStore store = getFeatureStore(childId);
    if (store == null) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
          "missing feature store [" + childId + "]");
    }
    response.add(FEATURES_JSON_FIELD,
        featuresAsManagedResources(store));
  }
}
 
Example 13
Source Project: lucene-solr   Source File: V2HttpCall.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void execute(SolrQueryResponse rsp) {
  SolrCore.preDecorateResponse(solrReq, rsp);
  if (api == null) {
    rsp.setException(new SolrException(SolrException.ErrorCode.NOT_FOUND,
        "Cannot find correspond api for the path : " + solrReq.getContext().get(CommonParams.PATH)));
  } else {
    try {
      api.call(solrReq, rsp);
    } catch (Exception e) {
      rsp.setException(e);
    }
  }

  SolrCore.postDecorateResponse(handler, solrReq, rsp);
}
 
Example 14
Source Project: lucene-solr   Source File: VelocityResponseWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("SOLR-14025: Velocity's SecureUberspector addresses this")
public void testSandboxIntersection() throws Exception {
  assumeTrue("This test only works with security manager", System.getSecurityManager() != null);
  VelocityResponseWriter vrw = new VelocityResponseWriter();
  NamedList<String> nl = new NamedList<>();
  nl.add("template.base.dir", getFile("velocity").getAbsolutePath());
  vrw.init(nl);
  SolrQueryRequest req = req(VelocityResponseWriter.TEMPLATE,"sandbox_intersection");
  SolrQueryResponse rsp = new SolrQueryResponse();
  StringWriter buf = new StringWriter();
  try {
    vrw.write(buf, req, rsp);
    fail("template broke outside the box, retrieved: " + buf);
  } catch (MethodInvocationException e) {
    assertNotNull(e.getCause());
    assertEquals(AccessControlException.class, e.getCause().getClass());
    // expected failure, can't get outside the box
  }
}
 
Example 15
Source Project: lucene-solr   Source File: MaxSizeAutoCommitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAdds() throws Exception {

  Assert.assertEquals("There have been no updates yet, so there shouldn't have been any commits", 0,
                      hardCommitTracker.getCommitCount());

  long tlogSizePreUpdates = updateHandler.getUpdateLog().getCurrentLogSizeFromStream();
  Assert.assertEquals("There have been no updates yet, so tlog should be empty", 0, tlogSizePreUpdates);

  // Add a large number of docs - should trigger a commit
  int numDocsToAdd = 500;
  SolrQueryResponse updateResp = new SolrQueryResponse();
  
  monitor.doStuffAndExpectAtLeastOneCommit(hardCommitTracker, updateHandler, () -> {
      updateRequestHandler.handleRequest(constructBatchAddDocRequest(0, numDocsToAdd), updateResp);
    });
}
 
Example 16
Source Project: lucene-solr   Source File: AnalyticsComponent.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void finishStage(ResponseBuilder rb) {
  if (rb.isAnalytics() && rb.stage == ResponseBuilder.STAGE_GET_FIELDS) {
    AnalyticsRequestManager reqManager = getAnalyticsRequestManager(rb);
    // Generate responses from the merged shard data
    if (rb.isOlapAnalytics()) {
      rb.rsp.add(AnalyticsResponseHeadings.COMPLETED_OLD_HEADER, reqManager.createOldResponse());
    } else {
      rb.rsp.add(AnalyticsResponseHeadings.COMPLETED_HEADER, reqManager.createResponse());
    }
    if (reqManager.isPartialResults()) {
      rb.rsp.getResponseHeader().asShallowMap().put(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY,true);
    }
  }

  super.finishStage(rb);
}
 
Example 17
Source Project: lucene-solr   Source File: HttpSolrCall.java    License: 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 18
Source Project: lucene-solr   Source File: AnnotatedApi.java    License: Apache License 2.0 6 votes vote down vote up
Cmd(String command, Object obj, Method method) {
  this.command = command;
  this.obj = obj;
  try {
    this.method = MethodHandles.publicLookup().unreflect(method);
  } catch (IllegalAccessException e) {
    throw new RuntimeException("Unable to access method, may be not public or accessible ", e);
  }
  Class<?>[] parameterTypes = method.getParameterTypes();
  paramsCount = parameterTypes.length;
  if (parameterTypes.length == 1) {
    readPayloadType(method.getGenericParameterTypes()[0]);
  } else if (parameterTypes.length == 3) {
    if (parameterTypes[0] != SolrQueryRequest.class || parameterTypes[1] != SolrQueryResponse.class) {
      throw new RuntimeException("Invalid params for method " + method);
    }
    Type t = method.getGenericParameterTypes()[2];
    readPayloadType(t);
  }
  if (parameterTypes.length > 3) {
    throw new RuntimeException("Invalid params count for method " + method);
  }
}
 
Example 19
private SolrQueryRequest request(ModifiableSolrParams params, String handlerName) {
  SolrCore core = h.getCore();
  SolrRequestHandler handler = core.getRequestHandler(handlerName);

  SolrQueryResponse rsp = new SolrQueryResponse();
  NamedList<Object> list = new NamedList<Object>();
  list.add("responseHeader", new SimpleOrderedMap<Object>());
  rsp.setAllValues(list);
  SolrQueryRequest req = new LocalSolrQueryRequest(core, params);
  handler.handleRequest(req, rsp);
  return req;
}
 
Example 20
Source Project: lucene-solr   Source File: RuntimeLibResponseWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {
  rsp.add("wt", RuntimeLibResponseWriter.class.getName());
  rsp.add("loader",  getClass().getClassLoader().getClass().getName() );

  super.write(writer, req, rsp);
}
 
Example 21
Source Project: lucene-solr   Source File: CdcrRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private void handleQueuesAction(SolrQueryRequest req, SolrQueryResponse rsp) {
  NamedList hosts = new NamedList();

  for (CdcrReplicatorState state : replicatorManager.getReplicatorStates()) {
    NamedList queueStats = new NamedList();

    CdcrUpdateLog.CdcrLogReader logReader = state.getLogReader();
    if (logReader == null) {
      String collectionName = req.getCore().getCoreDescriptor().getCloudDescriptor().getCollectionName();
      String shard = req.getCore().getCoreDescriptor().getCloudDescriptor().getShardId();
      log.warn("The log reader for target collection {} is not initialised @ {}:{}",
          state.getTargetCollection(), collectionName, shard);
      queueStats.add(CdcrParams.QUEUE_SIZE, -1l);
    } else {
      queueStats.add(CdcrParams.QUEUE_SIZE, logReader.getNumberOfRemainingRecords());
    }
    queueStats.add(CdcrParams.LAST_TIMESTAMP, state.getTimestampOfLastProcessedOperation());

    if (hosts.get(state.getZkHost()) == null) {
      hosts.add(state.getZkHost(), new NamedList());
    }
    ((NamedList) hosts.get(state.getZkHost())).add(state.getTargetCollection(), queueStats);
  }

  rsp.add(CdcrParams.QUEUES, hosts);
  UpdateLog updateLog = core.getUpdateHandler().getUpdateLog();
  rsp.add(CdcrParams.TLOG_TOTAL_SIZE, updateLog.getTotalLogsSize());
  rsp.add(CdcrParams.TLOG_TOTAL_COUNT, updateLog.getTotalLogsNumber());
  rsp.add(CdcrParams.UPDATE_LOG_SYNCHRONIZER,
      updateLogSynchronizer.isStarted() ? CdcrParams.ProcessState.STARTED.toLower() : CdcrParams.ProcessState.STOPPED.toLower());
}
 
Example 22
Source Project: BioSolr   Source File: TestDJoin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test that (a) sorting works correctly, so that we get docs 1 and 2 returned (sort values A and B)
 *       and (b) we still get all parts of doc 1 returned even though it ranks third on shard/3
 */
@Test
public void testJoin() throws Exception {
  try (SolrCore core = h.getCoreContainer().getCore("djoin")) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("rows", "2");
    params.add("sort", "letter asc");
    params.add("fl", "*,[shard]");

    SolrQueryResponse rsp = query(core, "djoin", params);
    assertNull(rsp.getException());
    SolrDocumentList docs = (SolrDocumentList)rsp.getValues().get("response");
    assertEquals(2, docs.size());
    
    assertEquals(true, docs.get(0).get(DuplicateDocumentList.MERGE_PARENT_FIELD));
    assertEquals(3, docs.get(0).getChildDocumentCount());
    assertEquals("1", docs.get(0).getChildDocuments().get(0).get("id"));
    assertEquals("1", docs.get(0).getChildDocuments().get(1).get("id"));
    assertEquals("1", docs.get(0).getChildDocuments().get(2).get("id"));
    Set<String> letters = new HashSet<>();
    for (SolrDocument doc : docs.get(0).getChildDocuments()) {
      letters.add((String)doc.get("letter"));
    }
    assertEquals(new HashSet<String>(Arrays.asList("A", "D", "E")), letters);
    
    assertEquals(true, docs.get(1).get(DuplicateDocumentList.MERGE_PARENT_FIELD));
    assertEquals(2, docs.get(1).getChildDocumentCount());
    assertEquals("2", docs.get(1).getChildDocuments().get(0).get("id"));
    assertEquals("B", docs.get(1).getChildDocuments().get(0).get("letter"));
    assertEquals("2", docs.get(1).getChildDocuments().get(1).get("id"));
    assertEquals("B", docs.get(1).getChildDocuments().get(1).get("letter"));
  }
}
 
Example 23
Source Project: lucene-solr   Source File: RunUpdateProcessorFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {
  RunUpdateProcessor runUpdateProcessor = new RunUpdateProcessor(req, next);
  UpdateRequestProcessorChain preRun = req.getCore().getUpdateProcessingChain(PRE_RUN_CHAIN_NAME);
  if (preRun != null) {
    return preRun.createProcessor(req, rsp, false, runUpdateProcessor);
  } else {
    return runUpdateProcessor;
  }
}
 
Example 24
Source Project: lucene-solr   Source File: XsltUpdateRequestHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdate() throws Exception
{
  String xml = 
    "<random>" +
    " <document>" +
    "  <node name=\"id\" value=\"12345\"/>" +
    "  <node name=\"name\" value=\"kitten\"/>" +
    "  <node name=\"text\" enhance=\"3\" value=\"some other day\"/>" +
    "  <node name=\"title\" enhance=\"4\" value=\"A story\"/>" +
    "  <node name=\"timestamp\" enhance=\"5\" value=\"2011-07-01T10:31:57.140Z\"/>" +
    " </document>" +
    "</random>";

  Map<String,String> args = new HashMap<>();
  args.put(CommonParams.TR, "xsl-update-handler-test.xsl");
    
  SolrCore core = h.getCore();
  LocalSolrQueryRequest req = new LocalSolrQueryRequest( core, new MapSolrParams( args) );
  ArrayList<ContentStream> streams = new ArrayList<>();
  streams.add(new ContentStreamBase.StringStream(xml));
  req.setContentStreams(streams);
  SolrQueryResponse rsp = new SolrQueryResponse();
  try (UpdateRequestHandler handler = new UpdateRequestHandler()) {
    handler.init(new NamedList<String>());
    handler.handleRequestBody(req, rsp);
  }
  StringWriter sw = new StringWriter(32000);
  QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
  responseWriter.write(sw,req,rsp);
  req.close();
  String response = sw.toString();
  assertU(response);
  assertU(commit());

  assertQ("test document was correctly committed", req("q","*:*")
          , "//result[@numFound='1']"
          , "//str[@name='id'][.='12345']"
      );
}
 
Example 25
@Override
public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {
  List<EngineInfo> scriptEngines = null;

  scriptEngines = initEngines(req, rsp);

  return new ScriptUpdateProcessor(req, rsp, scriptEngines, next);
}
 
Example 26
@Override
public UpdateRequestProcessor getInstance(
		final SolrQueryRequest request, 
		final SolrQueryResponse response, 
		final UpdateRequestProcessor next) {
	return new AddCoordinatesUpdateRequestProcessor(service, sleepTimeInMsecs, next);
}
 
Example 27
Source Project: lucene-solr   Source File: CloudMLTQParser.java    License: Apache License 2.0 5 votes vote down vote up
private SolrDocument getDocument(String id) {
  SolrCore core = req.getCore();
  SolrQueryResponse rsp = new SolrQueryResponse();
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.add(ID, id);

  SolrQueryRequestBase request = new SolrQueryRequestBase(core, params) {
  };

  core.getRequestHandler("/get").handleRequest(request, rsp);
  @SuppressWarnings({"rawtypes"})
  NamedList response = rsp.getValues();

  return (SolrDocument) response.get("doc");
}
 
Example 28
/**
 * Maintenance method
 * @param aclId
 * @throws Exception
 */
public void reindexAclId(long aclId) throws Exception
{
    CoreAdminHandler admin = getMultiCoreHandler();
    SolrQueryResponse resp = new SolrQueryResponse();
    admin.handleRequestBody(req(CoreAdminParams.ACTION, "REINDEX",
                    CoreAdminParams.NAME, getCore().getName(),
                    "aclid", Long.toString(aclId)),
            resp);
}
 
Example 29
Source Project: lucene-solr   Source File: XsltUpdateRequestHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEntities() throws Exception
{
  // use a binary file, so when it's loaded fail with XML eror:
  String file = getFile("mailing_lists.pdf").toURI().toASCIIString();
  String xml = 
    "<?xml version=\"1.0\"?>" +
    "<!DOCTYPE foo [" + 
    // check that external entities are not resolved!
    "<!ENTITY bar SYSTEM \""+file+"\">"+
    // but named entities should be
    "<!ENTITY wacky \"zzz\">"+
    "]>" +
    "<random>" +
    " &bar;" +
    " <document>" +
    "  <node name=\"id\" value=\"12345\"/>" +
    "  <node name=\"foo_s\" value=\"&wacky;\"/>" +
    " </document>" +
    "</random>";
  SolrQueryRequest req = req(CommonParams.TR, "xsl-update-handler-test.xsl");
  SolrQueryResponse rsp = new SolrQueryResponse();
  BufferingRequestProcessor p = new BufferingRequestProcessor(null);
  XMLLoader loader = new XMLLoader().init(null);
  loader.load(req, rsp, new ContentStreamBase.StringStream(xml), p);

  AddUpdateCommand add = p.addCommands.get(0);
  assertEquals("12345", add.solrDoc.getField("id").getFirstValue());
  assertEquals("zzz", add.solrDoc.getField("foo_s").getFirstValue());
  req.close();
}
 
Example 30
Source Project: lucene-solr   Source File: ReplicationHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void reportErrorOnResponse(SolrQueryResponse response, String message, Exception e) {
  response.add(STATUS, ERR_STATUS);
  response.add(MESSAGE, message);
  if (e != null) {
    response.add(EXCEPTION, e);
  }
}