1

I'm trying to connect to a solr server using this code:

SolrServer solr = new HttpSolrServer("http://localhost:8080/solr-all");
SolrQuery query = new SolrQuery();

query.setQuery("*:*");
query.setRows(10);
query.setStart(0);

QueryResponse response = solr.query(query);
System.out.println(response);

but i get this error:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: Server at http://localhost:8080/solr-all returned non ok status:401, message:Unauthorized

i really don't know how to set the username and password, i found many exaples on the web using htttpclient but none of them worked for me.

user2071581
  • 183
  • 2
  • 13
  • "returned non ok status:401" Check your solr server functioning or not? is it running in jetty or external server like tomcat?? – Siva Sep 17 '13 at 10:47
  • the server is working fine, but it is running in tomcat... could it create some problems? – user2071581 Sep 17 '13 at 10:49
  • Did you add all the jars from "solr/example/lib/ext" to tomca lib folder?? – Siva Sep 17 '13 at 10:51

3 Answers3

1

To set credentials:

httpclient.getCredentialsProvider().setCredentials(
                    AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
solrServer = new HttpSolrServer(solrUrl, httpclient);//with credentials

Check similar discussion:

Solr 4 with basic authentication

Community
  • 1
  • 1
harsh
  • 7,502
  • 3
  • 31
  • 32
  • i tried to use this solutions but i have a problem with the HttpSolrServer costructor: "no suitable costructor found" – user2071581 Sep 17 '13 at 10:46
  • Which version of solr are you using? – harsh Sep 17 '13 at 10:48
  • "Solr Implementation Version: 4.0-dev 996861" – user2071581 Sep 17 '13 at 10:51
  • some other issue you are facing, 4.0 version do have this : http://svn.apache.org/viewvc/lucene/dev/branches/lucene_solr_4_0/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java?view=markup – harsh Sep 17 '13 at 10:58
  • first make sure you are able to access avaialble constructors of `HttpSolrServer` as per javadoc: http://lucene.apache.org/solr/4_2_1/solr-solrj/org/apache/solr/client/solrj/impl/HttpSolrServer.html, if you verify that there is some mismatch there you are most probably facing classpath issue – harsh Sep 17 '13 at 11:42
  • i'm writing code in netbeans and it suggests me the costructor `HttpSolrServer(String baseURL, HttpClient client)` but when i chose this one i get the error "no suitable costructor found" the version of solarj is: 4.4.0 – user2071581 Sep 17 '13 at 11:51
  • can you verify `HttpClient` is actually `org.apache.http.client.HttpClient` from related `import` statement? – harsh Sep 17 '13 at 12:13
  • my `httpClient` is `org.apache.commons.httpclient.HttpClient`. in `org.apache.http.client` i only have `fluent` packet. – user2071581 Sep 17 '13 at 12:24
  • Exactly, this means you have `commons-httpclient-*.jar`, what you additionally require is `httpclient-*.jar` e.g. `httpclient-4.1.1.jar`. This is the reason for `No suitable constructor`. Add httpclient jar in your classpath and replace older `HttpClient` import with `org.apache.http.client.HttpClient` – harsh Sep 17 '13 at 12:33
  • `HttpClient` in `org.apache.http.client` is abstract. the (deprecated) `DefaultHttpClient` doesn't have `GetCredentialsProvider()` method. i'm using httpclient-4.3. i tried with 4.1.1 version too. – user2071581 Sep 17 '13 at 12:51
0

SolrConfig:

@Configuration
public class SolrConfig {

    @Value("${solr.http.url}")
    private String solrUrl;

    @Value("${solr.http.username}")
    private String solrUser;

    @Value("${solr.http.password}")
    private String solrPassword;

    @Value("${solr.http.pool.maxTotal}")
    private int poolMaxTotal;

    @Value("${solr.http.pool.maxPerRoute}")
    private int pollMaxPerRoute;

    @Bean
    public SolrClient solrClient() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(poolMaxTotal);
        connectionManager.setDefaultMaxPerRoute(pollMaxPerRoute);

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(solrUser, solrPassword));

        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .addInterceptorFirst(new PreemptiveAuthInterceptor())
                .setConnectionManager(connectionManager)
                .setDefaultCredentialsProvider(credentialsProvider)
                .build();

        return new HttpSolrClient.Builder(solrUrl).withHttpClient(httpClient).build();
    }


}

PreemptiveAuthInterceptor:

public class PreemptiveAuthInterceptor implements HttpRequestInterceptor {

    public void process(final HttpRequest request, final HttpContext context)
            throws HttpException {
        AuthState authState = (AuthState) context
                .getAttribute(HttpClientContext.TARGET_AUTH_STATE);

        // If no auth scheme available yet, try to initialize it
        // preemptively
        if (authState.getAuthScheme() == null) {
            CredentialsProvider credentialsProvider = (CredentialsProvider) context
                    .getAttribute(HttpClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context
                    .getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            Credentials credentials = credentialsProvider.getCredentials(new AuthScope(
                    targetHost.getHostName(), targetHost.getPort()));
            if (credentials == null) {
                throw new HttpException(
                        "No credentials for preemptive authentication");
            }
            authState.update(new BasicScheme(), credentials);
        }

    }

}

SolrController:

@RestController
public class SolrController {

    private final SolrClient solrClient;
    private final Gson gson;

    @Autowired
    public SolrController(SolrClient solrClient, Gson gson) {
        this.solrClient = solrClient;
        this.gson = gson;
    }

    @GetMapping("/search")
    SolrDocumentList search(@RequestParam("q") String q) {
        SolrQuery query = new SolrQuery();
        query.set("q", q);

        QueryRequest queryRequest = new QueryRequest(query);
        QueryResponse response = queryRequest.process(solrClient);
        return response.getResults();
    }

    @PutMapping("/add")
    public void addIndex(HttpEntity<String> httpEntity) {
        Type type = new TypeToken<Map<String, Object>>(){}.getType();
        Map<String, Object> map = gson.fromJson(httpEntity.getBody(), type);
        if (isNull(map)) return;
        SolrInputDocument doc = new SolrInputDocument();
        for (var entry : map.entrySet()) {
            doc.addField(entry.getKey(), entry.getValue());
        }

        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.add(doc);
        solrClient.request(updateRequest);
    }

}
Yersin
  • 1,639
  • 1
  • 9
  • 6
-2

Could you please check Slf4j is available at runtime ?

 Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Means your code needs this class at runtime.

Fraz
  • 17
  • 1