sorted = null;
133 | if (list != null) {
134 | sorted = new ArrayList<>(list);
135 | sorted.sort(Comparator.comparing(Service::getId));
136 | }
137 | return sorted;
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/ServiceQueryOptions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | import io.vertx.codegen.annotations.DataObject;
19 | import io.vertx.codegen.json.annotations.JsonGen;
20 | import io.vertx.core.json.JsonObject;
21 |
22 | /**
23 | * Options used to requesting list of services
24 | *
25 | * @author Ruslan Sennov
26 | */
27 | @DataObject
28 | @JsonGen(publicConverter = false)
29 | public class ServiceQueryOptions {
30 |
31 | private String tag;
32 | private String near;
33 | private BlockingQueryOptions options;
34 |
35 | /**
36 | * Default constructor
37 | */
38 | public ServiceQueryOptions() {}
39 |
40 | /**
41 | * Constructor from JSON
42 | *
43 | * @param json the JSON
44 | */
45 | public ServiceQueryOptions(JsonObject json) {
46 | ServiceQueryOptionsConverter.fromJson(json, this);
47 | }
48 |
49 | /**
50 | * Convert to JSON
51 | *
52 | * @return the JSON
53 | */
54 | public JsonObject toJson() {
55 | JsonObject jsonObject = new JsonObject();
56 | ServiceQueryOptionsConverter.toJson(this, jsonObject);
57 | return jsonObject;
58 | }
59 |
60 | /**
61 | * Get node name for sorting the list in ascending order based on the estimated round trip time from that node.
62 | *
63 | * @return the node name
64 | */
65 | public String getNear() {
66 | return near;
67 | }
68 |
69 | /**
70 | * Set node name for sorting the list in ascending order based on the estimated round trip time from that node.
71 | *
72 | * @param near the node name
73 | * @return reference to this, for fluency
74 | */
75 | public ServiceQueryOptions setNear(String near) {
76 | this.near = near;
77 | return this;
78 | }
79 |
80 | /**
81 | * Get tag for filtering request results
82 | *
83 | * @return the tag
84 | */
85 | public String getTag() {
86 | return tag;
87 | }
88 |
89 | /**
90 | * Set tag for filtering request results
91 | *
92 | * @param tag the tag
93 | * @return reference to this, for fluency
94 | */
95 | public ServiceQueryOptions setTag(String tag) {
96 | this.tag = tag;
97 | return this;
98 | }
99 |
100 | /**
101 | * Get options for blocking query
102 | *
103 | * @return the blocking options
104 | */
105 | public BlockingQueryOptions getBlockingOptions() {
106 | return options;
107 | }
108 |
109 | /**
110 | * Set options for blocking query
111 | *
112 | * @param options the blocking options
113 | * @return reference to this, for fluency
114 | */
115 | public ServiceQueryOptions setBlockingOptions(BlockingQueryOptions options) {
116 | this.options = options;
117 | return this;
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/SessionBehavior.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | import io.vertx.codegen.annotations.VertxGen;
19 |
20 | /**
21 | * When a session is invalidated, it is destroyed and can no longer be used. What happens to the associated locks
22 | * depends on the behavior specified at creation time. Consul supports a release and delete behavior.
23 | * The release behavior is the default if none is specified.
24 | *
25 | * If the release behavior is being used, any of the locks held in association with the session are released,
26 | * and the ModifyIndex of the key is incremented. Alternatively, if the delete behavior is used,
27 | * the key corresponding to any of the held locks is simply deleted. This can be used to create ephemeral
28 | * entries that are automatically deleted by Consul.
29 | *
30 | * @author Ruslan Sennov
31 | * @see Consul sessions documentation
32 | */
33 | @VertxGen
34 | public enum SessionBehavior {
35 |
36 | RELEASE("release"),
37 | DELETE("delete");
38 |
39 | public final String key;
40 |
41 | public static SessionBehavior of(String key) {
42 | for (SessionBehavior sessionBehavior : values()) {
43 | if (sessionBehavior.key.equals(key)) {
44 | return sessionBehavior;
45 | }
46 | }
47 | return null;
48 | }
49 |
50 | SessionBehavior(String key) {
51 | this.key = key;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/SessionList.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | import io.vertx.codegen.annotations.DataObject;
19 | import io.vertx.codegen.json.annotations.JsonGen;
20 | import io.vertx.core.json.JsonObject;
21 |
22 | import java.util.ArrayList;
23 | import java.util.Comparator;
24 | import java.util.List;
25 |
26 | /**
27 | * Holds result of sessions query
28 | *
29 | * @author Ruslan Sennov
30 | */
31 | @DataObject
32 | @JsonGen(publicConverter = false)
33 | public class SessionList {
34 |
35 | private long index;
36 | private List list;
37 |
38 | /**
39 | * Default constructor
40 | */
41 | public SessionList() {}
42 |
43 | /**
44 | * Copy constructor
45 | *
46 | * @param other the one to copy
47 | */
48 | public SessionList(SessionList other) {
49 | this.index = other.index;
50 | this.list = other.list;
51 | }
52 |
53 | /**
54 | * Constructor from JSON
55 | *
56 | * @param json the JSON
57 | */
58 | public SessionList(JsonObject json) {
59 | SessionListConverter.fromJson(json, this);
60 | }
61 |
62 | /**
63 | * Convert to JSON
64 | *
65 | * @return the JSON
66 | */
67 | public JsonObject toJson() {
68 | JsonObject jsonObject = new JsonObject();
69 | SessionListConverter.toJson(this, jsonObject);
70 | return jsonObject;
71 | }
72 |
73 | /**
74 | * Get Consul index
75 | *
76 | * @return the consul index
77 | */
78 | public long getIndex() {
79 | return index;
80 | }
81 |
82 | /**
83 | * Set Consul index, a unique identifier representing the current state of the requested list of sessions
84 | *
85 | * @param index the consul index
86 | * @return reference to this, for fluency
87 | */
88 | public SessionList setIndex(long index) {
89 | this.index = index;
90 | return this;
91 | }
92 |
93 | /**
94 | * Get list of sessions
95 | *
96 | * @return the list of sessions
97 | */
98 | public List getList() {
99 | return list;
100 | }
101 |
102 | /**
103 | * Set list of sessions
104 | *
105 | * @param list the list of sessions
106 | * @return reference to this, for fluency
107 | */
108 | public SessionList setList(List list) {
109 | this.list = list;
110 | return this;
111 | }
112 |
113 | @Override
114 | public boolean equals(Object o) {
115 | if (this == o) return true;
116 | if (o == null || getClass() != o.getClass()) return false;
117 |
118 | SessionList that = (SessionList) o;
119 |
120 | if (index != that.index) return false;
121 | return list != null ? sorted().equals(that.sorted()) : that.list == null;
122 | }
123 |
124 | @Override
125 | public int hashCode() {
126 | int result = (int) (index ^ (index >>> 32));
127 | result = 31 * result + (list != null ? sorted().hashCode() : 0);
128 | return result;
129 | }
130 |
131 | private List sorted() {
132 | List sorted = null;
133 | if (list != null) {
134 | sorted = new ArrayList<>(list);
135 | sorted.sort(Comparator.comparing(Session::getId));
136 | }
137 | return sorted;
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnError.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | import io.vertx.codegen.annotations.DataObject;
19 | import io.vertx.codegen.json.annotations.JsonGen;
20 | import io.vertx.core.json.JsonObject;
21 |
22 | /**
23 | * Holds information describing which operations failed if the transaction was rolled back.
24 | *
25 | * @author Ruslan Sennov
26 | */
27 | @DataObject
28 | @JsonGen(publicConverter = false)
29 | public class TxnError {
30 |
31 | private int opIndex;
32 | private String what;
33 |
34 | /**
35 | * Default constructor
36 | */
37 | public TxnError() {
38 | }
39 |
40 | /**
41 | * Constructor from JSON
42 | *
43 | * @param json the JSON
44 | */
45 | public TxnError(JsonObject json) {
46 | TxnErrorConverter.fromJson(json, this);
47 | }
48 |
49 | /**
50 | * Convert to JSON
51 | *
52 | * @return the JSON
53 | */
54 | public JsonObject toJson() {
55 | JsonObject jsonObject = new JsonObject();
56 | TxnErrorConverter.toJson(this, jsonObject);
57 | return jsonObject;
58 | }
59 |
60 | /**
61 | * Get the index of the failed operation in the transaction
62 | *
63 | * @return the index of the failed operation in the transaction
64 | */
65 | public int getOpIndex() {
66 | return opIndex;
67 | }
68 |
69 | /**
70 | * Get error message about why that operation failed.
71 | *
72 | * @return error message about why that operation failed.
73 | */
74 | public String getWhat() {
75 | return what;
76 | }
77 |
78 | /**
79 | * Set the index of the failed operation in the transaction
80 | *
81 | * @param opIndex the index of the failed operation in the transaction
82 | * @return reference to this, for fluency
83 | */
84 | public TxnError setOpIndex(int opIndex) {
85 | this.opIndex = opIndex;
86 | return this;
87 | }
88 |
89 | /**
90 | * Set error message about why that operation failed.
91 | *
92 | * @param what error message about why that operation failed.
93 | * @return reference to this, for fluency
94 | */
95 | public TxnError setWhat(String what) {
96 | this.what = what;
97 | return this;
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnKVVerb.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | import io.vertx.codegen.annotations.VertxGen;
19 |
20 | /**
21 | * Holds type of KV operation in transaction
22 | *
23 | * @author Ruslan Sennov
24 | * @see /v1/txn endpoint
25 | */
26 | @VertxGen
27 | public enum TxnKVVerb {
28 |
29 | /**
30 | * Sets the Key to the given Value
31 | */
32 | SET("set"),
33 |
34 | /**
35 | * Sets the Key to the given Value with check-and-set semantics.
36 | * The Key will only be set if its current modify index matches the supplied Index
37 | */
38 | CAS("cas"),
39 |
40 | /**
41 | * Locks the Key with the given Session. The Key will only obtain the lock
42 | * if the Session is valid, and no other session has it locked
43 | */
44 | LOCK("lock"),
45 |
46 | /**
47 | * Unlocks the Key with the given Session. The Key will only release the lock
48 | * if the Session is valid and currently has it locked
49 | */
50 | UNLOCK("unlock"),
51 |
52 | /**
53 | * Gets the Key during the transaction. This fails the transaction if the Key doesn't exist.
54 | * The key may not be present in the results if ACLs do not permit it to be read
55 | */
56 | GET("get"),
57 |
58 | /**
59 | * Gets all keys with a prefix of Key during the transaction. This does not fail the transaction
60 | * if the Key doesn't exist. Not all keys may be present in the results if ACLs do not permit them to be read
61 | */
62 | GET_TREE("get-tree"),
63 |
64 | /**
65 | * Fails the transaction if Key does not have a modify index equal to Index
66 | */
67 | CHECK_INDEX("check-index"),
68 |
69 | /**
70 | * Fails the transaction if Key is not currently locked by Session
71 | */
72 | CHECK_SESSION("check-session"),
73 |
74 | /**
75 | * Deletes the Key
76 | */
77 | DELETE("delete"),
78 |
79 | /**
80 | * Deletes all keys with a prefix ofKey
81 | */
82 | DELETE_TREE("delete-tree"),
83 |
84 | /**
85 | * Deletes the Key with check-and-set semantics. The Key will only be deleted
86 | * if its current modify index matches the supplied Index
87 | */
88 | DELETE_CAS("delete-cas");
89 |
90 | public static TxnKVVerb ofVerb(String verb) {
91 | for (TxnKVVerb type : values()) {
92 | if (type.getVerb().equals(verb)) {
93 | return type;
94 | }
95 | }
96 | return null;
97 | }
98 |
99 | private final String verb;
100 |
101 | TxnKVVerb(String verb) {
102 | this.verb = verb;
103 | }
104 |
105 | public String getVerb() {
106 | return verb;
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnOperation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | /**
19 | * Represents operation in transaction. The available operation types are KV and Service
20 | *
21 | * @author Ruslan Sennov
22 | */
23 | public interface TxnOperation {
24 |
25 | /**
26 | * Returns the type of operation in a transaction
27 | *
28 | * @return the type of operation in a transaction
29 | */
30 | TxnOperationType getOperationType();
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnOperationType.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul;
2 |
3 | import io.vertx.codegen.annotations.VertxGen;
4 |
5 | /**
6 | * Represents the type of operation in a transaction. The available operation types are KV and Service
7 | *
8 | * @author Ruslan Sennov
9 | * @see /v1/txn endpoint
10 | */
11 | @VertxGen
12 | public enum TxnOperationType {
13 | KV,
14 | SERVICE
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnResponse.java:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * Copyright (c) 2016 The original author or authors
4 | *
5 | * All rights reserved. This program and the accompanying materials
6 | * are made available under the terms of the Eclipse Public License v1.0
7 | * and Apache License v2.0 which accompanies this distribution.
8 | *
9 | * The Eclipse Public License is available at
10 | * http://www.eclipse.org/legal/epl-v10.html
11 | *
12 | * The Apache License v2.0 is available at
13 | * http://www.opensource.org/licenses/apache2.0.php
14 | *
15 | * You may elect to redistribute this code under either of these licenses.
16 | */
17 | package io.vertx.ext.consul;
18 |
19 | import io.vertx.codegen.annotations.DataObject;
20 | import io.vertx.core.json.JsonArray;
21 | import io.vertx.core.json.JsonObject;
22 |
23 | import java.util.ArrayList;
24 | import java.util.List;
25 |
26 | /**
27 | * Holds results of transaction
28 | *
29 | * @author Ruslan Sennov
30 | */
31 | @DataObject
32 | public class TxnResponse {
33 |
34 | private final List results = new ArrayList<>();
35 | private final List errors = new ArrayList<>();
36 |
37 | /**
38 | * Default constructor
39 | */
40 | public TxnResponse() {
41 | }
42 |
43 | /**
44 | * Constructor from JSON
45 | *
46 | * @param json the JSON
47 | */
48 | public TxnResponse(JsonObject json) {
49 | if (json.getValue("Results") instanceof JsonArray) {
50 | json.getJsonArray("Results").forEach(entry -> {
51 | JsonObject obj = (JsonObject) entry;
52 | if (obj.containsKey("KV")) {
53 | results.add(new KeyValue(obj.getJsonObject("KV")));
54 | } else if (obj.containsKey("Service")) {
55 | Service service = new Service(obj.getJsonObject("Service"));
56 | service.setName(obj.getJsonObject("Service").getString("Service"));
57 | results.add(service);
58 | }
59 | });
60 | }
61 | if (json.getValue("Errors") instanceof JsonArray) {
62 | json.getJsonArray("Errors").forEach(entry -> errors.add(new TxnError((JsonObject) entry)));
63 | }
64 | }
65 |
66 | /**
67 | * Convert to JSON
68 | *
69 | * @return the JSON
70 | */
71 | public JsonObject toJson() {
72 | JsonArray jsonResults = new JsonArray();
73 | results.forEach(op -> {
74 | if (op instanceof KeyValue) {
75 | jsonResults.add(new JsonObject().put("KV", ((KeyValue) op).toJson()));
76 | } else if (op instanceof Service) {
77 | JsonObject jsonObject = ((Service) op).toJson();
78 | jsonObject.put("Service", jsonObject.getString("ServiceName"));
79 | jsonObject.remove("ServiceName");
80 | jsonResults.add(new JsonObject().put("Service", jsonObject));
81 | }
82 | });
83 | JsonArray jsonErrors = new JsonArray();
84 | errors.forEach(err -> jsonErrors.add(err.toJson()));
85 | return new JsonObject().put("Results", jsonResults).put("Errors", jsonErrors);
86 | }
87 |
88 | /**
89 | * Returns list of transaction results
90 | *
91 | * @return list of transaction results
92 | */
93 | public List getResults() {
94 | return results;
95 | }
96 |
97 | /**
98 | * Returns the number of results in this response
99 | *
100 | * @return the number of results in this response
101 | */
102 | public int getResultsSize() {
103 | return results.size();
104 | }
105 |
106 | /**
107 | * Returns the result at the specified position in this list
108 | *
109 | * @param index index of the result to return
110 | * @return the result at the specified position in this list
111 | */
112 | public TxnResult getResult(int index) {
113 | return results.get(index);
114 | }
115 |
116 | /**
117 | * Adds result to this response
118 | *
119 | * @param result the result
120 | * @return reference to this, for fluency
121 | */
122 | public TxnResponse addResult(TxnResult result) {
123 | results.add(result);
124 | return this;
125 | }
126 |
127 | /**
128 | * Returns list of transaction errors
129 | *
130 | * @return list of transaction errors
131 | */
132 | public List getErrors() {
133 | return errors;
134 | }
135 |
136 | /**
137 | * Returns the number of errors in this response
138 | *
139 | * @return the number of errors in this response
140 | */
141 | public int getErrorsSize() {
142 | return errors.size();
143 | }
144 |
145 | /**
146 | * Returns the errors at the specified position in this list
147 | *
148 | * @param index index of the error to return
149 | * @return the error at the specified position in this list
150 | */
151 | public TxnError getError(int index) {
152 | return errors.get(index);
153 | }
154 |
155 | /**
156 | * Adds error to this response
157 | *
158 | * @param error the error
159 | * @return reference to this, for fluency
160 | */
161 | public TxnResponse addError(TxnError error) {
162 | errors.add(error);
163 | return this;
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | /**
19 | * Represents result of operation. The available operation types are KV and Service
20 | *
21 | * @author Ruslan Sennov
22 | */
23 | public interface TxnResult {
24 |
25 | TxnOperationType getOperationType();
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnServiceOperation.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.codegen.annotations.GenIgnore;
5 | import io.vertx.core.json.JsonObject;
6 | import io.vertx.codegen.json.annotations.JsonGen;
7 |
8 | /**
9 | * Holds the operation to apply to the service inside a transaction
10 | */
11 | @DataObject
12 | @JsonGen(publicConverter = false)
13 | public class TxnServiceOperation implements TxnOperation {
14 |
15 | private TxnServiceVerb type;
16 | private String node;
17 | private ServiceOptions serviceOptions;
18 |
19 | /**
20 | * Default constructor
21 | */
22 | public
23 | TxnServiceOperation() {
24 |
25 | }
26 |
27 | /**
28 | * Constructor from JSON
29 | *
30 | * @param json the JSON
31 | */
32 | public TxnServiceOperation(JsonObject json) {
33 | TxnServiceOperationConverter.fromJson(json, this);
34 | }
35 |
36 | /**
37 | * Convert to JSON
38 | *
39 | * @return the JSON
40 | */
41 | public JsonObject toJson() {
42 | JsonObject jsonObject = new JsonObject();
43 | TxnServiceOperationConverter.toJson(this, jsonObject);
44 | return jsonObject;
45 | }
46 |
47 | /**
48 | * Get the type of operation to perform
49 | *
50 | * @return the type of operation to perform
51 | */
52 | public TxnServiceVerb getType() {
53 | return type;
54 | }
55 |
56 | /**
57 | * Get the node
58 | *
59 | * @return the node name
60 | */
61 | public String getNode() { return node; }
62 |
63 | /**
64 | * Get the service
65 | *
66 | * @return the service
67 | */
68 | public ServiceOptions getServiceOptions() { return serviceOptions; }
69 |
70 | /**
71 | * Set the type of operation to perform
72 | *
73 | * @param type the type of operation to perform
74 | * @return reference to this, for fluency
75 | */
76 | public TxnServiceOperation setType(TxnServiceVerb type) {
77 | this.type = type;
78 | return this;
79 | }
80 |
81 | /**
82 | * Set the node
83 | *
84 | * @param node
85 | * @return reference to this, for fluency
86 | */
87 | public TxnServiceOperation setNode(String node) {
88 | this.node = node;
89 | return this;
90 | }
91 |
92 | /**
93 | * Set the service
94 | *
95 | * @param serviceOptions
96 | * @return reference to this, for fluency
97 | */
98 | public TxnServiceOperation setServiceOptions(ServiceOptions serviceOptions) {
99 | this.serviceOptions = serviceOptions;
100 | return this;
101 | }
102 |
103 | @GenIgnore
104 | @Override
105 | public TxnOperationType getOperationType() {
106 | return TxnOperationType.SERVICE;
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/TxnServiceVerb.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul;
2 |
3 | /**
4 | * Holds the type of Service operation in transaction
5 | */
6 | public enum TxnServiceVerb {
7 |
8 | /**
9 | * Sets the service to the given state
10 | */
11 | SET("set"),
12 |
13 | /**
14 | * Sets, but with CAS semantics using the given ModifyIndex
15 | */
16 | CAS("cas"),
17 |
18 | /**
19 | * Get the service, fails if it does not exist
20 | */
21 | GET("get"),
22 |
23 | /**
24 | * Delete the service
25 | */
26 | DELETE("delete"),
27 |
28 | /**
29 | * Delete, but with CAS semantics
30 | */
31 | DELETE_CAS("delete-cas");
32 |
33 | public static TxnServiceVerb ofVerb(String verb) {
34 | for (TxnServiceVerb type : values()) {
35 | if (type.getVerb().equals(verb)) {
36 | return type;
37 | }
38 | }
39 | return null;
40 | }
41 |
42 | private final String verb;
43 |
44 | TxnServiceVerb(String verb) {
45 | this.verb = verb;
46 | }
47 |
48 | public String getVerb() {
49 | return verb;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/WatchResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul;
17 |
18 | import io.vertx.codegen.annotations.VertxGen;
19 |
20 | @VertxGen
21 | public interface WatchResult {
22 |
23 | /**
24 | * The previous result of the operation.
25 | *
26 | * @return the previous result.
27 | */
28 | T prevResult();
29 |
30 | /**
31 | * The next result of the operation. This will be null if the operation failed.
32 | *
33 | * @return the next result or null if the operation failed.
34 | */
35 | T nextResult();
36 |
37 | /**
38 | * A Throwable describing failure. This will be null if the operation succeeded.
39 | *
40 | * @return the cause or null if the operation succeeded.
41 | */
42 | Throwable cause();
43 |
44 | /**
45 | * Did it succeed?
46 | *
47 | * @return true if it succeded or false otherwise
48 | */
49 | boolean succeeded();
50 |
51 | /**
52 | * Did it fail?
53 | *
54 | * @return true if it failed or false otherwise
55 | */
56 | boolean failed();
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/connect/ConnectOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.connect;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | @DataObject
7 | public class ConnectOptions {
8 | private static final String SIDECAR = "SidecarService";
9 |
10 | private SidecarServiceOptions sidecarService;
11 |
12 | /**
13 | * Default constructor
14 | */
15 | public ConnectOptions() {
16 | }
17 |
18 | /**
19 | * Constructor from JSON
20 | *
21 | * @param options the JSON
22 | */
23 | public ConnectOptions(JsonObject options) {
24 | this.sidecarService = new SidecarServiceOptions(options.getJsonObject(SIDECAR));
25 | }
26 |
27 | /**
28 | * Convert to JSON
29 | *
30 | * @return the JSON
31 | */
32 | public JsonObject toJson() {
33 | JsonObject jsonObject = new JsonObject();
34 | if (sidecarService != null) {
35 | jsonObject.put(SIDECAR, sidecarService.toJson());
36 | }
37 | return jsonObject;
38 | }
39 |
40 | public SidecarServiceOptions getSidecarService() {
41 | return sidecarService;
42 | }
43 |
44 | public ConnectOptions setSidecarService(SidecarServiceOptions sidecarService) {
45 | this.sidecarService = sidecarService;
46 | return this;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/connect/ExposeOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.connect;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | import java.util.List;
7 | import java.util.stream.Collectors;
8 |
9 | @DataObject
10 | public class ExposeOptions {
11 | private static final String PATHS = "Paths";
12 |
13 | private List paths;
14 |
15 | /**
16 | * Default constructor
17 | */
18 | public ExposeOptions() {
19 | }
20 |
21 | /**
22 | * Constructor from JSON
23 | *
24 | * @param options the JSON
25 | */
26 | public ExposeOptions(JsonObject options) {
27 | this.paths = options.getJsonArray(PATHS).stream()
28 | .map(o -> new ExposePathOptions((JsonObject) o))
29 | .collect(Collectors.toList());
30 | }
31 |
32 | /**
33 | * Convert to JSON
34 | *
35 | * @return the JSON
36 | */
37 | public JsonObject toJson() {
38 | JsonObject jsonObject = new JsonObject();
39 | jsonObject.put(PATHS, paths.stream().map(ExposePathOptions::toJson).collect(Collectors.toList()));
40 | return jsonObject;
41 | }
42 |
43 | public List getPaths() {
44 | return paths;
45 | }
46 |
47 | public ExposeOptions setPaths(List paths) {
48 | this.paths = paths;
49 | return this;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/connect/ExposePathOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.connect;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | @DataObject
7 | public class ExposePathOptions {
8 | private static final String PATH = "Path";
9 | private static final String PROTOCOL = "Protocol";
10 | private static final String LOC_PATH = "LocalPathPort";
11 | private static final String LIS_PORT = "ListenerPort";
12 |
13 | private String path;
14 | private String protocol;
15 | private Integer localPathPort;
16 | private Integer listenerPort;
17 |
18 | /**
19 | * Default constructor
20 | */
21 | public ExposePathOptions() {
22 | }
23 |
24 | /**
25 | * Constructor from JSON
26 | *
27 | * @param options the JSON
28 | */
29 | public ExposePathOptions(JsonObject options) {
30 | this.path = options.getString(PATH);
31 | this.protocol = options.getString(PROTOCOL);
32 | this.localPathPort = options.getInteger(LOC_PATH);
33 | this.listenerPort = options.getInteger(LIS_PORT);
34 | }
35 |
36 | /**
37 | * Convert to JSON
38 | *
39 | * @return the JSON
40 | */
41 | public JsonObject toJson() {
42 | JsonObject jsonObject = new JsonObject();
43 | jsonObject.put(PATH, path);
44 | jsonObject.put(PROTOCOL, protocol);
45 | jsonObject.put(LOC_PATH, localPathPort);
46 | jsonObject.put(LIS_PORT, listenerPort);
47 | return jsonObject;
48 | }
49 |
50 | public String getPath() {
51 | return path;
52 | }
53 |
54 | public ExposePathOptions setPath(String path) {
55 | this.path = path;
56 | return this;
57 | }
58 |
59 | public String getProtocol() {
60 | return protocol;
61 | }
62 |
63 | public ExposePathOptions setProtocol(String protocol) {
64 | this.protocol = protocol;
65 | return this;
66 | }
67 |
68 | public Integer getLocalPathPort() {
69 | return localPathPort;
70 | }
71 |
72 | public ExposePathOptions setLocalPathPort(Integer localPathPort) {
73 | this.localPathPort = localPathPort;
74 | return this;
75 | }
76 |
77 | public Integer getListenerPort() {
78 | return listenerPort;
79 | }
80 |
81 | public ExposePathOptions setListenerPort(Integer listenerPort) {
82 | this.listenerPort = listenerPort;
83 | return this;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/connect/ProxyOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.connect;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | import java.util.List;
7 | import java.util.stream.Collectors;
8 |
9 | @DataObject
10 | public class ProxyOptions {
11 | private static final String CONFIG = "Config";
12 | private static final String UPSTREAMS = "Upstreams";
13 | private static final String EXPOSE = "Expose";
14 |
15 | private JsonObject config;
16 | private List upstreams;
17 | private ExposeOptions expose;
18 |
19 | /**
20 | * Default constructor
21 | */
22 | public ProxyOptions() {
23 | }
24 |
25 | /**
26 | * Constructor from JSON
27 | *
28 | * @param options the JSON
29 | */
30 | public ProxyOptions(JsonObject options) {
31 | this.config = options.getJsonObject(CONFIG);
32 | this.upstreams = options.getJsonArray(UPSTREAMS).stream()
33 | .map(o -> new UpstreamOptions((JsonObject) o))
34 | .collect(Collectors.toList());
35 | this.expose = new ExposeOptions(options.getJsonObject(EXPOSE));
36 | }
37 |
38 | /**
39 | * Convert to JSON
40 | *
41 | * @return the JSON
42 | */
43 | public JsonObject toJson() {
44 | JsonObject jsonObject = new JsonObject();
45 | if (upstreams != null) {
46 | jsonObject.put(UPSTREAMS, upstreams.stream().map(UpstreamOptions::toJson).collect(Collectors.toList()));
47 | }
48 | if (config != null) {
49 | jsonObject.put(CONFIG, config);
50 | }
51 | if (expose != null) {
52 | jsonObject.put(EXPOSE, expose.toJson());
53 | }
54 | return jsonObject;
55 | }
56 |
57 | public JsonObject getConfig() {
58 | return config;
59 | }
60 |
61 | public ProxyOptions setConfig(JsonObject config) {
62 | this.config = config;
63 | return this;
64 | }
65 |
66 | public List getUpstreams() {
67 | return upstreams;
68 | }
69 |
70 | public ProxyOptions setUpstreams(List upstreams) {
71 | this.upstreams = upstreams;
72 | return this;
73 | }
74 |
75 | public ExposeOptions getExpose() {
76 | return expose;
77 | }
78 |
79 | public ProxyOptions setExpose(ExposeOptions expose) {
80 | this.expose = expose;
81 | return this;
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/connect/SidecarServiceOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.connect;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | import java.util.List;
7 | import java.util.stream.Collectors;
8 |
9 | @DataObject
10 | public class SidecarServiceOptions {
11 | private static final String PROXY = "Proxy";
12 | private static final String PORT = "Port";
13 | private static final String CHECKS = "Checks";
14 |
15 | private ProxyOptions proxy;
16 | private int port;
17 | private List checks;
18 |
19 | /**
20 | * Default constructor
21 | */
22 | public SidecarServiceOptions() {
23 | }
24 |
25 | /**
26 | * Constructor from JSON
27 | *
28 | * @param options the JSON
29 | */
30 | public SidecarServiceOptions(JsonObject options) {
31 | this.proxy = new ProxyOptions(options.getJsonObject(PROXY));
32 | this.port = options.getInteger(PORT);
33 | this.checks = options.getJsonArray(CHECKS).stream()
34 | .map(o -> (JsonObject) o)
35 | .collect(Collectors.toList());
36 | }
37 |
38 | /**
39 | * Convert to JSON
40 | *
41 | * @return the JSON
42 | */
43 | public JsonObject toJson() {
44 | JsonObject jsonObject = new JsonObject();
45 | jsonObject.put(PORT, port);
46 | if (proxy != null) {
47 | jsonObject.put(PROXY, proxy.toJson());
48 | }
49 | if (checks != null) {
50 | jsonObject.put(CHECKS, checks);
51 | }
52 | return jsonObject;
53 | }
54 |
55 | public int getPort() {
56 | return port;
57 | }
58 |
59 | public SidecarServiceOptions setPort(int port) {
60 | this.port = port;
61 | return this;
62 | }
63 |
64 | public ProxyOptions getProxy() {
65 | return proxy;
66 | }
67 |
68 | public SidecarServiceOptions setProxy(ProxyOptions proxy) {
69 | this.proxy = proxy;
70 | return this;
71 | }
72 |
73 | public List getChecks() {
74 | return checks;
75 | }
76 |
77 | public void setChecks(List checks) {
78 | this.checks = checks;
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/connect/UpstreamOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.connect;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | @DataObject
7 | public class UpstreamOptions {
8 | private static final String DC = "Datacenter";
9 | private static final String DEST_NAME = "DestinationName";
10 | private static final String LOCAL_PORT = "LocalBindPort";
11 |
12 | private String destinationName;
13 | private String dc;
14 | private int localBindPort;
15 |
16 | /**
17 | * Default constructor
18 | */
19 | public UpstreamOptions() {
20 | }
21 |
22 | /**
23 | * Constructor from JSON
24 | *
25 | * @param options the JSON
26 | */
27 | public UpstreamOptions(JsonObject options) {
28 | this.destinationName = options.getString(DEST_NAME);
29 | this.localBindPort = options.getInteger(LOCAL_PORT);
30 | this.dc = options.getString(DC);
31 | }
32 |
33 | /**
34 | * Convert to JSON
35 | *
36 | * @return the JSON
37 | */
38 | public JsonObject toJson() {
39 | JsonObject jsonObject = new JsonObject();
40 | if (destinationName != null) {
41 | jsonObject.put(DEST_NAME, destinationName);
42 | }
43 | jsonObject.put(LOCAL_PORT, localBindPort);
44 | if (dc != null) {
45 | jsonObject.put(DC, dc);
46 | }
47 | return jsonObject;
48 | }
49 |
50 | public String getDestinationName() {
51 | return destinationName;
52 | }
53 |
54 | public UpstreamOptions setDestinationName(String destinationName) {
55 | this.destinationName = destinationName;
56 | return this;
57 | }
58 |
59 | public String getDc() {
60 | return dc;
61 | }
62 |
63 | public UpstreamOptions setDc(String dc) {
64 | this.dc = dc;
65 | return this;
66 | }
67 |
68 | public int getLocalBindPort() {
69 | return localBindPort;
70 | }
71 |
72 | public UpstreamOptions setLocalBindPort(int localBindPort) {
73 | this.localBindPort = localBindPort;
74 | return this;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/CheckParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonObject;
19 | import io.vertx.ext.consul.Check;
20 | import io.vertx.ext.consul.CheckStatus;
21 |
22 | /**
23 | * @author Ruslan Sennov
24 | */
25 | class CheckParser {
26 |
27 | private static final String SERVICE_ID_KEY = "ServiceID";
28 | private static final String SERVICE_NAME_KEY = "ServiceName";
29 | private static final String ID_KEY = "CheckID";
30 | private static final String NAME_KEY = "Name";
31 | private static final String NODE_KEY = "Node";
32 | private static final String STATUS_KEY = "Status";
33 | private static final String NOTES_KEY = "Notes";
34 | private static final String OUTPUT_KEY = "Output";
35 |
36 | static Check parse(JsonObject check) {
37 | return new Check()
38 | .setId(check.getString(ID_KEY))
39 | .setName(check.getString(NAME_KEY))
40 | .setStatus(CheckStatus.of(check.getString(STATUS_KEY)))
41 | .setNotes(check.getString(NOTES_KEY))
42 | .setOutput(check.getString(OUTPUT_KEY))
43 | .setServiceId(check.getString(SERVICE_ID_KEY))
44 | .setServiceName(check.getString(SERVICE_NAME_KEY));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/CoordinateParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonArray;
19 | import io.vertx.core.json.JsonObject;
20 | import io.vertx.ext.consul.Coordinate;
21 | import io.vertx.ext.consul.DcCoordinates;
22 |
23 | import java.util.stream.Collectors;
24 |
25 | /**
26 | * @author Ruslan Sennov
27 | */
28 | class CoordinateParser {
29 |
30 | private static final String NODE_KEY = "Node";
31 | private static final String COORD_KEY = "Coord";
32 | private static final String ADJ_KEY = "Adjustment";
33 | private static final String ERR_KEY = "Error";
34 | private static final String HEIGHT_KEY = "Height";
35 | private static final String VEC_KEY = "Vec";
36 |
37 | private static final String DATACENTER_KEY = "Datacenter";
38 | private static final String COORDS_KEY = "Coordinates";
39 |
40 | static Coordinate parse(JsonObject json) {
41 | Coordinate coordinate = new Coordinate()
42 | .setNode(json.getString(NODE_KEY));
43 | JsonObject coord = json.getJsonObject(COORD_KEY);
44 | if (coord != null) {
45 | coordinate
46 | .setAdj(coord.getFloat(ADJ_KEY, 0f))
47 | .setErr(coord.getFloat(ERR_KEY, 0f))
48 | .setHeight(coord.getFloat(HEIGHT_KEY, 0f));
49 | JsonArray arr = coord.getJsonArray(VEC_KEY);
50 | coordinate.setVec(arr == null ? null : arr.stream()
51 | .map(o -> o instanceof Number ? ((Number) o).floatValue() : 0f)
52 | .collect(Collectors.toList()));
53 | }
54 | return coordinate;
55 | }
56 |
57 | static DcCoordinates parseDc(JsonObject json) {
58 | return new DcCoordinates()
59 | .setDatacenter(json.getString(DATACENTER_KEY))
60 | .setServers(json.getJsonArray(COORDS_KEY).stream()
61 | .map(obj -> parse((JsonObject) obj))
62 | .collect(Collectors.toList()));
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/EventParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonObject;
19 | import io.vertx.ext.consul.Event;
20 |
21 | import java.util.Base64;
22 |
23 | /**
24 | * @author Ruslan Sennov
25 | */
26 | class EventParser {
27 |
28 | private static final String ID_KEY = "ID";
29 | private static final String NAME_KEY = "Name";
30 | private static final String PAYLOAD_KEY = "Payload";
31 | private static final String NODE_FILTER_KEY = "NodeFilter";
32 | private static final String SERVICE_FILTER_KEY = "ServiceFilter";
33 | private static final String TAG_FILTER_KEY = "TagFilter";
34 | private static final String VERSION_KEY = "Version";
35 | private static final String LTIME_KEY = "LTime";
36 |
37 | static Event parse(JsonObject json) {
38 | Event ev = new Event()
39 | .setId(json.getString(ID_KEY))
40 | .setName(json.getString(NAME_KEY))
41 | .setNode(json.getString(NODE_FILTER_KEY))
42 | .setService(json.getString(SERVICE_FILTER_KEY))
43 | .setTag(json.getString(TAG_FILTER_KEY))
44 | .setVersion(json.getInteger(VERSION_KEY, 0))
45 | .setLTime(json.getInteger(LTIME_KEY, 0));
46 | String payload = json.getString(PAYLOAD_KEY);
47 | if (payload != null) {
48 | ev.setPayload(Utils.decode64(payload));
49 | }
50 | return ev;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/KVParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonObject;
19 | import io.vertx.ext.consul.KeyValue;
20 |
21 | import java.util.Base64;
22 |
23 | /**
24 | * @author Ruslan Sennov
25 | */
26 | class KVParser {
27 |
28 | private static final String KEY_KEY = "Key";
29 | private static final String VALUE_KEY = "Value";
30 | private static final String SESSION_KEY = "Session";
31 | private static final String FLAGS_KEY = "Flags";
32 | private static final String CREATE_KEY = "CreateIndex";
33 | private static final String MODIFY_KEY = "ModifyIndex";
34 | private static final String LOCK_KEY = "LockIndex";
35 |
36 | static KeyValue parse(JsonObject json) {
37 | return new KeyValue()
38 | .setKey(json.getString(KEY_KEY))
39 | .setValue(Utils.decode64(json.getString(VALUE_KEY)))
40 | .setSession(json.getString(SESSION_KEY))
41 | .setFlags(json.getLong(FLAGS_KEY, 0L))
42 | .setCreateIndex(json.getLong(CREATE_KEY, 0L))
43 | .setModifyIndex(json.getLong(MODIFY_KEY, 0L))
44 | .setLockIndex(json.getLong(LOCK_KEY, 0L));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/NodeListParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonArray;
19 | import io.vertx.core.json.JsonObject;
20 | import io.vertx.ext.consul.Node;
21 | import io.vertx.ext.consul.NodeList;
22 |
23 | import java.util.stream.Collectors;
24 |
25 | /**
26 | * @author Ruslan Sennov
27 | */
28 | class NodeListParser {
29 |
30 | private static final String INDEX_KEY = "Index";
31 | private static final String LIST_KEY = "List";
32 |
33 | static NodeList parse(JsonObject json) {
34 | return new NodeList()
35 | .setIndex(json.getLong(INDEX_KEY, 0L))
36 | .setList(json.getJsonArray(LIST_KEY, new JsonArray()).stream()
37 | .map(obj -> new Node((JsonObject) obj)).collect(Collectors.toList()));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/NodeParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonObject;
19 | import io.vertx.ext.consul.Node;
20 |
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 | /**
25 | * @author Ruslan Sennov
26 | */
27 | class NodeParser {
28 |
29 | private static final String NODE_KEY = "Node";
30 | private static final String ADDRESS_KEY = "Address";
31 | private static final String TAGGED_ADDRESSES_KEY = "TaggedAddresses";
32 | private static final String LAN_KEY = "lan";
33 | private static final String WAN_KEY = "wan";
34 | private static final String ID_KEY = "ID";
35 | private static final String DATACENTER_KEY = "Datacenter";
36 | private static final String META_KEY = "Meta";
37 |
38 | static Node parse(JsonObject json) {
39 | Node node = new Node()
40 | .setId(json.getString(ID_KEY))
41 | .setName(json.getString(NODE_KEY))
42 | .setAddress(json.getString(ADDRESS_KEY))
43 | .setDatacenter(json.getString(DATACENTER_KEY));
44 | JsonObject tagged = json.getJsonObject(TAGGED_ADDRESSES_KEY);
45 | if (tagged != null) {
46 | node.setLanAddress(tagged.getString(LAN_KEY)).setWanAddress(tagged.getString(WAN_KEY));
47 | }
48 |
49 | Map metaMap = mapOfStringsFromJsonObject(json.getJsonObject(META_KEY));
50 | if (!metaMap.isEmpty()) {
51 | node.setNodeMeta(metaMap);
52 | }
53 |
54 | return node;
55 | }
56 |
57 | private static Map mapOfStringsFromJsonObject(JsonObject jsonObject) {
58 | Map result = new HashMap<>();
59 | if (jsonObject != null) {
60 | Map map = jsonObject.getMap();
61 | if (!map.isEmpty()) {
62 | for (Map.Entry entry : map.entrySet()) {
63 | if (entry.getValue() instanceof String) {
64 | result.put(entry.getKey(), (String) entry.getValue());
65 | }
66 | }
67 | }
68 | }
69 | return result;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/Query.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.buffer.Buffer;
19 | import io.vertx.ext.consul.BlockingQueryOptions;
20 | import io.vertx.ext.web.client.HttpRequest;
21 |
22 | import java.util.HashMap;
23 | import java.util.Map;
24 | import java.util.Set;
25 |
26 | /**
27 | * @author Ruslan Sennov
28 | */
29 | class Query {
30 |
31 | private final Map map = new HashMap<>();
32 |
33 | static Query of(BlockingQueryOptions options) {
34 | return new Query().put(options);
35 | }
36 |
37 | static Query of(String key, Object value) {
38 | return new Query().put(key, value);
39 | }
40 |
41 | Query put(String key, Object value) {
42 | if (value == null) {
43 | return this;
44 | }
45 | String str = value.toString();
46 | if (!str.isEmpty()) {
47 | map.put(key, str);
48 | }
49 | return this;
50 | }
51 |
52 | Query put(BlockingQueryOptions options) {
53 | if (options != null) {
54 | put("index", Long.toUnsignedString(options.getIndex()));
55 | if (options.getWait() != null) {
56 | put("wait", options.getWait());
57 | }
58 | }
59 | return this;
60 | }
61 |
62 | Set> entrySet() {
63 | return map.entrySet();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/ServiceEntryParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonObject;
19 | import io.vertx.ext.consul.ServiceEntry;
20 |
21 | import java.util.stream.Collectors;
22 |
23 | /**
24 | * @author Ruslan Sennov
25 | */
26 | class ServiceEntryParser {
27 |
28 | private static final String NODE_KEY = "Node";
29 | private static final String SERVICE_KEY = "Service";
30 | private static final String CHECKS_KEY = "Checks";
31 |
32 | static ServiceEntry parse(JsonObject json) {
33 | return new ServiceEntry()
34 | .setNode(NodeParser.parse(json.getJsonObject(NODE_KEY)))
35 | .setService(ServiceParser.parseAgentInfo(json.getJsonObject(SERVICE_KEY)))
36 | .setChecks(json.getJsonArray(CHECKS_KEY).stream().map(obj -> CheckParser.parse((JsonObject) obj)).collect(Collectors.toList()));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/ServiceParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonArray;
19 | import io.vertx.core.json.JsonObject;
20 | import io.vertx.ext.consul.Service;
21 |
22 | import java.util.Map;
23 | import java.util.stream.Collectors;
24 |
25 | import static io.vertx.ext.consul.impl.Utils.listOf;
26 | import static io.vertx.ext.consul.impl.Utils.mapStringString;
27 |
28 | /**
29 | * @author Ruslan Sennov
30 | */
31 | class ServiceParser {
32 |
33 | private static final String AGENT_SERVICE_ID = "ID";
34 | private static final String AGENT_SERVICE_SERVICE = "Service";
35 | private static final String AGENT_SERVICE_TAGS = "Tags";
36 | private static final String AGENT_SERVICE_ADDRESS = "Address";
37 | private static final String AGENT_SERVICE_META = "Meta";
38 | private static final String AGENT_SERVICE_PORT = "Port";
39 |
40 | static Service parseAgentInfo(JsonObject jsonObject) {
41 | JsonArray tagsArr = jsonObject.getJsonArray(AGENT_SERVICE_TAGS);
42 | return new Service()
43 | .setId(jsonObject.getString(AGENT_SERVICE_ID))
44 | .setName(jsonObject.getString(AGENT_SERVICE_SERVICE))
45 | .setTags(listOf(tagsArr))
46 | .setMeta(mapStringString(jsonObject.getJsonObject(AGENT_SERVICE_META)))
47 | .setAddress(jsonObject.getString(AGENT_SERVICE_ADDRESS))
48 | .setPort(jsonObject.getInteger(AGENT_SERVICE_PORT, 0));
49 | }
50 |
51 | static Service parseCatalogInfo(Map.Entry entry) {
52 | Object tags = entry.getValue();
53 | return new Service()
54 | .setName(entry.getKey())
55 | .setTags(((JsonArray) tags).stream().map(o -> (String) o).collect(Collectors.toList()));
56 | }
57 |
58 | static Service parseNodeInfo(String nodeName, String nodeAddress, JsonObject serviceInfo) {
59 | JsonArray tagsArr = serviceInfo.getJsonArray(AGENT_SERVICE_TAGS);
60 | return new Service()
61 | .setNode(nodeName)
62 | .setNodeAddress(nodeAddress)
63 | .setId(serviceInfo.getString(AGENT_SERVICE_ID))
64 | .setAddress(serviceInfo.getString(AGENT_SERVICE_ADDRESS))
65 | .setMeta(mapStringString(serviceInfo.getJsonObject(AGENT_SERVICE_META)))
66 | .setName(serviceInfo.getString(AGENT_SERVICE_SERVICE))
67 | .setTags(listOf(tagsArr))
68 | .setPort(serviceInfo.getInteger(AGENT_SERVICE_PORT));
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/SessionParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonArray;
19 | import io.vertx.core.json.JsonObject;
20 | import io.vertx.ext.consul.Session;
21 |
22 | import java.util.concurrent.TimeUnit;
23 |
24 | import static io.vertx.ext.consul.impl.Utils.listOf;
25 |
26 | /**
27 | * @author Ruslan Sennov
28 | */
29 | class SessionParser {
30 |
31 | private static final String LOCK_KEY = "LockDelay";
32 | private static final String NODE_KEY = "Node";
33 | private static final String CHECKS_KEY = "Checks";
34 | private static final String ID_KEY = "ID";
35 | private static final String CREATE_INDEX_KEY = "CreateIndex";
36 |
37 | static Session parse(JsonObject session) {
38 | return parse(session, 0);
39 | }
40 |
41 | static Session parse(JsonObject session, long index) {
42 | Session res = new Session();
43 | res.setLockDelay(TimeUnit.NANOSECONDS.toSeconds(session.getLong(LOCK_KEY, 0L)));
44 | res.setNode(session.getString(NODE_KEY));
45 | res.setId(session.getString(ID_KEY));
46 | res.setCreateIndex(session.getLong(CREATE_INDEX_KEY, 0L));
47 | JsonArray arr = session.getJsonArray(CHECKS_KEY);
48 | res.setChecks(listOf(arr));
49 | res.setIndex(index);
50 | return res;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/TxnResponseParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonArray;
19 | import io.vertx.core.json.JsonObject;
20 | import io.vertx.ext.consul.TxnError;
21 | import io.vertx.ext.consul.TxnResponse;
22 |
23 | /**
24 | * @author Ruslan Sennov
25 | */
26 | class TxnResponseParser {
27 |
28 | static TxnResponse parse(JsonObject json) {
29 | TxnResponse response = new TxnResponse();
30 | if (json.getValue("Results") instanceof JsonArray) {
31 | json.getJsonArray("Results").forEach(entry -> {
32 | JsonObject obj = (JsonObject) entry;
33 | if (obj.containsKey("KV")) {
34 | response.addResult(KVParser.parse(obj.getJsonObject("KV")));
35 | }
36 | else if (obj.containsKey("Service")) {
37 | response.addResult(ServiceParser.parseAgentInfo(obj.getJsonObject("Service")));
38 | }
39 | });
40 | }
41 | if (json.getValue("Errors") instanceof JsonArray) {
42 | json.getJsonArray("Errors").forEach(entry -> {
43 | JsonObject obj = (JsonObject) entry;
44 | response.addError(new TxnError()
45 | .setOpIndex(obj.getInteger("OpIndex"))
46 | .setWhat(obj.getString("What")));
47 | });
48 | }
49 | return response;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/impl/Utils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.impl;
17 |
18 | import io.vertx.core.json.JsonArray;
19 | import io.vertx.core.json.JsonObject;
20 | import io.vertx.ext.consul.CheckStatus;
21 |
22 | import java.io.UnsupportedEncodingException;
23 | import java.net.URLEncoder;
24 | import java.util.*;
25 |
26 | /**
27 | * @author Ruslan Sennov
28 | */
29 | public class Utils {
30 |
31 | public static CheckStatus aggregateCheckStatus(List checks) {
32 | boolean warning = false, critical = false;
33 | for (CheckStatus status: checks) {
34 | switch (status) {
35 | case WARNING:
36 | warning = true;
37 | break;
38 | case CRITICAL:
39 | critical = true;
40 | break;
41 | }
42 | }
43 | if (critical) {
44 | return CheckStatus.CRITICAL;
45 | } else if (warning) {
46 | return CheckStatus.WARNING;
47 | } else {
48 | return CheckStatus.PASSING;
49 | }
50 | }
51 |
52 | public static String urlEncode(String str) {
53 | try {
54 | return URLEncoder.encode(str, "UTF-8");
55 | } catch (UnsupportedEncodingException ignore) {
56 | }
57 | return "";
58 | }
59 |
60 | public static String encode64(String src) {
61 | if (src == null || src.isEmpty()) {
62 | return "";
63 | } else {
64 | return new String(Base64.getEncoder().encode(src.getBytes()));
65 | }
66 | }
67 |
68 | public static String decode64(String src) {
69 | if (src == null || src.isEmpty()) {
70 | return "";
71 | } else {
72 | return new String(Base64.getDecoder().decode(src));
73 | }
74 | }
75 |
76 | public static List listOf(List list) {
77 | if (list == null) {
78 | return null;
79 | } else {
80 | return new ArrayList<>(list);
81 | }
82 | }
83 |
84 | @SuppressWarnings("unchecked")
85 | public static Map mapStringString(JsonObject obj) {
86 | if (obj == null) {
87 | return null;
88 | } else {
89 | Map map = new HashMap<>();
90 | obj.getMap().forEach((k, v) -> map.put(k, (String) v));
91 | return map;
92 | }
93 | }
94 |
95 | @SuppressWarnings("unchecked")
96 | public static List listOf(JsonArray arr) {
97 | if (arr == null) {
98 | return null;
99 | } else {
100 | return (List) arr.getList();
101 | }
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/package-info.java:
--------------------------------------------------------------------------------
1 | @ModuleGen(name = "vertx-consul", groupPackage = "io.vertx")
2 | package io.vertx.ext.consul;
3 |
4 | import io.vertx.codegen.annotations.ModuleGen;
5 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/token/CloneAclTokenOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.token;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | @DataObject
7 | public class CloneAclTokenOptions {
8 | private static final String DESCRIPTION_KEY = "Description";
9 | private static final String NAMESPACE_KEY = "Namespace";
10 | /**
11 | * Description for the cloned token
12 | */
13 | private String description;
14 | private String namespace;
15 |
16 | public CloneAclTokenOptions() {
17 | }
18 |
19 | public CloneAclTokenOptions(JsonObject json){
20 | this.description = json.getString(DESCRIPTION_KEY);
21 | this.namespace = json.getString(NAMESPACE_KEY);
22 | }
23 |
24 | public JsonObject toJson() {
25 | JsonObject json = new JsonObject();
26 | if (description != null) {
27 | json.put(DESCRIPTION_KEY, description);
28 | }
29 | if (namespace != null) {
30 | json.put(NAMESPACE_KEY, namespace);
31 | }
32 | return json;
33 | }
34 |
35 | /**
36 | * Sets an optional description
37 | *
38 | * @param description Free form human-readable description
39 | */
40 | public CloneAclTokenOptions setDescription(String description) {
41 | this.description = description;
42 | return this;
43 | }
44 |
45 | /**
46 | * Sets an optional namespace
47 | * Default value is ns URL query parameter or in the X-Consul-Namespace header, or 'default' namespace.
48 | *
49 | * @param namespace
50 | */
51 | public CloneAclTokenOptions setNamespace(String namespace) {
52 | this.namespace = namespace;
53 | return this;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/token/NodeTokenApplyingOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.token;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonArray;
5 | import io.vertx.core.json.JsonObject;
6 |
7 | import java.util.ArrayList;
8 |
9 | @DataObject
10 | public class NodeTokenApplyingOptions extends TokenApplyingOptions {
11 | private static final String NODE_NAME_KEY = "NodeName";
12 |
13 | public NodeTokenApplyingOptions(JsonObject json) {
14 | this.name = json.getString(NODE_NAME_KEY);
15 | JsonArray datacenters = json.getJsonArray(DATACENTERS_KEY);
16 | if (datacenters != null && !datacenters.isEmpty()) {
17 | this.datacenters = new ArrayList<>();
18 | for (int i = 1; i < datacenters.size(); i++) {
19 | this.datacenters.add(datacenters.getString(i));
20 | }
21 | }
22 | }
23 |
24 | @Override
25 | public JsonObject toJson() {
26 | JsonObject json = super.toJson();
27 | if (name != null) {
28 | json.put(NODE_NAME_KEY, name);
29 | }
30 | return json;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/token/PolicyLink.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.token;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | /**
7 | * It is an object with an "ID" and/or "Name" field to specify a policy
8 | */
9 | @DataObject
10 | public class PolicyLink {
11 | private static final String ID_KEY = "ID";
12 | private static final String NAME_KEY = "Name";
13 | /**
14 | * Policy ID
15 | */
16 | private String id;
17 | /**
18 | * Policy name
19 | */
20 | private String name;
21 |
22 | public PolicyLink() {
23 | }
24 |
25 | public PolicyLink(JsonObject json) {
26 | this.id = json.getString(ID_KEY);
27 | this.name = json.getString(NAME_KEY);
28 | }
29 |
30 | public JsonObject toJson() {
31 | JsonObject json = new JsonObject();
32 | if (id != null) {
33 | json.put(ID_KEY, id);
34 | }
35 | if (name != null) {
36 | json.put(NAME_KEY, name);
37 | }
38 | return json;
39 | }
40 |
41 | /**
42 | * Sets a policy id
43 | *
44 | * @param id uuid
45 | */
46 | public PolicyLink setId(String id) {
47 | PolicyLink.this.id = id;
48 | return this;
49 | }
50 |
51 | /**
52 | * Sets a policy name
53 | *
54 | * @param name
55 | */
56 | public PolicyLink setName(String name) {
57 | PolicyLink.this.name = name;
58 | return this;
59 | }
60 |
61 | public String getId() {
62 | return id;
63 | }
64 |
65 | public String getName() {
66 | return name;
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/token/ServiceTokenApplyingOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.token;
2 |
3 | import io.vertx.codegen.annotations.DataObject;
4 | import io.vertx.core.json.JsonArray;
5 | import io.vertx.core.json.JsonObject;
6 |
7 | import java.util.ArrayList;
8 |
9 | @DataObject
10 | public class ServiceTokenApplyingOptions extends TokenApplyingOptions {
11 | private static final String SERVICE_NAME_KEY = "ServiceName";
12 |
13 | public ServiceTokenApplyingOptions(JsonObject json) {
14 | this.name = json.getString(SERVICE_NAME_KEY);
15 | JsonArray datacenters = json.getJsonArray(DATACENTERS_KEY);
16 | if (datacenters != null && !datacenters.isEmpty()) {
17 | this.datacenters = new ArrayList<>();
18 | for (int i = 1; i < datacenters.size(); i++) {
19 | this.datacenters.add(datacenters.getString(i));
20 | }
21 | }
22 | }
23 |
24 | @Override
25 | public JsonObject toJson() {
26 | JsonObject json = super.toJson();
27 | if (name != null) {
28 | json.put(SERVICE_NAME_KEY, name);
29 | }
30 | return json;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/io/vertx/ext/consul/token/TokenApplyingOptions.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.token;
2 |
3 | import io.vertx.core.json.JsonArray;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | public abstract class TokenApplyingOptions {
10 | protected static final String DATACENTERS_KEY = "Datacenters";
11 |
12 | /**
13 | * The name of the service/node
14 | */
15 | protected String name;
16 | /**
17 | * Specifies the datacenters the policy is valid within
18 | */
19 | protected List datacenters;
20 |
21 | public TokenApplyingOptions() {
22 |
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | /**
30 | * Sets a name
31 | *
32 | * @param name - must be no longer than 256 characters, must start and end with a lowercase alphanumeric character,
33 | * and can only contain lowercase alphanumeric characters as well as '-' and '_'.
34 | */
35 | public TokenApplyingOptions setName(String name) {
36 | this.name = name;
37 | return this;
38 | }
39 |
40 | public List getDatacenters() {
41 | return datacenters;
42 | }
43 |
44 | /**
45 | * Sets an optional datacenters. By default, the policy is valid in all datacenters
46 | *
47 | * @param datacenters list of datacenters
48 | * @see #datacenters
49 | */
50 | public TokenApplyingOptions setDatacenters(List datacenters) {
51 | this.datacenters = datacenters;
52 | return this;
53 | }
54 |
55 | /**
56 | * Adds a datacenter, like {@link #setDatacenters(List)}
57 | *
58 | * @see #datacenters
59 | */
60 | public TokenApplyingOptions addDatacenter(String datacenter) {
61 | if (datacenters == null) {
62 | datacenters = new ArrayList<>();
63 | }
64 | datacenters.add(datacenter);
65 | return this;
66 | }
67 |
68 | public JsonObject toJson() {
69 | JsonObject json = new JsonObject();
70 | if (datacenters != null && !datacenters.isEmpty()) {
71 | JsonArray array = new JsonArray(datacenters);
72 | json.put(DATACENTERS_KEY, array);
73 | }
74 | return json;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/module-info.java:
--------------------------------------------------------------------------------
1 | module io.vertx.consul.client {
2 |
3 | requires static io.vertx.docgen;
4 | requires static io.vertx.codegen.api;
5 | requires static io.vertx.codegen.json;
6 |
7 | requires io.netty.codec.http;
8 | requires io.vertx.core;
9 | requires io.vertx.web.client;
10 |
11 | exports io.vertx.ext.consul;
12 | exports io.vertx.ext.consul.connect;
13 | exports io.vertx.ext.consul.policy;
14 | exports io.vertx.ext.consul.token;
15 |
16 | exports io.vertx.ext.consul.impl to io.vertx.consul.client.tests;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/AggregateStatusTest.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests;
2 |
3 | import io.vertx.ext.consul.Check;
4 | import io.vertx.ext.consul.CheckStatus;
5 | import io.vertx.ext.consul.ServiceEntry;
6 | import org.junit.Assert;
7 | import org.junit.Test;
8 |
9 | import java.util.Arrays;
10 | import java.util.Collections;
11 |
12 | import static io.vertx.ext.consul.impl.Utils.aggregateCheckStatus;
13 | import static org.junit.Assert.assertEquals;
14 |
15 | public class AggregateStatusTest {
16 |
17 | @Test
18 | public void ofEmpty() {
19 | Assert.assertEquals(aggregateCheckStatus(Collections.emptyList()), CheckStatus.PASSING);
20 | }
21 |
22 | @Test
23 | public void ofSingletonList() {
24 | assertEquals(aggregateCheckStatus(Collections.singletonList(CheckStatus.PASSING)), CheckStatus.PASSING);
25 | assertEquals(aggregateCheckStatus(Collections.singletonList(CheckStatus.WARNING)), CheckStatus.WARNING);
26 | assertEquals(aggregateCheckStatus(Collections.singletonList(CheckStatus.CRITICAL)), CheckStatus.CRITICAL);
27 | }
28 |
29 | @Test
30 | public void critical() {
31 | assertEquals(aggregateCheckStatus(Arrays.asList(CheckStatus.CRITICAL, CheckStatus.CRITICAL)), CheckStatus.CRITICAL);
32 | assertEquals(aggregateCheckStatus(Arrays.asList(CheckStatus.CRITICAL, CheckStatus.PASSING)), CheckStatus.CRITICAL);
33 | assertEquals(aggregateCheckStatus(Arrays.asList(CheckStatus.WARNING, CheckStatus.CRITICAL, CheckStatus.PASSING)), CheckStatus.CRITICAL);
34 | assertEquals(aggregateCheckStatus(Arrays.asList(CheckStatus.WARNING, CheckStatus.CRITICAL)), CheckStatus.CRITICAL);
35 | }
36 |
37 | @Test
38 | public void warning() {
39 | assertEquals(aggregateCheckStatus(Arrays.asList(CheckStatus.WARNING, CheckStatus.PASSING)), CheckStatus.WARNING);
40 | assertEquals(aggregateCheckStatus(Arrays.asList(CheckStatus.WARNING, CheckStatus.WARNING)), CheckStatus.WARNING);
41 | }
42 |
43 | @Test
44 | public void passing() {
45 | assertEquals(aggregateCheckStatus(Arrays.asList(CheckStatus.PASSING, CheckStatus.PASSING)), CheckStatus.PASSING);
46 | }
47 |
48 | @Test
49 | public void entry() {
50 | ServiceEntry entry = new ServiceEntry().setChecks(Arrays.asList(
51 | new Check().setStatus(CheckStatus.WARNING),
52 | new Check().setStatus(CheckStatus.PASSING)
53 | ));
54 | assertEquals(entry.aggregatedStatus(), CheckStatus.WARNING);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/ConnectOptionsTest.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests;
2 |
3 | import io.vertx.core.json.JsonObject;
4 | import io.vertx.ext.consul.connect.*;
5 | import org.junit.Test;
6 |
7 | import static org.junit.Assert.assertEquals;
8 |
9 | public class ConnectOptionsTest {
10 |
11 | @Test
12 | public void parse() throws Exception {
13 | JsonObject src = new JsonObject(Utils.readResource("connect_example.json"));
14 | SidecarServiceOptions scOpts = new ConnectOptions(src).getSidecarService();
15 | assertEquals(33333, scOpts.getPort());
16 | ProxyOptions proxyOptions = scOpts.getProxy();
17 | assertEquals(1, proxyOptions.getUpstreams().size());
18 | UpstreamOptions upstream = proxyOptions.getUpstreams().get(0);
19 | assertEquals("dev-mesh-database-service", upstream.getDestinationName());
20 | assertEquals(19102, upstream.getLocalBindPort());
21 | assertEquals("dc-v5", upstream.getDc());
22 | JsonObject config = proxyOptions.getConfig();
23 | assertEquals("envoy_local_cluster_json1", config.getString("envoy_local_cluster_json"));
24 | assertEquals("envoy_local_cluster_json2", config.getString("envoy_public_listener_json"));
25 | assertEquals("0.0.0.0:19500", config.getString("envoy_prometheus_bind_addr"));
26 | assertEquals("envoy_local_cluster_json3", config.getString("envoy_extra_static_clusters_json"));
27 | ExposeOptions expOptions = proxyOptions.getExpose();
28 | assertEquals(1, expOptions.getPaths().size());
29 | ExposePathOptions path = expOptions.getPaths().get(0);
30 | assertEquals("/metrics", path.getPath());
31 | assertEquals("http", path.getProtocol());
32 | assertEquals((Integer) 53000, path.getLocalPathPort());
33 | assertEquals((Integer) 19600, path.getListenerPort());
34 | }
35 |
36 | @Test
37 | public void convert() throws Exception {
38 | JsonObject src = new JsonObject(Utils.readResource("connect_example.json"));
39 | ConnectOptions options = new ConnectOptions(src);
40 | JsonObject act = new JsonObject(options.toJson().encode());
41 | assertEquals(src, act);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/ConsulClientTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests;
17 |
18 | import io.vertx.ext.consul.tests.suite.*;
19 | import org.junit.runner.RunWith;
20 | import org.junit.runners.Suite;
21 |
22 | /**
23 | * @author Ruslan Sennov
24 | */
25 | @RunWith(Suite.class)
26 | @Suite.SuiteClasses({
27 | BrokenConsul.class,
28 | BrokenClient.class,
29 | AgentInfo.class,
30 | AclTokens.class,
31 | Catalog.class,
32 | Checks.class,
33 | Coordinates.class,
34 | Events.class,
35 | KVStore.class,
36 | Services.class,
37 | Sessions.class,
38 | Status.class,
39 | SecureClient.class,
40 | Transactions.class,
41 | Watches.class,
42 | PreparedQuery.class
43 | })
44 | public class ConsulClientTest {
45 | }
46 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/OptionsTest.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests;
2 |
3 | import io.vertx.core.json.JsonObject;
4 | import io.vertx.ext.consul.ConsulClientOptions;
5 | import org.junit.Test;
6 |
7 | import java.net.URI;
8 |
9 | import static org.junit.Assert.assertEquals;
10 |
11 | /**
12 | * @author Ruslan Sennov
13 | */
14 | public class OptionsTest {
15 |
16 | @Test
17 | public void defaults() {
18 | ConsulClientOptions options = new ConsulClientOptions();
19 | assertEquals(options.getHost(), "localhost");
20 | assertEquals(options.getPort(), 8500);
21 | assertEquals(options.getTimeout(), 0);
22 | assertEquals(options.getAclToken(), null);
23 | assertEquals(options.getDc(), null);
24 | }
25 |
26 | @Test
27 | public void fromURI() {
28 | checkURI(URI.create("consul://host"), "host", 8500, null, null);
29 | checkURI(URI.create("scheme://host?acl=secret"), "host", 8500, null, "secret");
30 | checkURI(URI.create("will://host?aclToken=token"), "host", 8500, null, "token");
31 | checkURI(URI.create("be://google?dc=data"), "google", 8500, "data", null);
32 | checkURI(URI.create("ignored://example?dc=center&acl=000"), "example", 8500, "center", "000");
33 | checkURI(URI.create("full://1:2?dc=3&acl=4"), "1", 2, "3", "4");
34 | }
35 |
36 | private void checkURI(URI uri, String host, int port, String dc, String acl) {
37 | ConsulClientOptions options = new ConsulClientOptions(uri);
38 | assertEquals(options.getHost(), host);
39 | assertEquals(options.getPort(), port);
40 | assertEquals(options.getDc(), dc);
41 | assertEquals(options.getAclToken(), acl);
42 | }
43 |
44 | @Test
45 | public void fromEmptyJson() {
46 | ConsulClientOptions options = new ConsulClientOptions(new JsonObject());
47 | assertEquals(options.getHost(), "localhost");
48 | assertEquals(options.getPort(), 8500);
49 | }
50 |
51 | private void checkJson(ConsulClientOptions options, JsonObject json) {
52 | assertEquals(options.getHost(), json.getString("host"));
53 | assertEquals(options.getPort(), (int) json.getInteger("port"));
54 | assertEquals(options.getTimeout(), (long) json.getLong("timeout"));
55 | assertEquals(options.getUserAgent(), json.getString("userAgent"));
56 | assertEquals(options.getAclToken(), json.getString("aclToken"));
57 | assertEquals(options.getDc(), json.getString("dc"));
58 | }
59 |
60 | @Test
61 | public void toJson() {
62 | ConsulClientOptions options = new ConsulClientOptions()
63 | .setHost("host")
64 | .setPort(42)
65 | .setTimeout(33)
66 | .setUserAgent("ag")
67 | .setAclToken("tok")
68 | .setDc("d");
69 | JsonObject json = options.toJson();
70 | checkJson(options, json);
71 | }
72 |
73 | @Test
74 | public void fromJson() {
75 | JsonObject json = new JsonObject()
76 | .put("host", "host")
77 | .put("port", 42)
78 | .put("timeout", 33)
79 | .put("userAgent", "agent")
80 | .put("aclToken", "top-secret")
81 | .put("dc", "far-away");
82 | ConsulClientOptions options = new ConsulClientOptions(json);
83 | checkJson(options, json);
84 | }
85 |
86 | @Test
87 | public void copy() {
88 | ConsulClientOptions options = new ConsulClientOptions()
89 | .setHost("host")
90 | .setPort(42)
91 | .setTimeout(33)
92 | .setUserAgent("ag")
93 | .setAclToken("tok")
94 | .setDc("d");
95 | ConsulClientOptions copy = new ConsulClientOptions(options);
96 | assertEquals(options.getHost(), copy.getHost());
97 | assertEquals(options.getPort(), copy.getPort());
98 | assertEquals(options.getTimeout(), copy.getTimeout());
99 | assertEquals(options.getUserAgent(), copy.getUserAgent());
100 | assertEquals(options.getAclToken(), copy.getAclToken());
101 | assertEquals(options.getDc(), copy.getDc());
102 | }
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/dc/ConsulDatacenter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.dc;
17 |
18 | /**
19 | * @author Ruslan Sennov
20 | */
21 | public class ConsulDatacenter {
22 |
23 | private final String name;
24 | private final String masterToken;
25 | private String writeToken;
26 | private String readToken;
27 |
28 |
29 | public static ConsulDatacenter create() {
30 | return new ConsulDatacenter(new ConsulDatacenterOptions());
31 | }
32 |
33 | public static ConsulDatacenter create(ConsulDatacenterOptions options) {
34 | return new ConsulDatacenter(options);
35 | }
36 |
37 | private ConsulDatacenter(ConsulDatacenterOptions options) {
38 | name = options.getName();
39 | masterToken = options.getMasterToken();
40 | }
41 |
42 | public String getName() {
43 | return name;
44 | }
45 |
46 | public String getMasterToken() {
47 | return masterToken;
48 | }
49 |
50 | public void setWriteToken(String token) {
51 | writeToken = token;
52 | }
53 |
54 | public void setReadToken(String token) {
55 | readToken = token;
56 | }
57 |
58 | public String writeToken() {
59 | return writeToken;
60 | }
61 |
62 | public String readToken() {
63 | return readToken;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/dc/ConsulDatacenterOptions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.dc;
17 |
18 | import java.util.UUID;
19 |
20 | import static io.vertx.test.core.TestUtils.randomPositiveInt;
21 |
22 | /**
23 | * @author Ruslan Sennov
24 | */
25 | public class ConsulDatacenterOptions {
26 |
27 | private String name;
28 | private String masterToken;
29 |
30 | public ConsulDatacenterOptions() {
31 | name = "dc-" + randomPositiveInt();
32 | masterToken = UUID.randomUUID().toString();
33 | }
34 |
35 | public String getName() {
36 | return name;
37 | }
38 |
39 | public String getMasterToken() {
40 | return masterToken;
41 | }
42 |
43 | public ConsulDatacenterOptions setName(String name) {
44 | this.name = name;
45 | return this;
46 | }
47 |
48 | public ConsulDatacenterOptions setMasterToken(String masterToken) {
49 | this.masterToken = masterToken;
50 | return this;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/impl/WatchKeyPrefixCnt.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests.impl;
2 |
3 | import io.vertx.core.AsyncResult;
4 | import io.vertx.core.Handler;
5 | import io.vertx.core.Vertx;
6 | import io.vertx.ext.consul.ConsulClientOptions;
7 | import io.vertx.ext.consul.KeyValueList;
8 | import io.vertx.ext.consul.impl.WatchImpl;
9 |
10 | public class WatchKeyPrefixCnt extends WatchImpl.KeyPrefix {
11 |
12 | private int cnt = 0;
13 |
14 | public WatchKeyPrefixCnt(String keyPrefix, Vertx vertx, ConsulClientOptions options) {
15 | super(keyPrefix, vertx, options);
16 | }
17 |
18 | @Override
19 | protected void wait(long index, Handler>> handler) {
20 | cnt++;
21 | super.wait(index, handler);
22 | }
23 |
24 | public int cnt() {
25 | return cnt;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/instance/SemVer.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests.instance;
2 |
3 | import org.jetbrains.annotations.NotNull;
4 |
5 | public class SemVer implements Comparable {
6 | int major;
7 | int minor;
8 | int patch;
9 |
10 | public SemVer(String version) {
11 | String[] split = version.split("\\.");
12 | if (split.length == 0) {
13 | throw new RuntimeException("Empty version");
14 | }
15 | major = Integer.parseInt(split[0]);
16 | minor = Integer.parseInt(split[1]);
17 | patch = Integer.parseInt(split[2]);
18 | }
19 |
20 | @Override
21 | public int compareTo(@NotNull SemVer o) {
22 | int majors = Integer.compare(major, o.major);
23 | if (majors == 0) {
24 | int minors = Integer.compare(minor, o.minor);
25 | if (minors == 0) {
26 | return Integer.compare(patch, o.patch);
27 | } else return minors;
28 | } else return majors;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/AclPolicyTest.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests.suite;
2 |
3 | import io.vertx.ext.consul.tests.ConsulTestBase;
4 | import io.vertx.ext.consul.policy.AclPolicy;
5 | import io.vertx.ext.unit.TestContext;
6 | import io.vertx.ext.unit.junit.VertxUnitRunner;
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import java.util.HashSet;
11 | import java.util.List;
12 | import java.util.Set;
13 | import java.util.stream.Collectors;
14 |
15 | import static io.vertx.ext.consul.tests.Utils.getAsync;
16 |
17 | @RunWith(VertxUnitRunner.class)
18 | public class AclPolicyTest extends ConsulTestBase {
19 |
20 | private static final Set buildIn;
21 |
22 | static {
23 | buildIn = new HashSet<>();
24 | buildIn.add("global-management");
25 | buildIn.add("builtin/global-read-only");
26 | }
27 |
28 | private List filter(List policies) {
29 | return policies.stream()
30 | .filter(aclPolicy -> !buildIn.contains(aclPolicy.getName()))
31 | .collect(Collectors.toList());
32 | }
33 |
34 | @Test
35 | public void lifecycle(TestContext tc) {
36 | List policies = filter(getAsync(() -> masterClient.getAclPolicies()));
37 | tc.assertEquals(2, policies.size());
38 | AclPolicy policy = new AclPolicy()
39 | .setName("created_policy")
40 | .setRules("key \"bar/\" { policy = \"read\" }");
41 | String createdId = getAsync(() -> masterClient.createAclPolicy(policy));
42 | List newPolicies = filter(getAsync(() -> masterClient.getAclPolicies()));
43 | tc.assertEquals(3, newPolicies.size());
44 | AclPolicy read = getAsync(() -> masterClient.readPolicy(createdId));
45 | tc.assertEquals(createdId, read.getId());
46 | tc.assertEquals(policy.getRules(), read.getRules());
47 | tc.assertEquals(policy.getName(), read.getName());
48 |
49 | AclPolicy updateOptions = new AclPolicy()
50 | .setName("updated_policy")
51 | .setRules("key \"bar/\" { policy = \"write\" }");
52 | AclPolicy updatedPolicy = getAsync(() -> masterClient.updatePolicy(createdId, updateOptions));
53 | tc.assertEquals(updateOptions.getName(), updatedPolicy.getName());
54 | tc.assertEquals(updateOptions.getRules(), updateOptions.getRules());
55 | AclPolicy readByName = getAsync(() -> masterClient.readPolicyByName(updateOptions.getName()));
56 | tc.assertEquals(createdId, readByName.getId());
57 | tc.assertEquals(updateOptions.getName(), readByName.getName());
58 | tc.assertEquals(updateOptions.getRules(), readByName.getRules());
59 | Boolean isDeleted = getAsync(() -> masterClient.deletePolicy(createdId));
60 | tc.assertTrue(isDeleted);
61 | List afterDeleting = filter(getAsync(() -> masterClient.getAclPolicies()));
62 | tc.assertEquals(2, afterDeleting.size());
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/AclTokens.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.suite;
17 |
18 | import io.vertx.ext.consul.tests.ConsulTestBase;
19 | import io.vertx.ext.consul.policy.AclPolicy;
20 | import io.vertx.ext.consul.token.AclToken;
21 | import io.vertx.ext.consul.token.CloneAclTokenOptions;
22 | import io.vertx.ext.consul.token.PolicyLink;
23 | import io.vertx.ext.unit.TestContext;
24 | import io.vertx.ext.unit.junit.VertxUnitRunner;
25 | import org.junit.Test;
26 | import org.junit.runner.RunWith;
27 |
28 | /**
29 | * @author Ruslan Sennov
30 | */
31 | @RunWith(VertxUnitRunner.class)
32 | public class AclTokens extends ConsulTestBase {
33 |
34 | @Test
35 | public void lifecycle(TestContext tc) {
36 | masterClient.getAclTokens().onComplete(tc.asyncAssertSuccess(backupTokens -> {
37 | AclPolicy policy = new AclPolicy()
38 | .setName("tokenName")
39 | .setRules("key \"bar/\" { policy = \"read\" }");
40 | masterClient.createAclPolicy(policy).onComplete(tc.asyncAssertSuccess(policyId -> {
41 | AclToken init = new AclToken()
42 | .addPolicy(new PolicyLink().setId(policyId));
43 | masterClient.createAclToken(init).onComplete(tc.asyncAssertSuccess(aclToken -> {
44 | String id = aclToken.getAccessorId();
45 | masterClient.readAclToken(id).onComplete(tc.asyncAssertSuccess(token -> {
46 | PolicyLink receivedPolicy = token.getPolicies().stream().findFirst()
47 | .orElse(new PolicyLink());
48 | tc.assertEquals(id, token.getAccessorId());
49 | tc.assertEquals(policy.getName(), receivedPolicy.getName());
50 | masterClient.cloneAclToken(id, new CloneAclTokenOptions()).onComplete(tc.asyncAssertSuccess(clonedToken -> {
51 | String clonedId = clonedToken.getAccessorId();
52 | masterClient.readAclToken(clonedId).onComplete(tc.asyncAssertSuccess(receivedClonedToken -> {
53 | PolicyLink receivedClonedPolicy = receivedClonedToken.getPolicies().stream().findFirst()
54 | .orElse(new PolicyLink());
55 | tc.assertEquals(clonedId, receivedClonedToken.getAccessorId());
56 | tc.assertEquals(receivedPolicy.getName(), receivedClonedPolicy.getName());
57 | AclPolicy policy2 = new AclPolicy()
58 | .setName("updatedName")
59 | .setRules("key \"bar/\" { policy = \"write\" }");
60 | masterClient.createAclPolicy(policy2).onComplete(tc.asyncAssertSuccess(policyId2 -> {
61 | AclToken token2 = new AclToken()
62 | .addPolicy(new PolicyLink().setId(policyId2));
63 | masterClient.updateAclToken(clonedToken.getAccessorId(), token2).onComplete(tc.asyncAssertSuccess(updatedId -> {
64 | masterClient.readAclToken(updatedId.getAccessorId()).onComplete(tc.asyncAssertSuccess(updatedToken -> {
65 | PolicyLink receivedPolicy2 = updatedToken.getPolicies().stream().findFirst()
66 | .orElse(new PolicyLink());
67 | tc.assertEquals(clonedToken.getAccessorId(), updatedToken.getAccessorId());
68 | tc.assertEquals(policy2.getName(), receivedPolicy2.getName());
69 | masterClient.deleteAclToken(id).onComplete(tc.asyncAssertSuccess(v1 -> {
70 | masterClient.deleteAclToken(clonedId).onComplete(tc.asyncAssertSuccess(v2 -> {
71 | masterClient.getAclTokens().onComplete(tc.asyncAssertSuccess(aliveTokens -> {
72 | tc.assertEquals(backupTokens.size(), aliveTokens.size());
73 | }));
74 | }));
75 | }));
76 | }));
77 | }));
78 | }));
79 | }));
80 | }));
81 | }));
82 | }));
83 | }));
84 | }));
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/AgentInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.suite;
17 |
18 | import io.vertx.core.json.JsonObject;
19 | import io.vertx.ext.consul.tests.ConsulTestBase;
20 | import io.vertx.ext.unit.TestContext;
21 | import io.vertx.ext.unit.junit.VertxUnitRunner;
22 | import org.junit.Test;
23 | import org.junit.runner.RunWith;
24 |
25 | /**
26 | * @author Ruslan Sennov
27 | */
28 | @RunWith(VertxUnitRunner.class)
29 | public class AgentInfo extends ConsulTestBase {
30 |
31 | @Test
32 | public void info(TestContext tc) {
33 | readClient.agentInfo().onComplete(tc.asyncAssertSuccess(info -> {
34 | JsonObject config = info.getJsonObject("Config");
35 | tc.assertEquals(config.getString("Datacenter"), consul.dc().getName());
36 | }));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/BrokenClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.suite;
17 |
18 | import io.vertx.ext.consul.ConsulClient;
19 | import io.vertx.ext.consul.ConsulClientOptions;
20 | import io.vertx.ext.consul.tests.ConsulTestBase;
21 | import io.vertx.ext.consul.tests.Utils;
22 | import io.vertx.ext.unit.TestContext;
23 | import io.vertx.ext.unit.junit.VertxUnitRunner;
24 | import org.junit.Test;
25 | import org.junit.runner.RunWith;
26 |
27 | /**
28 | * @author Ruslan Sennov
29 | */
30 | @RunWith(VertxUnitRunner.class)
31 | public class BrokenClient extends ConsulTestBase {
32 |
33 | @Test
34 | public void unknownHost(TestContext tc) {
35 | ConsulClient unknownHost = consul.createClient(vertx, new ConsulClientOptions().setHost("unknownConsulHost"));
36 | tryClient(tc, unknownHost, "unknownConsulHost");
37 | }
38 |
39 | @Test
40 | public void unknownPort(TestContext tc) {
41 | ConsulClient unknownPort = consul.createClient(vertx, new ConsulClientOptions().setPort(Utils.getFreePort()));
42 | tryClient(tc, unknownPort, "Connection refused");
43 | }
44 |
45 | private void tryClient(TestContext tc, ConsulClient client, String expectedExceptionMessageSubstring) {
46 | client.agentInfo().onComplete(tc.asyncAssertFailure(t -> {
47 | tc.assertTrue(t.getMessage().contains(expectedExceptionMessageSubstring));
48 | client.close();
49 | }));
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/BrokenConsul.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.suite;
17 |
18 | import io.vertx.core.Handler;
19 | import io.vertx.core.Vertx;
20 | import io.vertx.core.http.HttpHeaders;
21 | import io.vertx.core.http.HttpServer;
22 | import io.vertx.core.http.HttpServerRequest;
23 | import io.vertx.core.http.HttpServerResponse;
24 | import io.vertx.ext.consul.ConsulClient;
25 | import io.vertx.ext.consul.ConsulClientOptions;
26 | import io.vertx.ext.consul.tests.ConsulTestBase;
27 | import io.vertx.ext.consul.tests.Utils;
28 | import io.vertx.ext.unit.TestContext;
29 | import io.vertx.ext.unit.junit.VertxUnitRunner;
30 | import org.junit.Test;
31 | import org.junit.runner.RunWith;
32 |
33 | import java.util.concurrent.CountDownLatch;
34 | import java.util.concurrent.TimeUnit;
35 |
36 | /**
37 | * @author Ruslan Sennov
38 | */
39 | @RunWith(VertxUnitRunner.class)
40 | public class BrokenConsul extends ConsulTestBase {
41 |
42 | @Test
43 | public void timeout(TestContext tc) {
44 | SlowHttpServer slowConsul = new SlowHttpServer(vertx, 10000);
45 | ConsulClient client = consul.createClient(vertx, new ConsulClientOptions().setPort(slowConsul.port()).setTimeout(1000));
46 | client.agentInfo().onComplete(tc.asyncAssertFailure(t -> {
47 | client.close();
48 | slowConsul.close();
49 | tc.assertTrue(t.getMessage().contains("The timeout period of 1000ms"));
50 | }));
51 | }
52 |
53 | @Test
54 | public void closedConnection(TestContext tc) {
55 | BrokenHttpServer brokenConsul = new BrokenHttpServer(vertx);
56 | ConsulClient client = consul.createClient(vertx, new ConsulClientOptions().setPort(brokenConsul.port()));
57 | client.agentInfo().onComplete(tc.asyncAssertFailure(t -> {
58 | client.close();
59 | brokenConsul.close();
60 | tc.assertTrue(t.getMessage().contains("Connection was closed"));
61 | }));
62 | }
63 |
64 | static class SlowHttpServer extends CustomHttpServer {
65 | SlowHttpServer(Vertx vertx, long delay) {
66 | super(vertx, h -> vertx.setTimer(delay, t -> h.response().end()));
67 | }
68 | }
69 |
70 | static class BrokenHttpServer extends CustomHttpServer {
71 | BrokenHttpServer(Vertx vertx) {
72 | super(vertx, h -> {
73 | HttpServerResponse resp = h.response();
74 | resp.putHeader(HttpHeaders.CONTENT_LENGTH, "10000").write("start and ... ");
75 | h.connection().close();
76 | });
77 | }
78 | }
79 |
80 | static class CustomHttpServer {
81 |
82 | private final HttpServer server;
83 | private final int port;
84 |
85 | CustomHttpServer(Vertx vertx, Handler handler) {
86 | this.port = Utils.getFreePort();
87 | CountDownLatch latch = new CountDownLatch(1);
88 | this.server = vertx.createHttpServer()
89 | .requestHandler(handler);
90 | server.listen(port).onComplete(h -> latch.countDown());
91 | try {
92 | latch.await(10, TimeUnit.SECONDS);
93 | } catch (InterruptedException e) {
94 | e.printStackTrace();
95 | }
96 | }
97 |
98 | int port() {
99 | return port;
100 | }
101 |
102 | void close() {
103 | server.close();
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/Coordinates.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.suite;
17 |
18 | import io.vertx.ext.consul.*;
19 | import io.vertx.ext.consul.tests.instance.ConsulInstance;
20 | import io.vertx.ext.consul.tests.ConsulTestBase;
21 | import org.junit.Test;
22 |
23 | import java.util.List;
24 | import java.util.concurrent.CountDownLatch;
25 | import java.util.concurrent.TimeUnit;
26 |
27 | import static io.vertx.ext.consul.tests.Utils.*;
28 |
29 | /**
30 | * @author Ruslan Sennov
31 | */
32 | public class Coordinates extends ConsulTestBase {
33 |
34 | private static final int MAX_REQUESTS = 100;
35 |
36 | @Test
37 | public void nodes() throws InterruptedException {
38 | CoordinateList nodes1 = null;
39 | int requests = MAX_REQUESTS;
40 | while (requests --> 0) {
41 | nodes1 = getAsync(() -> readClient.coordinateNodes());
42 | if (nodes1.getList().size() == 1) {
43 | break;
44 | }
45 | sleep(vertx, 1000);
46 | System.out.println("waiting for node coordinates...");
47 | }
48 | if(nodes1 == null || nodes1.getList().size() != 1) {
49 | fail();
50 | return;
51 | }
52 | Coordinate coordinate = nodes1.getList().get(0);
53 | assertEquals(coordinate.getNode(), consul.getConfig("node_name"));
54 |
55 | CountDownLatch latch = new CountDownLatch(1);
56 |
57 | waitBlockingQuery(latch, 10, nodes1.getIndex(), (idx, fut) -> {
58 | BlockingQueryOptions opts = new BlockingQueryOptions().setIndex(idx);
59 | readClient.coordinateNodesWithOptions(opts).onComplete(h -> {
60 | boolean success = h.result().getList().size() == 2;
61 | waitComplete(vertx, fut, h.result().getIndex(), success);
62 | });
63 | });
64 |
65 | sleep(vertx, 2000);
66 | ConsulInstance attached = ConsulInstance.defaultConsulBuilder(dc).join(consul).nodeName("new_node").build();
67 | latch.await(2, TimeUnit.MINUTES);
68 | assertEquals(latch.getCount(), 0);
69 |
70 | attached.stop();
71 |
72 | // wait until the second consul will leave
73 | assertTrue(waitPeers());
74 | }
75 |
76 | private boolean waitPeers() {
77 | int requests = MAX_REQUESTS;
78 | while (requests --> 0) {
79 | List peers = getAsync(() -> readClient.peersStatus());
80 | if (peers.size() == 1) {
81 | return true;
82 | }
83 | sleep(vertx, 1000);
84 | System.out.println("waiting for peers...");
85 | }
86 | return false;
87 | }
88 |
89 | @Test
90 | public void datacenters() {
91 | List datacenters = null;
92 | int requests = MAX_REQUESTS;
93 | while (requests --> 0) {
94 | datacenters = getAsync(() -> readClient.coordinateDatacenters());
95 | if (datacenters.size() > 0) {
96 | break;
97 | }
98 | sleep(vertx, 1000);
99 | System.out.println("waiting for datacenter coordinates...");
100 | }
101 | if(datacenters == null || datacenters.size() == 0) {
102 | fail();
103 | return;
104 | }
105 | DcCoordinates coordinate = datacenters.get(0);
106 | assertEquals(coordinate.getDatacenter(), consul.dc().getName());
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/Events.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.suite;
17 |
18 | import io.vertx.ext.consul.*;
19 | import io.vertx.ext.consul.tests.ConsulTestBase;
20 | import io.vertx.ext.unit.Async;
21 | import io.vertx.ext.unit.TestContext;
22 | import io.vertx.ext.unit.junit.VertxUnitRunner;
23 | import org.junit.Test;
24 | import org.junit.runner.RunWith;
25 |
26 | import java.util.List;
27 | import java.util.stream.Collectors;
28 |
29 | import static io.vertx.test.core.TestUtils.randomAlphaString;
30 |
31 | /**
32 | * @author Ruslan Sennov
33 | */
34 | @RunWith(VertxUnitRunner.class)
35 | public class Events extends ConsulTestBase {
36 |
37 | @Test
38 | public void events(TestContext tc) {
39 | runTest(tc, false);
40 | }
41 |
42 | @Test
43 | public void timeout(TestContext tc) {
44 | runTest(tc, true);
45 | }
46 |
47 | private void runTest(TestContext tc, boolean timeout) {
48 | String name1 = randomAlphaString(10);
49 | String name2 = randomAlphaString(10);
50 | EventOptions opts = new EventOptions().setPayload(randomAlphaString(10));
51 | writeClient.fireEventWithOptions(name1, opts).onComplete(tc.asyncAssertSuccess(event -> {
52 | tc.assertEquals(name1, event.getName());
53 | tc.assertEquals(opts.getPayload(), event.getPayload());
54 | String evId1 = event.getId();
55 | writeClient.listEvents().onComplete(tc.asyncAssertSuccess(list1 -> {
56 | long cnt1 = list1.getList().stream()
57 | .map(Event::getId)
58 | .filter(id -> id.equals(evId1))
59 | .count();
60 | tc.assertEquals(cnt1, (long) 1);
61 | writeClient.listEventsWithOptions(new EventListOptions().setName(name2)).onComplete(tc.asyncAssertSuccess(list2 -> {
62 | tc.assertEquals(list2.getList().size(), 0);
63 | Async async = tc.async(2);
64 | BlockingQueryOptions blockingQueryOptions = new BlockingQueryOptions()
65 | .setIndex(list1.getIndex());
66 | if (timeout) {
67 | blockingQueryOptions.setWait("2s");
68 | }
69 | writeClient.listEventsWithOptions(new EventListOptions().setBlockingOptions(blockingQueryOptions)).onComplete(tc.asyncAssertSuccess(h -> {
70 | List names = h.getList().stream().map(Event::getName).collect(Collectors.toList());
71 | if (timeout) {
72 | tc.assertTrue(names.contains(name1));
73 | tc.assertFalse(names.contains(name2));
74 | } else {
75 | tc.assertTrue(names.contains(name1));
76 | tc.assertTrue(names.contains(name2));
77 | }
78 | async.countDown();
79 | }));
80 | tc.assertEquals(async.count(), 2);
81 | vertx.setTimer(4000, l -> {
82 | tc.assertEquals(async.count(), timeout ? 1 : 2);
83 | writeClient.fireEvent(name2).onComplete(tc.asyncAssertSuccess(ev -> {
84 | writeClient.listEventsWithOptions(new EventListOptions().setName(name2)).onComplete(tc.asyncAssertSuccess(list3 -> {
85 | tc.assertEquals(list3.getList().size(), 1);
86 | async.complete();
87 | }));
88 | }));
89 | });
90 | }));
91 | }));
92 | }));
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/SecureClient.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests.suite;
2 |
3 | import io.vertx.core.buffer.Buffer;
4 | import io.vertx.core.net.PemTrustOptions;
5 | import io.vertx.ext.consul.ConsulClient;
6 | import io.vertx.ext.consul.tests.ConsulTestBase;
7 | import io.vertx.ext.consul.tests.Utils;
8 | import io.vertx.ext.unit.TestContext;
9 | import io.vertx.ext.unit.junit.VertxUnitRunner;
10 | import org.junit.Test;
11 | import org.junit.runner.RunWith;
12 |
13 | /**
14 | * @author Ruslan Sennov
15 | */
16 | @RunWith(VertxUnitRunner.class)
17 | public class SecureClient extends ConsulTestBase {
18 |
19 | @Test
20 | public void withTrustAll(TestContext tc) {
21 | go(tc, true, null);
22 | }
23 |
24 | @Test
25 | public void withTrustOptions(TestContext tc) throws Exception {
26 | PemTrustOptions options = new PemTrustOptions()
27 | .addCertValue(Buffer.buffer(Utils.readResource("server-cert-ca-chain.pem")));
28 | go(tc, false, options);
29 | }
30 |
31 | private void go(TestContext tc, boolean trustAll, PemTrustOptions trustOptions) {
32 | ConsulClient secureClient = consul.createSecureClient(vertx, consul.dc().getMasterToken(), trustAll, trustOptions);
33 | secureClient.putValue("foo/bars42", "value42").onComplete(tc.asyncAssertSuccess(b -> {
34 | tc.assertTrue(b);
35 | secureClient.getValue("foo/bars42").onComplete(tc.asyncAssertSuccess(pair -> {
36 | tc.assertEquals(pair.getValue(), "value42");
37 | secureClient.close();
38 | }));
39 | }));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/suite/Status.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 The original author or authors
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 | package io.vertx.ext.consul.tests.suite;
17 |
18 | import io.vertx.ext.consul.tests.ConsulTestBase;
19 | import io.vertx.ext.unit.TestContext;
20 | import io.vertx.ext.unit.junit.VertxUnitRunner;
21 | import org.junit.Test;
22 | import org.junit.runner.RunWith;
23 |
24 | /**
25 | * @author Ruslan Sennov
26 | */
27 | @RunWith(VertxUnitRunner.class)
28 | public class Status extends ConsulTestBase {
29 |
30 | @Test
31 | public void leader(TestContext tc) {
32 | readClient.leaderStatus().onComplete(tc.asyncAssertSuccess(leader -> {
33 | tc.assertEquals(leader.substring(0, leader.indexOf(':')), consul.getContainerNetwork().getIpAddress());
34 | }));
35 | }
36 |
37 | @Test
38 | public void peers(TestContext tc) {
39 | readClient.peersStatus().onComplete(tc.asyncAssertSuccess(peers -> {
40 | tc.assertEquals(peers.size(), 1);
41 | }));
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/test/java/io/vertx/ext/consul/tests/vertx/VertxHttpServer.java:
--------------------------------------------------------------------------------
1 | package io.vertx.ext.consul.tests.vertx;
2 |
3 | import com.github.dockerjava.api.model.ContainerNetwork;
4 | import io.vertx.ext.consul.CheckStatus;
5 | import org.testcontainers.containers.GenericContainer;
6 | import org.testcontainers.containers.wait.strategy.Wait;
7 | import org.testcontainers.containers.wait.strategy.WaitStrategy;
8 | import org.testcontainers.images.builder.Transferable;
9 | import org.testcontainers.utility.MountableFile;
10 |
11 | import java.time.Duration;
12 |
13 | public class VertxHttpServer extends GenericContainer {
14 | private static final String IMAGE = "vertx/vertx4";
15 | private final String VERTICLE_HOME = "/usr/verticles";
16 | private final String STATUS_FILE = "health_status.txt";
17 | private final String HEALTH_HTTP_VERTICLE = "health_http_verticle.groovy";
18 |
19 | public VertxHttpServer() {
20 | super(IMAGE);
21 | }
22 |
23 | @Override
24 | protected void configure() {
25 | String version;
26 | if (isArm64()) {
27 | version = "4.4.1";
28 | } else version = "4.4.0";
29 | this.setDockerImageName(IMAGE + ":" + version);
30 | this.withEnv("VERTICLE_NAME", HEALTH_HTTP_VERTICLE);
31 | this.withEnv("VERTICLE_HOME", VERTICLE_HOME);
32 | this.withExposedPorts(8080);
33 | this.withWorkingDirectory(VERTICLE_HOME);
34 | this.withCopyFileToContainer(MountableFile.forClasspathResource(HEALTH_HTTP_VERTICLE), VERTICLE_HOME + "/");
35 | this.withCopyFileToContainer(MountableFile.forClasspathResource(STATUS_FILE), VERTICLE_HOME + "/");
36 | this.withCommand("vertx run " + HEALTH_HTTP_VERTICLE + " -cp " + VERTICLE_HOME + "/*");
37 | WaitStrategy wait = Wait.forHttp("/")
38 | .forStatusCode(200)
39 | .forPort(8080)
40 | .withStartupTimeout(Duration.ofSeconds(90));
41 | setWaitStrategy(wait);
42 | }
43 |
44 | public String address() {
45 | if (isMacOS()) return getContainerNetwork().getIpAddress();
46 | else return getContainerNetwork().getGateway();
47 | }
48 |
49 | public int port() {
50 | if (isMacOS()) return 8080;
51 | else return getMappedPort(8080);
52 | }
53 |
54 | private boolean isMacOS() {
55 | String osName = System.getProperty("os.name");
56 | return osName != null
57 | && (osName.toLowerCase().contains("mac") || osName.toLowerCase().contains("darwin"));
58 | }
59 |
60 | private boolean isArm64() {
61 | String osArch = System.getProperty("os.arch");
62 | return osArch != null && isMacOS() && osArch.equalsIgnoreCase("aarch64");
63 | }
64 |
65 | private ContainerNetwork getContainerNetwork() {
66 | return getContainerInfo()
67 | .getNetworkSettings()
68 | .getNetworks()
69 | .values()
70 | .stream()
71 | .findFirst()
72 | .orElseThrow(() -> new IllegalStateException("Container network is unknown"));
73 | }
74 |
75 | public void updateStatus(CheckStatus status) {
76 | int statusCode;
77 | switch (status) {
78 | case PASSING:
79 | statusCode = 200;
80 | break;
81 | case WARNING:
82 | statusCode = 429;
83 | break;
84 | default:
85 | statusCode = 500;
86 | break;
87 | }
88 | copyFileToContainer(Transferable.of(String.valueOf(statusCode)), VERTICLE_HOME + "/" + STATUS_FILE);
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/src/test/java/module-info.java:
--------------------------------------------------------------------------------
1 | open module io.vertx.consul.client.tests {
2 | requires consul;
3 | requires com.github.dockerjava.api;
4 | requires com.fasterxml.jackson.annotation;
5 | requires io.vertx.core;
6 | requires io.vertx.consul.client;
7 | requires io.vertx.core.tests;
8 | requires io.vertx.testing.unit;
9 | requires junit;
10 | requires hamcrest.core;
11 | requires org.slf4j;
12 | requires testcontainers;
13 | }
14 |
--------------------------------------------------------------------------------
/src/test/resources/connect_example.json:
--------------------------------------------------------------------------------
1 | {
2 | "SidecarService": {
3 | "Port": 33333,
4 | "Proxy": {
5 | "Upstreams": [{
6 | "DestinationName": "dev-mesh-database-service",
7 | "Datacenter": "dc-v5",
8 | "LocalBindPort": 19102
9 | }],
10 | "Config": {
11 | "envoy_local_cluster_json": "envoy_local_cluster_json1",
12 | "envoy_public_listener_json": "envoy_local_cluster_json2",
13 | "envoy_prometheus_bind_addr": "0.0.0.0:19500",
14 | "envoy_extra_static_clusters_json": "envoy_local_cluster_json3"
15 | },
16 | "Expose": {
17 | "Paths": [
18 | {
19 | "Path": "/metrics",
20 | "Protocol": "http",
21 | "LocalPathPort": 53000,
22 | "ListenerPort": 19600
23 | }
24 | ]
25 | }
26 | },
27 | "Checks": [
28 | {
29 | "Name": "Connect Sidecar dev-mesh-counting-service Listening",
30 | "HTTP": "http://dev-mesh-counting-service:19000/healthcheck/ok",
31 | "Method": "POST",
32 | "Interval": "20s",
33 | "Timeout": "5s"
34 | },
35 | {
36 | "Name": "Connect Sidecar Aliasing dev-mesh-counting-service",
37 | "AliasService": "dev-mesh-counting-service"
38 | }
39 | ]
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/test/resources/health_http_verticle.groovy:
--------------------------------------------------------------------------------
1 | vertx.createHttpServer().requestHandler({ request ->
2 | File file = new File("/usr/verticles/health_status.txt");
3 | def statusCode = file.text
4 | request.response().setStatusCode(statusCode.toInteger()).end(statusCode)
5 | }).listen(8080);
6 |
--------------------------------------------------------------------------------
/src/test/resources/health_script.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | for /f "delims=" %%x in (%STATUS_FILE%) do exit %%x
3 |
--------------------------------------------------------------------------------
/src/test/resources/health_script.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | CODE=`cat %STATUS_FILE%`
3 | exit $((CODE))
4 |
--------------------------------------------------------------------------------
/src/test/resources/health_status.txt:
--------------------------------------------------------------------------------
1 | 200
2 |
--------------------------------------------------------------------------------
/src/test/resources/read_rules.hcl:
--------------------------------------------------------------------------------
1 | agent_prefix "" {
2 | policy = "read"
3 | }
4 | agent "" {
5 | policy = "read"
6 | }
7 | key_prefix "" {
8 | policy = "read"
9 | }
10 | key "" {
11 | policy = "read"
12 | }
13 | key "foo/" {
14 | policy = "read"
15 | }
16 | event_prefix "" {
17 | policy = "read"
18 | }
19 | event "" {
20 | policy = "read"
21 | }
22 | service_prefix "" {
23 | policy = "read"
24 | }
25 | service "" {
26 | policy = "read"
27 | }
28 | query_prefix "" {
29 | policy = "write"
30 | }
31 | query "" {
32 | policy = "read"
33 | }
34 | node_prefix "" {
35 | policy = "read"
36 | }
37 | node "" {
38 | policy = "read"
39 | }
40 | session_prefix "" {
41 | policy = "read"
42 | }
43 | session "" {
44 | policy = "read"
45 | }
46 |
--------------------------------------------------------------------------------
/src/test/resources/server-cert-ca-chain.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICnDCCAkKgAwIBAgIQPzkL/KFHHwh5xqs0UUd9jjAKBggqhkjOPQQDAjCBuTEL
3 | MAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2Nv
4 | MRowGAYDVQQJExExMDEgU2Vjb25kIFN0cmVldDEOMAwGA1UEERMFOTQxMDUxFzAV
5 | BgNVBAoTDkhhc2hpQ29ycCBJbmMuMUAwPgYDVQQDEzdDb25zdWwgQWdlbnQgQ0Eg
6 | MTQzMjk0ODU5MzYyNjEzNTQ4NTI4NzIzMzE2NDU2NjQ1MTkxNjQ4MB4XDTIxMDgw
7 | OTEyMDI0MloXDTIyMDgwOTEyMDI0MlowHDEaMBgGA1UEAxMRc2VydmVyLmRjMS5j
8 | b25zdWwwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQJQypshCRG7dunJ5LWPOrr
9 | mlC06StsjVwPJdydbjTRS9uixZt7xH4eQ+w4PxtOgiO0EvG5BKz6fGSq/asxi2F9
10 | o4HHMIHEMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB
11 | BQUHAwIwDAYDVR0TAQH/BAIwADApBgNVHQ4EIgQgNG0PIept6WR4RMu+naCSCQGc
12 | SfUSC3l3VcgK76iB68UwKwYDVR0jBCQwIoAg+c8jHV46Lhpg59BAEgFKU11GxXuF
13 | 7QxHW+ViJ1dULI4wLQYDVR0RBCYwJIIRc2VydmVyLmRjMS5jb25zdWyCCWxvY2Fs
14 | aG9zdIcEfwAAATAKBggqhkjOPQQDAgNIADBFAiEA2MfuE395aok7Dj6ffM17P8hn
15 | sqNuIHeqWvhuudKEFiYCIG3njN56elTfXtiRY5GSGmrGM7A6gxnpwuN/zfulneNB
16 | -----END CERTIFICATE-----
17 |
--------------------------------------------------------------------------------
/src/test/resources/server-cert.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICnDCCAkKgAwIBAgIQPzkL/KFHHwh5xqs0UUd9jjAKBggqhkjOPQQDAjCBuTEL
3 | MAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2Nv
4 | MRowGAYDVQQJExExMDEgU2Vjb25kIFN0cmVldDEOMAwGA1UEERMFOTQxMDUxFzAV
5 | BgNVBAoTDkhhc2hpQ29ycCBJbmMuMUAwPgYDVQQDEzdDb25zdWwgQWdlbnQgQ0Eg
6 | MTQzMjk0ODU5MzYyNjEzNTQ4NTI4NzIzMzE2NDU2NjQ1MTkxNjQ4MB4XDTIxMDgw
7 | OTEyMDI0MloXDTIyMDgwOTEyMDI0MlowHDEaMBgGA1UEAxMRc2VydmVyLmRjMS5j
8 | b25zdWwwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQJQypshCRG7dunJ5LWPOrr
9 | mlC06StsjVwPJdydbjTRS9uixZt7xH4eQ+w4PxtOgiO0EvG5BKz6fGSq/asxi2F9
10 | o4HHMIHEMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB
11 | BQUHAwIwDAYDVR0TAQH/BAIwADApBgNVHQ4EIgQgNG0PIept6WR4RMu+naCSCQGc
12 | SfUSC3l3VcgK76iB68UwKwYDVR0jBCQwIoAg+c8jHV46Lhpg59BAEgFKU11GxXuF
13 | 7QxHW+ViJ1dULI4wLQYDVR0RBCYwJIIRc2VydmVyLmRjMS5jb25zdWyCCWxvY2Fs
14 | aG9zdIcEfwAAATAKBggqhkjOPQQDAgNIADBFAiEA2MfuE395aok7Dj6ffM17P8hn
15 | sqNuIHeqWvhuudKEFiYCIG3njN56elTfXtiRY5GSGmrGM7A6gxnpwuN/zfulneNB
16 | -----END CERTIFICATE-----
17 |
--------------------------------------------------------------------------------
/src/test/resources/server-key.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN EC PRIVATE KEY-----
2 | MHcCAQEEIIXUFQI61QEpH0jgQV8n5wDKye0tGqGcHUaOY29YMwHFoAoGCCqGSM49
3 | AwEHoUQDQgAECUMqbIQkRu3bpyeS1jzq65pQtOkrbI1cDyXcnW400UvbosWbe8R+
4 | HkPsOD8bToIjtBLxuQSs+nxkqv2rMYthfQ==
5 | -----END EC PRIVATE KEY-----
6 |
--------------------------------------------------------------------------------
/src/test/resources/ssl.txt:
--------------------------------------------------------------------------------
1 | # How to generate new PEM files
2 |
3 | ## Install consul CLI
4 |
5 | See https://www.consul.io/downloads
6 |
7 | ## Generate files
8 |
9 | See https://learn.hashicorp.com/tutorials/consul/tls-encryption-secure
10 |
11 | consul tls ca create
12 | consul tls cert create -server
13 | mv dc1-server-consul-0-key.pem server-key.pem
14 | mv dc1-server-consul-0.pem server-cert.pem
15 | cp server-cert.pem server-cert-ca-chain.pem
16 | rm consul-agent-ca*
17 |
18 |
--------------------------------------------------------------------------------
/src/test/resources/write_rules.hcl:
--------------------------------------------------------------------------------
1 | agent_prefix "" {
2 | policy = "write"
3 | }
4 | agent "" {
5 | policy = "write"
6 | }
7 | key_prefix "" {
8 | policy = "write"
9 | }
10 | key "" {
11 | policy = "read"
12 | }
13 | key "foo/" {
14 | policy = "write"
15 | }
16 | event_prefix "" {
17 | policy = "write"
18 | }
19 | event "" {
20 | policy = "write"
21 | }
22 | service_prefix "" {
23 | policy = "write"
24 | }
25 | service "" {
26 | policy = "write"
27 | }
28 | query_prefix "" {
29 | policy = "write"
30 | }
31 | query "" {
32 | policy = "write"
33 | }
34 | node_prefix "" {
35 | policy = "write"
36 | }
37 | node "" {
38 | policy = "write"
39 | }
40 | session_prefix "" {
41 | policy = "write"
42 | }
43 | session "" {
44 | policy = "write"
45 | }
46 |
--------------------------------------------------------------------------------