Java Code Examples for org.apache.solr.client.solrj.SolrClient

The following examples show how to use org.apache.solr.client.solrj.SolrClient. 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: JsonRequestApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonQueryUsingParamsBlock() throws Exception {
  SolrClient solrClient = cluster.getSolrClient();

  //tag::solrj-json-query-params-block[]
  final ModifiableSolrParams params = new ModifiableSolrParams();
  params.set("fl", "name", "price");
  final JsonQueryRequest simpleQuery = new JsonQueryRequest(params)
      .withParam("q", "memory")
      .withParam("rows", 1);
  QueryResponse queryResponse = simpleQuery.process(solrClient, COLLECTION_NAME);
  // end::solrj-json-query-params-block[]

  assertEquals(0, queryResponse.getStatus());
  assertEquals(1, queryResponse.getResults().size());
  final SolrDocument doc = queryResponse.getResults().get(0);
  final Collection<String> returnedFields = doc.getFieldNames();
  assertEquals(2, doc.getFieldNames().size());
  assertTrue("Expected returned field list to include 'name'", returnedFields.contains("name"));
  assertTrue("Expected returned field list to include 'price'", returnedFields.contains("price"));
}
 
Example 2
/**
 * Has the same behavior as {@link org.apache.solr.client.solrj.SolrClient#deleteByQuery(String)}.
 *
 * @param deleteQuery delete query to be executed
 */
@Override
public void deleteByQuery(String deleteQuery) throws SolrServerException, IOException {
    try {
        for (SolrClient server : solrServers) {
            server.deleteByQuery(deleteQuery);
        }
    } catch (SolrException e) {
        if (isDocumentIssue(e)) {
            documentDeleteErrorMeter.mark(1);
        } else {
            solrDeleteErrorMeter.mark(1);
            throw e;
        }
    } catch (SolrServerException sse) {
        solrDeleteErrorMeter.mark(1);
        throw sse;
    }
}
 
Example 3
@Test
public void testUpdateWithXml() throws IOException, SolrServerException {
    final SolrClient solrClient = createEmbeddedSolrClient(DEFAULT_SOLR_CORE);
    final TestableProcessor proc = new TestableProcessor(solrClient);

    final TestRunner runner = createDefaultTestRunner(proc);
    runner.setProperty(PutSolrContentStream.CONTENT_STREAM_PATH, "/update");
    runner.setProperty(PutSolrContentStream.CONTENT_TYPE, "application/xml");

    try (FileInputStream fileIn = new FileInputStream(XML_MULTIPLE_DOCS_FILE)) {
        runner.enqueue(fileIn);

        runner.run(1, false);
        runner.assertTransferCount(PutSolrContentStream.REL_FAILURE, 0);
        runner.assertTransferCount(PutSolrContentStream.REL_CONNECTION_FAILURE, 0);
        runner.assertTransferCount(PutSolrContentStream.REL_SUCCESS, 1);

        verifySolrDocuments(proc.getSolrClient(), Arrays.asList(expectedDoc1, expectedDoc2));
    } finally {
        try {
            proc.getSolrClient().close();
        } catch (Exception e) {
        }
    }
}
 
Example 4
protected QueryResponse query(SolrClient solrClient, boolean andShards, String json, ModifiableSolrParams params) throws Exception
{
    params.set("distrib", "false");
    QueryRequest request = getAlfrescoRequest(json, params);
    QueryResponse controlRsp = request.process(solrClient);
    SOLR_RESPONSE_COMPARATOR.validateResponse(controlRsp);
    if (andShards)
    {
        params.remove("distrib");
        setDistributedParams(params);
        QueryResponse rsp = queryRandomShard(json, params);
        SOLR_RESPONSE_COMPARATOR.compareResponses(rsp, controlRsp);
        return rsp;
    }
    else
    {
        return controlRsp;
    }
}
 
Example 5
Source Project: nifi   Source File: TestQuerySolr.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRetrievalOfFullResults2() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty(QuerySolr.SOLR_PARAM_FIELD_LIST, "id");
    runner.setProperty(QuerySolr.SOLR_PARAM_SORT, "id asc");
    runner.setProperty(QuerySolr.SOLR_PARAM_ROWS, "3");
    runner.setProperty(QuerySolr.AMOUNT_DOCUMENTS_TO_RETURN, QuerySolr.RETURN_ALL_RESULTS);
    runner.setProperty("facet", "true");
    runner.setProperty("stats", "true");

    runner.enqueue(new byte[0]);
    runner.run();

    runner.assertTransferCount(QuerySolr.RESULTS, 4);
    runner.assertTransferCount(QuerySolr.ORIGINAL, 1);
    runner.assertTransferCount(QuerySolr.FACETS, 1);
    runner.assertTransferCount(QuerySolr.STATS, 1);

    solrClient.close();
}
 
Example 6
@Test
@AwaitsFix(bugUrl="https://issues.apache.org/jira/browse/HADOOP-9893")
public void testForwarding() throws Exception {
  String collectionName = "forwardingCollection";

  // create collection
  CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection(collectionName, "conf1",
      1, 1);
  try (SolrClient solrClient = newSolrClient()) {
    create.process(solrClient);
  }

  // try a command to each node, one of them must be forwarded
  for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
    try (HttpSolrClient client =
             new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName).build()) {
      ModifiableSolrParams params = new ModifiableSolrParams();
      params.set("q", "*:*");
      params.set(USER_PARAM, "user");
      client.query(params);
    }
  }
}
 
Example 7
public static void waitForShardsCount(ModifiableSolrParams query, int count, long waitMillis, long start) throws Exception
{

    long timeOut = start+waitMillis;
    int totalCount = 0;
    query.set("shards", shards);
    SolrClient clientShard = clientShards.get(0);
    while (System.currentTimeMillis() < timeOut)
    {
        QueryResponse response = clientShard.query(query);
        totalCount = (int) response.getResults().getNumFound();
        if (totalCount == count)
        {
            return;
        }
    }
    throw new Exception("Cluster:Wait error expected "+count+" found "+totalCount+" : "+query.toString());
}
 
Example 8
Source Project: lucene-solr   Source File: JsonRequestApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleJsonTermsFacet() throws Exception {
  SolrClient solrClient = cluster.getSolrClient();

  //tag::solrj-json-simple-terms-facet[]
  final TermsFacetMap categoryFacet = new TermsFacetMap("cat").setLimit(3);
  final JsonQueryRequest request = new JsonQueryRequest()
      .setQuery("*:*")
      .withFacet("categories", categoryFacet);
  QueryResponse queryResponse = request.process(solrClient, COLLECTION_NAME);
  //end::solrj-json-simple-terms-facet[]

  assertEquals(0, queryResponse.getStatus());
  assertEquals(32, queryResponse.getResults().getNumFound());
  assertEquals(10, queryResponse.getResults().size());
  final NestableJsonFacet topLevelFacetingData = queryResponse.getJsonFacetingResponse();
  assertHasFacetWithBucketValues(topLevelFacetingData,"categories",
      new FacetBucket("electronics",12),
      new FacetBucket("currency", 4),
      new FacetBucket("memory", 3));
}
 
Example 9
@Override
public boolean filter(MCRSet set) {
    if (!filterEmptySets()) {
        return false;
    }
    SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
    ModifiableSolrParams p = new ModifiableSolrParams();
    String value = set.getSpec();
    p.set(CommonParams.Q, MCROAIUtils.getDefaultSetQuery(value, getConfigPrefix()));
    String restriction = MCROAIUtils.getDefaultRestriction(getConfigPrefix());
    if (restriction != null) {
        p.set(CommonParams.FQ, restriction);
    }
    p.set(CommonParams.ROWS, 1);
    p.set(CommonParams.FL, "id");
    try {
        QueryResponse response = solrClient.query(p);
        return response.getResults().isEmpty();
    } catch (Exception exc) {
        LOGGER.error("Unable to get results of solr server", exc);
        return true;
    }
}
 
Example 10
/** uses a Cursor to iterate over every doc in the index, recording the 'id_i' value in a BitSet */
private static final BitSet allDocs(final SolrClient c, final int maxDocIdExpected) throws Exception {
  BitSet docs = new BitSet(maxDocIdExpected+1);
  String cursorMark = CURSOR_MARK_START;
  int docsOnThisPage = Integer.MAX_VALUE;
  while (0 < docsOnThisPage) {
    final SolrParams p = params("q","*:*",
                                "rows","100",
                                // note: not numeric, but we don't actual care about the order
                                "sort", "id asc",
                                CURSOR_MARK_PARAM, cursorMark);
    QueryResponse rsp = c.query(p);
    cursorMark = rsp.getNextCursorMark();
    docsOnThisPage = 0;
    for (SolrDocument doc : rsp.getResults()) {
      docsOnThisPage++;
      int id_i = ((Integer)doc.get("id_i")).intValue();
      assertTrue("found id_i bigger then expected "+maxDocIdExpected+": " + id_i,
                 id_i <= maxDocIdExpected);
      docs.set(id_i);
    }
    cursorMark = rsp.getNextCursorMark();
  }
  return docs;
}
 
Example 11
Source Project: nifi   Source File: QuerySolrIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStandardResponse() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty(QuerySolr.SOLR_PARAM_QUERY, "id:(doc0 OR doc1)");
    runner.setProperty(QuerySolr.SOLR_PARAM_FIELD_LIST, "id");
    runner.setProperty(QuerySolr.SOLR_PARAM_SORT, "id desc");

    runner.setNonLoopConnection(false);
    runner.run();
    runner.assertAllFlowFilesTransferred(QuerySolr.RESULTS, 1);

    MockFlowFile flowFile = runner.getFlowFilesForRelationship(QuerySolr.RESULTS).get(0);
    flowFile.assertAttributeExists(QuerySolr.ATTRIBUTE_CURSOR_MARK);
    flowFile.assertAttributeExists(QuerySolr.ATTRIBUTE_SOLR_STATUS);
    flowFile.assertAttributeExists(QuerySolr.ATTRIBUTE_QUERY_TIME);

    String expectedXml = "<docs><doc boost=\"1.0\"><field name=\"id\">doc1</field></doc><doc boost=\"1.0\"><field name=\"id\">doc0</field></doc></docs>";
    assertThat(expectedXml, CompareMatcher.isIdenticalTo(new String(runner.getContentAsByteArray(flowFile))));

    solrClient.close();
}
 
Example 12
Source Project: lucene-solr   Source File: JsonRequestApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFacetWidenedUsingQueryDomain() throws Exception {
  SolrClient solrClient = cluster.getSolrClient();

  //tag::solrj-json-facet-query-domain[]
  final TermsFacetMap inStockFacet = new TermsFacetMap("inStock").setLimit(2);
  final TermsFacetMap popularCategoriesFacet = new TermsFacetMap("cat")
      .withDomain(new DomainMap().withQuery("popularity:[8 TO 10]"))
      .setLimit(3);
  final JsonQueryRequest request = new JsonQueryRequest()
      .setQuery("apple")
      .withFacet("popular_categories", popularCategoriesFacet);
  QueryResponse queryResponse = request.process(solrClient, COLLECTION_NAME);
  //end::solrj-json-facet-query-domain[]

  assertEquals(0, queryResponse.getStatus());
  assertEquals(1, queryResponse.getResults().getNumFound());
  assertEquals(1, queryResponse.getResults().size());
  final NestableJsonFacet topLevelFacetingData = queryResponse.getJsonFacetingResponse();
  assertHasFacetWithBucketValues(topLevelFacetingData, "popular_categories",
      new FacetBucket("electronics", 1),
      new FacetBucket("music", 1),
      new FacetBucket("search", 1));
}
 
Example 13
Source Project: kite   Source File: SolrLocatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectsEmbeddedSolrServerAndAddDocument() throws Exception {
  //Solr locator should select EmbeddedSolrServer only solrHome is specified
  SolrLocator solrLocator = new SolrLocator(new SolrMorphlineContext.Builder().build());
  solrLocator.setSolrHomeDir(RESOURCES_DIR + "/solr");
  solrLocator.setCollectionName("collection1");

  SolrServerDocumentLoader documentLoader = (SolrServerDocumentLoader)solrLocator.getLoader();
  SolrClient solrServer = documentLoader.getSolrServer();
  
  assertTrue(solrServer instanceof EmbeddedSolrServer);
  
  SolrInputDocument doc = new SolrInputDocument();
  doc.addField("id", "myId");
  doc.addField("text", "myValue");
  solrServer.add(doc);
  solrServer.commit();
  
  SolrDocument resultDoc = solrServer.getById("myId");
  assertTrue(resultDoc.getFieldValues("text").contains("myValue"));
  
  UpdateResponse deleteResponse = solrServer.deleteById("myId");
  assertEquals(0, deleteResponse.getStatus());
  solrServer.commit();
  solrServer.close();
}
 
Example 14
Source Project: lucene-solr   Source File: DistributedVersionInfoTest.java    License: Apache License 2.0 6 votes vote down vote up
protected long getVersionFromIndex(Replica replica, String docId) throws IOException, SolrServerException {
  Long vers = null;
  String queryStr = (docId != null) ? "id:" + docId : "_version_:[0 TO *]";
  SolrQuery query = new SolrQuery(queryStr);
  query.setRows(1);
  query.setFields("id", "_version_");
  query.addSort(new SolrQuery.SortClause("_version_", SolrQuery.ORDER.desc));
  query.setParam("distrib", false);

  try (SolrClient client = getHttpSolrClient(replica.getCoreUrl())) {
    QueryResponse qr = client.query(query);
    SolrDocumentList hits = qr.getResults();
    if (hits.isEmpty())
      fail("No results returned from query: "+query);

    vers = (Long) hits.get(0).getFirstValue("_version_");
  }

  if (vers == null)
    fail("Failed to get version using query " + query + " from " + replica.getCoreUrl());

  return vers.longValue();
}
 
Example 15
Source Project: lucene-solr   Source File: PackageUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a file to the package store / file store of Solr.
 * 
 * @param client A Solr client
 * @param buffer File contents
 * @param name Name of the file as it will appear in the file store (can be hierarchical)
 * @param sig Signature digest (public key should be separately uploaded to ZK)
 */
public static void postFile(SolrClient client, ByteBuffer buffer, String name, String sig)
    throws SolrServerException, IOException {
  String resource = "/api/cluster/files" + name;
  ModifiableSolrParams params = new ModifiableSolrParams();
  if (sig != null) {
    params.add("sig", sig);
  }
  V2Response rsp = new V2Request.Builder(resource)
      .withMethod(SolrRequest.METHOD.PUT)
      .withPayload(buffer)
      .forceV2(true)
      .withMimeType("application/octet-stream")
      .withParams(params)
      .build()
      .process(client);
  if (!name.equals(rsp.getResponse().get(CommonParams.FILE))) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Mismatch in file uploaded. Uploaded: " +
        rsp.getResponse().get(CommonParams.FILE)+", Original: "+name);
  }
}
 
Example 16
Source Project: lucene-solr   Source File: SplitShardTest.java    License: Apache License 2.0 5 votes vote down vote up
long getNumDocs(CloudSolrClient client) throws Exception {
  String collectionName = client.getDefaultCollection();
  DocCollection collection = client.getZkStateReader().getClusterState().getCollection(collectionName);
  Collection<Slice> slices = collection.getSlices();

  long totCount = 0;
  for (Slice slice : slices) {
    if (!slice.getState().equals(Slice.State.ACTIVE)) continue;
    long lastReplicaCount = -1;
    for (Replica replica : slice.getReplicas()) {
      SolrClient replicaClient = getHttpSolrClient(replica.getBaseUrl() + "/" + replica.getCoreName());
      long numFound = 0;
      try {
        numFound = replicaClient.query(params("q", "*:*", "distrib", "false")).getResults().getNumFound();
        log.info("Replica count={} for {}", numFound, replica);
      } finally {
        replicaClient.close();
      }
      if (lastReplicaCount >= 0) {
        assertEquals("Replica doc count for " + replica, lastReplicaCount, numFound);
      }
      lastReplicaCount = numFound;
    }
    totCount += lastReplicaCount;
  }


  long cloudClientDocs = client.query(new SolrQuery("*:*")).getResults().getNumFound();
  assertEquals("Sum of shard count should equal distrib query doc count", totCount, cloudClientDocs);
  return totCount;
}
 
Example 17
Source Project: lucene-solr   Source File: AbstractFullDistribZkTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected SolrClient createNewSolrClient(String coreName, int port) {
  try {
    // setup the server...
    String baseUrl = buildUrl(port);
    String url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + coreName;
    HttpSolrClient client = getHttpSolrClient(url, DEFAULT_CONNECTION_TIMEOUT, 60000);
    return client;
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 18
Source Project: lucene-solr   Source File: TestDelegationWithHadoopAuth.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private int getStatusCode(String token, final String user, final String op, HttpSolrClient client)
throws Exception {
  SolrClient delegationTokenClient;
  if (random().nextBoolean()) delegationTokenClient = new HttpSolrClient.Builder(client.getBaseURL().toString())
      .withKerberosDelegationToken(token)
      .withResponseParser(client.getParser())
      .build();
  else delegationTokenClient = new CloudSolrClient.Builder(Collections.singletonList(cluster.getZkServer().getZkAddress()), Optional.empty())
      .withLBHttpSolrClientBuilder(new LBHttpSolrClient.Builder()
          .withResponseParser(client.getParser())
          .withSocketTimeout(30000).withConnectionTimeout(15000)
          .withHttpSolrClientBuilder(
              new HttpSolrClient.Builder()
                  .withKerberosDelegationToken(token)
          ))
      .build();
  try {
    ModifiableSolrParams p = new ModifiableSolrParams();
    if (user != null) p.set(PseudoAuthenticator.USER_NAME, user);
    if (op != null) p.set("op", op);
    @SuppressWarnings({"rawtypes"})
    SolrRequest req = getAdminRequest(p);
    if (user != null || op != null) {
      Set<String> queryParams = new HashSet<>();
      if (user != null) queryParams.add(PseudoAuthenticator.USER_NAME);
      if (op != null) queryParams.add("op");
      req.setQueryParams(queryParams);
    }
    try {
      delegationTokenClient.request(req, null);
      return HttpStatus.SC_OK;
    } catch (BaseHttpSolrClient.RemoteSolrException re) {
      return re.code();
    }
  } finally {
    delegationTokenClient.close();
  }
}
 
Example 19
Source Project: dubbox   Source File: SolrTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UpdateResponse deleteById(final String id) {
	Assert.notNull(id, "Cannot delete 'null' id.");

	return execute(new SolrCallback<UpdateResponse>() {
		@Override
		public UpdateResponse doInSolr(SolrClient solrClient) throws SolrServerException, IOException {
			return solrClient.deleteById(id);
		}
	});
}
 
Example 20
private SolrClient getClient(StratioStreamingMessage message) throws IOException, SolrServerException, URISyntaxException, TransformerException, SAXException, ParserConfigurationException {
    String core = message.getStreamName();
    if (solrClients.containsKey(core)) {
        //we have a client for this core
        return solrClients.get(core);
    } else {
        SolrClient solrClient = getSolrclient(core);
        solrClients.put(core, solrClient);
        return solrClient;
    }
}
 
Example 21
Source Project: lucene-solr   Source File: NoOpResponseParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void doBefore() throws IOException, SolrServerException {
  //add document and commit, and ensure it's there
  SolrClient client = getSolrClient();
  SolrInputDocument doc = new SolrInputDocument();
  doc.addField("id", "1234");
  client.add(doc);
  client.commit();
}
 
Example 22
Source Project: aem-solr-search   Source File: SolrPageListener.java    License: Apache License 2.0 5 votes vote down vote up
protected void addOrUpdatePage(Resource pageRes, SolrClient solr) {
		if (pageRes == null) {
				LOG.error("Page does not exist to add/update in solr");
				return;
		}
		GeometrixxMediaContentType dataPage = pageRes.adaptTo(GeometrixxMediaPage.class);
		try {
				LOG.info("Adding/updating page " + pageRes.getPath());
				solr.add(dataPage.getSolrDoc());
				solr.commit();
		} catch (Exception e) {
				LOG.error("Failure to add/update page " + pageRes.getPath(), e);
		}
}
 
Example 23
private void addField(SolrClient client, Map<String,Object> field) throws Exception {
  SchemaResponse.UpdateResponse addFieldResponse = new SchemaRequest.AddField(field).process(client, COLLECTION);
  assertNotNull(addFieldResponse);
  assertEquals(0, addFieldResponse.getStatus());
  assertNull(addFieldResponse.getResponse().get("errors"));
  String fieldName = field.get("name").toString();
  SchemaResponse.FieldResponse fieldResponse = new SchemaRequest.Field(fieldName).process(client, COLLECTION);
  assertNotNull(fieldResponse);
  assertEquals(0, fieldResponse.getStatus());
}
 
Example 24
Source Project: dubbox   Source File: SolrTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void softCommit() {
	if (VersionUtil.isSolr3XAvailable()) {
		throw new UnsupportedOperationException(
				"Soft commit is not available for solr version lower than 4.x - Please check your depdendencies.");
	}
	execute(new SolrCallback<UpdateResponse>() {
		@Override
		public UpdateResponse doInSolr(SolrClient solrClient) throws SolrServerException, IOException {
			return solrClient.commit(true, true, true);
		}
	});
}
 
Example 25
Source Project: kite   Source File: SolrServerDocumentLoader.java    License: Apache License 2.0 5 votes vote down vote up
public SolrServerDocumentLoader(SolrClient server, int batchSize) {
  if (server == null) {
    throw new IllegalArgumentException("solr server must not be null");
  }
  this.server = server;
  if (batchSize <= 0) {
    throw new IllegalArgumentException("batchSize must be a positive number: " + batchSize);      
  }
  this.batchSize = batchSize;
}
 
Example 26
Source Project: lucene-solr   Source File: MultiThreadedOCPTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Waits until the specified async task has completed or time ran out.
 * @return <code>null</code> if the task has not completed, the completion timestamp if the task has completed
 */
private Long waitForTaskToCompleted(SolrClient client, int requestId) throws Exception {
  for (int i = 0; i < 500; i++) {
    Long task = checkTaskHasCompleted(client, requestId);
    if (task != null) {
      return task;
    }
    Thread.sleep(100);
  }

  return null;
}
 
Example 27
Source Project: lucene-solr   Source File: HttpPartitionTest.java    License: Apache License 2.0 5 votes vote down vote up
protected int sendDoc(int docId, Integer minRf, SolrClient solrClient, String collection) throws IOException, SolrServerException {
  SolrInputDocument doc = new SolrInputDocument();
  doc.addField(id, String.valueOf(docId));
  doc.addField("a_t", "hello" + docId);

  UpdateRequest up = new UpdateRequest();
  if (minRf != null) {
    up.setParam(UpdateRequest.MIN_REPFACT, String.valueOf(minRf));
  }
  up.add(doc);
  return cloudClient.getMinAchievedReplicationFactor(collection, solrClient.request(up, collection));
}
 
Example 28
Source Project: lucene-solr   Source File: SolrExampleXMLHttp2Test.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SolrClient createNewSolrClient() {
  try {
    String url = jetty.getBaseUrl().toString() + "/collection1";
    Http2SolrClient client = new Http2SolrClient.Builder(url).connectionTimeout(DEFAULT_CONNECTION_TIMEOUT).build();
    client.setParser(new XMLResponseParser());
    client.setRequestWriter(new RequestWriter());
    return client;
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 29
Source Project: atlas   Source File: AtlasJanusGraphIndexClient.java    License: Apache License 2.0 5 votes vote down vote up
private SolrResponse createFreeTextRequestHandler(SolrClient solrClient, String collectionName,
                                                Map<String, Integer> indexFieldName2SearchWeightMap,
                                                Solr6Index.Mode mode) throws IOException, SolrServerException, AtlasBaseException {
    String searchWeightString = generateSearchWeightString(indexFieldName2SearchWeightMap);
    String payLoadString      = generatePayLoadForFreeText("create-requesthandler", searchWeightString);

    return performRequestHandlerAction(collectionName, solrClient, payLoadString, mode);
}
 
Example 30
Source Project: lucene-solr   Source File: TestConfigSetsAPI.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyException(SolrClient solrClient,
                             @SuppressWarnings({"rawtypes"})ConfigSetAdminRequest request,
    String errorContains) throws Exception {
  Exception e = expectThrows(Exception.class, () -> solrClient.request(request));
  assertTrue("Expected exception message to contain: " + errorContains
      + " got: " + e.getMessage(), e.getMessage().contains(errorContains));
}