Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chris-moreton/86b8e586719b398d1429e72d6ac1ba3e to your computer and use it in GitHub Desktop.
Save chris-moreton/86b8e586719b398d1429e72d6ac1ba3e to your computer and use it in GitHub Desktop.
Configuration class for using the Searchly Elasticsearch service on Pivotal Web Services (Cloud Foundry), defaulting to localhost:9200 when running locally.
package com.netsensia.directorzone;
import java.util.Base64;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfiguration {
private String getConnectionUrl() throws Exception {
String connectionUrl = null;
String vcapServices = System.getenv("VCAP_SERVICES");
if (!vcapServices.isEmpty()) {
JSONObject vcapServicesJson = new JSONObject(vcapServices);
JSONArray userProvidedServicesArray = vcapServicesJson.getJSONArray("searchly");
JSONObject credentials = null;
for (int i = 0; i < userProvidedServicesArray.length(); i++) {
JSONObject currService = userProvidedServicesArray.getJSONObject(i);
if (currService.getString("name").equals("my-searchly-service-name")) {
credentials = currService.getJSONObject("credentials");
}
}
if (credentials == null) {
throw new Exception("Did not find Searchly service");
}
connectionUrl = credentials.getString("sslUri");
}
return connectionUrl;
}
@Bean
public RestHighLevelClient highLevelRestClient() throws Exception {
String url, protocol;
int port;
Header[] defaultHeaders = null;
String connectionUrl = getConnectionUrl();
if (connectionUrl == null) {
url = "localhost";
port = 9200;
protocol = "http";
} else {
// Assume it's running on Cloud Foundry
port = 443;
protocol = "https";
String parts[] = connectionUrl.replaceAll("https://", "").split("@");
String credentials = parts[0];
url = parts[1];
String base64Credentials = Base64.getEncoder().encodeToString(credentials.getBytes());
defaultHeaders = new Header[] { new BasicHeader("Authorization", "Basic " + base64Credentials) };
}
RestClientBuilder builder = RestClient.builder(new HttpHost(url, port, protocol));
if (defaultHeaders != null) {
builder.setDefaultHeaders(defaultHeaders);
}
return new RestHighLevelClient(builder);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment