|
| 1 | +/* |
| 2 | + * Copyright 2022 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.springframework.data.couchbase.domain; |
| 17 | + |
| 18 | +import static com.couchbase.client.java.query.QueryOptions.queryOptions; |
| 19 | +import static java.nio.charset.StandardCharsets.UTF_8; |
| 20 | + |
| 21 | +import okhttp3.OkHttpClient; |
| 22 | +import okhttp3.Request; |
| 23 | +import okhttp3.Response; |
| 24 | +import okhttp3.tls.HandshakeCertificates; |
| 25 | + |
| 26 | +import java.io.IOException; |
| 27 | +import java.io.UnsupportedEncodingException; |
| 28 | +import java.security.InvalidKeyException; |
| 29 | +import java.security.NoSuchAlgorithmException; |
| 30 | +import java.time.Duration; |
| 31 | +import java.util.ArrayList; |
| 32 | +import java.util.Base64; |
| 33 | +import java.util.HashMap; |
| 34 | +import java.util.List; |
| 35 | +import java.util.Map; |
| 36 | + |
| 37 | +import javax.crypto.Mac; |
| 38 | +import javax.crypto.spec.SecretKeySpec; |
| 39 | + |
| 40 | +import com.couchbase.client.core.deps.io.netty.handler.ssl.util.InsecureTrustManagerFactory; |
| 41 | +import com.couchbase.client.core.env.IoConfig; |
| 42 | +import com.couchbase.client.core.env.SecurityConfig; |
| 43 | +import com.couchbase.client.java.Bucket; |
| 44 | +import com.couchbase.client.java.Cluster; |
| 45 | +import com.couchbase.client.java.ClusterOptions; |
| 46 | +import com.couchbase.client.java.Collection; |
| 47 | +import com.couchbase.client.java.env.ClusterEnvironment; |
| 48 | +import com.couchbase.client.java.json.JsonArray; |
| 49 | +import com.couchbase.client.java.json.JsonObject; |
| 50 | +import com.couchbase.client.java.manager.query.CreatePrimaryQueryIndexOptions; |
| 51 | +import com.couchbase.client.java.query.QueryResult; |
| 52 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 53 | + |
| 54 | +/** |
| 55 | + * Sample code for connecting to Capella through both the control-plane and the data-plane. An Access Key and a Secret |
| 56 | + * Key are required and a bucket named "my_bucket" on the 'last' cluster. |
| 57 | + */ |
| 58 | +public class CapellaConnectSample { |
| 59 | + |
| 60 | + static final String cbc_access_key = "3gcpgyTBzOetdETYxOAtmLYBe3f9ZSVN"; |
| 61 | + static final String cbc_secret_key = "PWiACuJIZUlv0fCZaIQbhI44NDXVZCDdRBbpdaWlACioN7jkuOINCUVrU2QL1jVO"; |
| 62 | + static final String hostname = "cloudapi.cloud.couchbase.com"; |
| 63 | + static final HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder() |
| 64 | + .addPlatformTrustedCertificates().addInsecureHost(hostname).build(); |
| 65 | + static final OkHttpClient httpClient = new OkHttpClient.Builder() |
| 66 | + .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager()).build(); |
| 67 | + |
| 68 | + protected static final ObjectMapper MAPPER = new ObjectMapper(); |
| 69 | + static final String authorizationHeaderLabel = "Authorization"; |
| 70 | + static final String timestampHeaderLabel = "Couchbase-Timestamp"; |
| 71 | + |
| 72 | + public static void main(String... args) { |
| 73 | + String endpoint = null; // "cb.zsibzkbgllfbcj8g.cloud.couchbase.com"; |
| 74 | + List<String> clusterIds = getClustersControlPlane(); |
| 75 | + for (String id : clusterIds) { |
| 76 | + endpoint = getClusterControlPlane(id); |
| 77 | + } |
| 78 | + |
| 79 | + // Update this to your cluster |
| 80 | + String bucketName = "my_bucket"; |
| 81 | + String username = "user"; |
| 82 | + String password = "Couch0base!"; |
| 83 | + // User Input ends here. |
| 84 | + |
| 85 | + ClusterEnvironment env = ClusterEnvironment.builder() |
| 86 | + .securityConfig(SecurityConfig.enableTls(true).trustManagerFactory(InsecureTrustManagerFactory.INSTANCE)) |
| 87 | + .ioConfig(IoConfig.enableDnsSrv(true)).build(); |
| 88 | + |
| 89 | + // Initialize the Connection |
| 90 | + Cluster cluster = Cluster.connect(endpoint, ClusterOptions.clusterOptions(username, password).environment(env)); |
| 91 | + Bucket bucket = cluster.bucket(bucketName); |
| 92 | + bucket.waitUntilReady(Duration.parse("PT10S")); |
| 93 | + Collection collection = bucket.defaultCollection(); |
| 94 | + |
| 95 | + cluster.queryIndexes().createPrimaryIndex(bucketName, |
| 96 | + CreatePrimaryQueryIndexOptions.createPrimaryQueryIndexOptions().ignoreIfExists(true)); |
| 97 | + |
| 98 | + // Create a JSON Document |
| 99 | + JsonObject arthur = JsonObject. create(). put( "name", "Arthur"). put( "email", "[email protected]") |
| 100 | + .put("interests", JsonArray.from("Holy Grail", "African Swallows")); |
| 101 | + |
| 102 | + // Store the Document |
| 103 | + collection.upsert("u:king_arthur", arthur); |
| 104 | + |
| 105 | + // Load the Document and print it |
| 106 | + // Prints Content and Metadata of the stored Document |
| 107 | + System.err.println(collection.get("u:king_arthur")); |
| 108 | + |
| 109 | + // Perform a N1QL Query |
| 110 | + QueryResult result = cluster.query(String.format("SELECT name FROM `%s` WHERE $1 IN interests", bucketName), |
| 111 | + queryOptions().parameters(JsonArray.from("African Swallows"))); |
| 112 | + |
| 113 | + // Print each found Row |
| 114 | + for (JsonObject row : result.rowsAsObject()) { |
| 115 | + System.err.println(row); |
| 116 | + } |
| 117 | + |
| 118 | + cluster.disconnect(); |
| 119 | + } |
| 120 | + |
| 121 | + public static List<String> getClustersControlPlane() { |
| 122 | + List<String> clusterIds = new ArrayList<>(); |
| 123 | + Map<String, Object> decoded = doRequest(hostname, "GET", "/v3/clusters"); |
| 124 | + HashMap data = (HashMap) decoded.get("data"); |
| 125 | + List<Map> items = (List<Map>) data.get("items"); |
| 126 | + for (Map m : items) { |
| 127 | + clusterIds.add((String) m.get("id")); |
| 128 | + } |
| 129 | + return clusterIds; |
| 130 | + } |
| 131 | + |
| 132 | + public static String getClusterControlPlane(String clusterId) { |
| 133 | + String endpointsSrv; |
| 134 | + Map<String, Object> decoded = doRequest(hostname, "GET", "/v3/clusters/" + clusterId); |
| 135 | + endpointsSrv = (String) decoded.get("endpointsSrv"); |
| 136 | + return endpointsSrv; |
| 137 | + } |
| 138 | + |
| 139 | + private static Map<String, Object> doRequest(String hostname, String cbc_api_method, String cbc_api_endpoint) { |
| 140 | + Map<String, Object> decoded; |
| 141 | + String responseString; |
| 142 | + try { |
| 143 | + String cbc_api_now = Long.toString(System.currentTimeMillis()); |
| 144 | + String authorizationValue = getApiSignature(cbc_api_method, cbc_api_endpoint, cbc_api_now); |
| 145 | + String urlString = "https://" + hostname + cbc_api_endpoint; |
| 146 | + System.err.println("curl --header \"" + authorizationHeaderLabel + ": " + authorizationValue + "\" --header \"" |
| 147 | + + timestampHeaderLabel + ": " + cbc_api_now + "\" " + urlString); |
| 148 | + Response response = httpClient.newCall(new Request.Builder().header(authorizationHeaderLabel, authorizationValue) |
| 149 | + .header(timestampHeaderLabel, cbc_api_now).url(urlString).build()).execute(); |
| 150 | + responseString = response.body().string(); |
| 151 | + System.err.println(responseString); |
| 152 | + } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { |
| 153 | + throw new RuntimeException(e); |
| 154 | + } |
| 155 | + |
| 156 | + try { |
| 157 | + decoded = (Map<String, Object>) MAPPER.readValue(responseString.getBytes(UTF_8), Map.class); |
| 158 | + } catch (IOException e) { |
| 159 | + throw new RuntimeException("Error decoding, raw: " + responseString, e); |
| 160 | + } |
| 161 | + return decoded; |
| 162 | + } |
| 163 | + |
| 164 | + private static String getApiSignature(String cbc_api_method, String cbc_api_endpoint, String cbc_api_now) |
| 165 | + throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { |
| 166 | + String cbc_api_message = cbc_api_method + '\n' + cbc_api_endpoint + '\n' + cbc_api_now; |
| 167 | + return "Bearer " + cbc_access_key + ':' + new String(Base64.getEncoder() |
| 168 | + .encode(hmac("hmacSHA256", cbc_secret_key.getBytes("utf-8"), cbc_api_message.getBytes("utf-8")))); |
| 169 | + } |
| 170 | + |
| 171 | + static byte[] hmac(String algorithm, byte[] key, byte[] message) |
| 172 | + throws NoSuchAlgorithmException, InvalidKeyException { |
| 173 | + Mac mac = Mac.getInstance(algorithm); |
| 174 | + mac.init(new SecretKeySpec(key, algorithm)); |
| 175 | + return mac.doFinal(message); |
| 176 | + } |
| 177 | + |
| 178 | +} |
0 commit comments