├── .gitignore ├── .travis.yml ├── README.md ├── pom.xml └── src ├── main └── java │ └── org │ └── kairosdb │ └── client │ ├── Client.java │ ├── ClientResponse.java │ ├── DataPointTypeRegistry.java │ ├── HttpClient.java │ ├── JsonMapper.java │ ├── TelnetClient.java │ ├── builder │ ├── AbstractQueryBuilder.java │ ├── Aggregator.java │ ├── AggregatorFactory.java │ ├── BuilderUtils.java │ ├── DataFormatException.java │ ├── DataPoint.java │ ├── Grouper.java │ ├── Metric.java │ ├── MetricBuilder.java │ ├── QueryBuilder.java │ ├── QueryMetric.java │ ├── QueryTagBuilder.java │ ├── QueryTagMetric.java │ ├── RelativeTime.java │ ├── Rollup.java │ ├── RollupBuilder.java │ ├── RollupTask.java │ ├── TimeUnit.java │ ├── TimeValidator.java │ ├── aggregator │ │ ├── CustomAggregator.java │ │ ├── DeserializedAggregator.java │ │ ├── PercentileAggregator.java │ │ ├── RateAggregator.java │ │ └── SamplingAggregator.java │ └── grouper │ │ ├── BinGrouper.java │ │ ├── CustomGrouper.java │ │ ├── TagGrouper.java │ │ ├── TimeGrouper.java │ │ └── ValueGrouper.java │ ├── deserializer │ ├── AggregatorDeserializer.java │ ├── GroupByDeserializer.java │ ├── GrouperDeserializer.java │ ├── ListMultiMapDeserializer.java │ ├── ResultsDeserializer.java │ └── TimeZoneDeserializer.java │ ├── response │ ├── DefaultJsonResponseHandler.java │ ├── ErrorResponse.java │ ├── Group.java │ ├── GroupResult.java │ ├── JsonResponseHandler.java │ ├── QueryResponse.java │ ├── QueryResult.java │ ├── QueryTagResponse.java │ ├── ResponseHelper.java │ ├── Result.java │ ├── TagQueryResult.java │ ├── TagResult.java │ ├── UnexpectedResponseException.java │ └── grouping │ │ ├── BinGroupResult.java │ │ ├── CustomGroupResult.java │ │ ├── DefaultGroupResult.java │ │ ├── GroupingNumber.java │ │ ├── TagGroupResult.java │ │ ├── TimeGroupResult.java │ │ └── ValueGroupResult.java │ ├── serializer │ ├── CustomAggregatorSerializer.java │ ├── CustomGrouperSerializer.java │ ├── DataPointSerializer.java │ ├── ListMultiMapSerializer.java │ ├── OrderSerializer.java │ └── TimeZoneSerializer.java │ └── util │ ├── Exceptions.java │ └── Preconditions.java └── test ├── java └── org │ └── kairosdb │ └── client │ ├── ClientIntegrationTest.java │ ├── ComplexNumberDataPoint.java │ ├── ComplexNumberDataPointFactory.java │ ├── CustomDataModule.java │ ├── HttpClientTest.java │ ├── InMemoryKairosServer.java │ ├── ListenerModule.java │ ├── TestDataPointListener.java │ ├── builder │ ├── AggregatorFactoryTest.java │ ├── CustomAggregatorTest.java │ ├── DataPointTest.java │ ├── MetricBuilderTest.java │ ├── MetricTest.java │ ├── QueryBuilderTest.java │ ├── QueryMetricTest.java │ ├── QueryTagBuilderTest.java │ ├── RollupBuilderTest.java │ ├── SamplingAggregatorTest.java │ ├── TimeValidatorTest.java │ ├── aggregator │ │ └── RateAggregatorTest.java │ └── grouper │ │ ├── BinGrouperTest.java │ │ ├── CustomGrouperTest.java │ │ ├── TagGrouperTest.java │ │ ├── TimeGrouperTest.java │ │ └── ValueGrouperTest.java │ ├── deserializer │ └── GroupByDeserializerTest.java │ ├── response │ ├── DefaultJsonResponseHandlerTest.java │ └── grouping │ │ ├── BinGroupResultTest.java │ │ ├── DefaultGroupResultTest.java │ │ ├── TagGroupResultTest.java │ │ ├── TimeGroupResultTest.java │ │ └── ValueGroupResultTest.java │ └── testUtils │ ├── MetricParser.java │ └── QueryParser.java └── resources ├── kairos.properties ├── logback.xml ├── multiple_metrics.json ├── query_multiple_metrics_relative_times.json ├── query_single_metric_absoluteStart_noEndTime_noTags.json ├── query_single_metric_aggregator_with_alignment.json ├── query_tag_response_valid.json ├── query_withGroupBys.json ├── query_withLimitAndOrder.json ├── query_withTimeZone.json ├── response_valid.json ├── rollup.json ├── rollupResponse.json ├── rollups.json └── ssl.jks /.gitignore: -------------------------------------------------------------------------------- 1 | *.ipr 2 | *.iws 3 | *.iml 4 | var/* 5 | target/* 6 | build/* 7 | */target/* 8 | .gradle/* 9 | out/* 10 | dependency.txt 11 | .tablesawcache 12 | .idea 13 | +.classpath 14 | +.project 15 | +.settings -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | language: java 4 | 5 | jdk: 6 | - oraclejdk8 7 | 8 | script: mvn -Dgpg.skip clean test 9 | 10 | install: /bin/true -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/Client.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import org.kairosdb.client.response.UnexpectedResponseException; 4 | import org.kairosdb.client.builder.*; 5 | import org.kairosdb.client.response.JsonResponseHandler; 6 | import org.kairosdb.client.response.QueryResponse; 7 | import org.kairosdb.client.response.QueryTagResponse; 8 | 9 | import java.io.Closeable; 10 | import java.util.List; 11 | 12 | public interface Client extends Closeable 13 | { 14 | /** 15 | * Create a new roll-up. 16 | * @param builder roll-up builder 17 | * @return newly created roll-up task 18 | * @throws UnexpectedResponseException if the operation fails 19 | */ 20 | RollupTask createRollupTask(RollupBuilder builder); 21 | 22 | /** 23 | * Delete the roll-up. Throws an exception if the delete fails. 24 | * @param id identifier of the roll-up 25 | * @throws UnexpectedResponseException if the operation fails 26 | */ 27 | void deleteRollupTask(String id); 28 | 29 | /** 30 | * Returns a list of all roll-up tasks. 31 | * @return list of roll-up tasks 32 | * @throws UnexpectedResponseException if the operation fails 33 | */ 34 | List getRollupTasks(); 35 | 36 | /** 37 | * Returns the roll-up. 38 | * @param id roll-up identifier 39 | * @return roll-up or null if no roll-ups match the specified identifier 40 | * @throws UnexpectedResponseException if the operation fails 41 | */ 42 | RollupTask getRollupTask(String id); 43 | 44 | /** 45 | * Returns a list of all metric names. 46 | * 47 | * @return list of all metric names 48 | * @throws UnexpectedResponseException if the operation fails 49 | */ 50 | Object getMetricNames(); 51 | 52 | /** 53 | * Returns status of Kairos Instance. 54 | * 55 | * @return status of Kairos instance 56 | * @throws UnexpectedResponseException if the operation fails 57 | */ 58 | List getStatus(); 59 | 60 | /** 61 | * Returns a status code fo 204 if all is healthy. 62 | * 63 | * @return status of Kairos instance 64 | * @throws UnexpectedResponseException if the operation fails 65 | */ 66 | int getStatusCheck(); 67 | 68 | /** 69 | * Queries KairosDB using the query built by the builder. 70 | * 71 | * @param builder query builder 72 | * @param handler response handler 73 | * @return query response 74 | * @throws UnexpectedResponseException if the operation fails 75 | */ 76 | T query(QueryBuilder builder, JsonResponseHandler handler); 77 | 78 | /** 79 | * Queries KairosDB using the query built by the builder. 80 | * 81 | * @param builder query builder 82 | * @return query response 83 | * @throws UnexpectedResponseException if the operation fails 84 | */ 85 | QueryResponse query(QueryBuilder builder); 86 | 87 | /** 88 | * Queries KairosDB tags using the query built by the builder. 89 | * 90 | * @param builder query tag builder 91 | * @return query response 92 | * @throws UnexpectedResponseException if the operation fails 93 | */ 94 | QueryTagResponse queryTags(QueryTagBuilder builder); 95 | 96 | /** 97 | * Queries KairosDB tags using the query built by the builder. 98 | * 99 | * @param builder query tag builder 100 | * @return query response 101 | * @throws UnexpectedResponseException if the operation fails 102 | */ 103 | T queryTags(QueryTagBuilder builder, JsonResponseHandler handler); 104 | 105 | /** 106 | * Sends metrics from the builder to the KairosDB server. 107 | * 108 | * @param builder metrics builder 109 | * @throws UnexpectedResponseException if the operation fails 110 | */ 111 | void pushMetrics(MetricBuilder builder); 112 | 113 | /** 114 | * Deletes a metric. This is the metric and all its data points. 115 | * An exception is thrown if this operation fails. 116 | * 117 | * @param name the metric to delete 118 | * @throws UnexpectedResponseException if the operation fails 119 | */ 120 | void deleteMetric(String name); 121 | 122 | /** 123 | * Deletes data in KairosDB using the query built by the builder. 124 | * An exception is thrown if this operation fails. 125 | * 126 | * @param builder query builder 127 | * @throws UnexpectedResponseException if the operation fails 128 | */ 129 | void delete(QueryBuilder builder); 130 | 131 | /** 132 | * Returns the version string for the KairosDB server. 133 | * @return KairosDB version 134 | */ 135 | String getVersion(); 136 | 137 | /** 138 | * Registers a new custom data type. The assumption is that this data type already exists on the server. The 139 | * dataPointValueClass is used to serialize and deserialize the custom type. This is simply a POJO. 140 | * 141 | * @param groupType type used to deserialize the json on the client 142 | * @param dataPointValueClass class that is the value of a data point 143 | */ 144 | void registerCustomDataType(String groupType, Class dataPointValueClass); 145 | 146 | /** 147 | * Returns the data point value class for the given group type or null if one is not registered for the group type 148 | * 149 | * @param groupType group type 150 | * @return data point class associated with the group type 151 | */ 152 | Class getDataPointValueClass(String groupType); 153 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/ClientResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client; 17 | 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | 21 | interface ClientResponse 22 | { 23 | int getStatusCode(); 24 | 25 | InputStream getContentStream() throws IOException; 26 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/DataPointTypeRegistry.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import static org.kairosdb.client.util.Preconditions.checkArgument; 7 | 8 | public class DataPointTypeRegistry 9 | { 10 | private Map customGroupTypes = new HashMap(); 11 | 12 | public DataPointTypeRegistry() 13 | { 14 | customGroupTypes.put("number", Number.class); 15 | customGroupTypes.put("text", String.class); 16 | } 17 | 18 | public void registerCustomDataType(String groupType, Class dataPointClass) 19 | { 20 | checkArgument(!customGroupTypes.containsKey(groupType), "Type has already been registered"); 21 | 22 | customGroupTypes.put(groupType, dataPointClass); 23 | } 24 | 25 | public Class getDataPointValueClass(String groupType) 26 | { 27 | Class valueClass = customGroupTypes.get(groupType); 28 | return valueClass == null? Number.class : valueClass; 29 | } 30 | 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/JsonMapper.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import com.google.common.collect.ListMultimap; 4 | import com.google.gson.Gson; 5 | import com.google.gson.GsonBuilder; 6 | import org.kairosdb.client.builder.Aggregator; 7 | import org.kairosdb.client.builder.Grouper; 8 | import org.kairosdb.client.deserializer.AggregatorDeserializer; 9 | import org.kairosdb.client.deserializer.GroupByDeserializer; 10 | import org.kairosdb.client.deserializer.GrouperDeserializer; 11 | import org.kairosdb.client.deserializer.ListMultiMapDeserializer; 12 | import org.kairosdb.client.deserializer.ResultsDeserializer; 13 | import org.kairosdb.client.deserializer.TimeZoneDeserializer; 14 | import org.kairosdb.client.response.GroupResult; 15 | import org.kairosdb.client.response.Result; 16 | 17 | import java.io.Reader; 18 | import java.lang.reflect.Type; 19 | import java.util.TimeZone; 20 | 21 | public class JsonMapper 22 | { 23 | private Gson mapper; 24 | 25 | public JsonMapper(DataPointTypeRegistry typeRegistry) 26 | { 27 | GsonBuilder builder = new GsonBuilder(); 28 | builder.registerTypeAdapter(GroupResult.class, new GroupByDeserializer()); 29 | builder.registerTypeAdapter(Result.class, new ResultsDeserializer(typeRegistry)); 30 | builder.registerTypeAdapter(ListMultimap.class, new ListMultiMapDeserializer()); 31 | builder.registerTypeAdapter(TimeZone.class, new TimeZoneDeserializer()); 32 | builder.registerTypeAdapter(Grouper.class, new GrouperDeserializer()); 33 | builder.registerTypeAdapter(Aggregator.class, new AggregatorDeserializer()); 34 | 35 | mapper = builder.create(); 36 | } 37 | 38 | public T fromJson(Reader json, Type typeOfT) 39 | { 40 | return mapper.fromJson(json, typeOfT); 41 | } 42 | 43 | public T fromJson(String json, Type typeOfT) 44 | { 45 | return mapper.fromJson(json, typeOfT); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/TelnetClient.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import org.kairosdb.client.builder.*; 4 | 5 | import java.io.BufferedOutputStream; 6 | import java.io.IOException; 7 | import java.io.PrintWriter; 8 | import java.net.Socket; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | /** 13 | * Communicates with KairosDB using the Telnet protocol. Only pushing of metrics is supported. Querying must be done 14 | * using the HTTP client. 15 | * 16 | * The socket is opened in the constructor and left open until the close() method is called. Note that no response is 17 | * returned. This allows data to flow more quickly. If you need to guarantee arrival of metrics then use the HTTP 18 | * client. 19 | */ 20 | public class TelnetClient 21 | { 22 | private Socket socket; 23 | private PrintWriter writer; 24 | 25 | public TelnetClient(String host, int port) throws IOException 26 | { 27 | socket = new Socket(host, port); 28 | writer = new PrintWriter(new BufferedOutputStream(socket.getOutputStream())); 29 | } 30 | 31 | /** 32 | * @deprecated As of KairosDB 1.0, use putMetrics. PutMetrics uses putm rather 33 | * than put. 34 | * 35 | * Sends metrics from the builder to the Kairos server. 36 | * 37 | * @param builder metrics builder 38 | */ 39 | @Deprecated 40 | public void pushMetrics(MetricBuilder builder) 41 | { 42 | List metrics = builder.getMetrics(); 43 | for (Metric metric : metrics) 44 | { 45 | StringBuilder tags = new StringBuilder(); 46 | for (Map.Entry tag : metric.getTags().entrySet()) 47 | { 48 | tags.append(" ").append(tag.getKey()).append("=").append(tag.getValue()); 49 | } 50 | 51 | for (DataPoint dataPoint : metric.getDataPoints()) 52 | { 53 | StringBuilder sb = new StringBuilder(); 54 | sb.append("put ").append(metric.getName()).append(" ") 55 | .append(dataPoint.getTimestamp()).append(" ") 56 | .append(dataPoint.getValue()) 57 | .append(tags.toString()); 58 | 59 | writer.println(sb.toString()); 60 | } 61 | } 62 | writer.flush(); 63 | } 64 | 65 | public void putMetrics(MetricBuilder builder) 66 | { 67 | List metrics = builder.getMetrics(); 68 | for (Metric metric : metrics) 69 | { 70 | StringBuilder tags = new StringBuilder(); 71 | for (Map.Entry tag : metric.getTags().entrySet()) 72 | { 73 | tags.append(" ").append(tag.getKey()).append("=").append(tag.getValue()); 74 | } 75 | 76 | for (DataPoint dataPoint : metric.getDataPoints()) 77 | { 78 | StringBuilder sb = new StringBuilder(); 79 | sb.append("putm ").append(metric.getName()).append(" ") 80 | .append(dataPoint.getTimestamp()).append(" ") 81 | .append(dataPoint.getValue()) 82 | .append(tags.toString()); 83 | 84 | writer.println(sb.toString()); 85 | } 86 | } 87 | writer.flush(); 88 | } 89 | 90 | /** 91 | * Closes the socket. 92 | * 93 | * @throws IOException if the socket could not be closed. 94 | */ 95 | public void shutdown() throws IOException 96 | { 97 | socket.close(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/AbstractQueryBuilder.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.annotations.SerializedName; 5 | 6 | import java.util.Date; 7 | 8 | import static java.util.Objects.requireNonNull; 9 | import static org.kairosdb.client.util.Preconditions.checkArgument; 10 | 11 | /** 12 | * Abstract class for querying KairosDB. 13 | * @param the builder 14 | */ 15 | public abstract class AbstractQueryBuilder> 16 | { 17 | @SerializedName("start_absolute") 18 | Long startAbsolute; 19 | 20 | @SerializedName("end_absolute") 21 | Long endAbsolute; 22 | 23 | @SerializedName("start_relative") 24 | RelativeTime startRelative; 25 | 26 | @SerializedName("end_relative") 27 | RelativeTime endRelative; 28 | 29 | private transient Gson mapper; 30 | 31 | AbstractQueryBuilder() 32 | { 33 | mapper = buildGson(); 34 | } 35 | 36 | /** 37 | * Builds Gson used by this implementation 38 | */ 39 | protected abstract Gson buildGson(); 40 | 41 | /** 42 | * Returns the absolute range start time. 43 | * 44 | * @return absolute range start time 45 | */ 46 | @SuppressWarnings("WeakerAccess") 47 | public Date getStartAbsolute() 48 | { 49 | return new Date(startAbsolute); 50 | } 51 | 52 | /** 53 | * Returns the absolute range end time. 54 | * 55 | * @return absolute range end time 56 | */ 57 | @SuppressWarnings("WeakerAccess") 58 | public Date getEndAbsolute() 59 | { 60 | return new Date(endAbsolute); 61 | } 62 | 63 | /** 64 | * Returns the relative range start time. 65 | * 66 | * @return relative range start time 67 | */ 68 | @SuppressWarnings("WeakerAccess") 69 | public RelativeTime getStartRelative() 70 | { 71 | return startRelative; 72 | } 73 | 74 | /** 75 | * Returns the relative range end time. 76 | * 77 | * @return relative range end time 78 | */ 79 | @SuppressWarnings("unused") 80 | public RelativeTime getEndRelative() 81 | { 82 | return endRelative; 83 | } 84 | 85 | /** 86 | * The beginning time of the time range. 87 | * 88 | * @param start start time 89 | * @return the builder 90 | */ 91 | @SuppressWarnings({"unchecked", "ConstantConditions"}) 92 | public B setStart(Date start) 93 | { 94 | requireNonNull(start, "start cannot be null"); 95 | checkArgument(startRelative == null, "Both relative and absolute start times cannot be set."); 96 | 97 | this.startAbsolute = start.getTime(); 98 | return (B) this; 99 | } 100 | 101 | /** 102 | * The beginning time of the time range relative to now. For example, return all data points that starting 2 days 103 | * ago. 104 | * 105 | * @param duration relative time value 106 | * @param unit unit of time 107 | * @return the builder 108 | */ 109 | @SuppressWarnings({"unchecked", "ConstantConditions"}) 110 | public B setStart(int duration, TimeUnit unit) 111 | { 112 | checkArgument(duration > 0, "duration must be greater than 0"); 113 | requireNonNull(unit, "unit cannot be null"); 114 | checkArgument(startAbsolute == null, "Both relative and absolute start times cannot be set."); 115 | 116 | startRelative = new RelativeTime(duration, unit); 117 | return (B) this; 118 | } 119 | 120 | /** 121 | * The ending value of the time range. Must be later in time than the start time. An end time is not required 122 | * and default to now. 123 | * 124 | * @param end end time 125 | * @return the builder 126 | */ 127 | @SuppressWarnings({"unchecked", "WeakerAccess"}) 128 | public B setEnd(Date end) 129 | { 130 | checkArgument(endRelative == null, "Both relative and absolute end times cannot be set."); 131 | this.endAbsolute = end.getTime(); 132 | return (B) this; 133 | } 134 | 135 | /** 136 | * The ending time of the time range relative to now. 137 | * 138 | * @param duration relative time value 139 | * @param unit unit of time 140 | * @return the builder 141 | */ 142 | @SuppressWarnings({"unchecked", "ConstantConditions", "WeakerAccess"}) 143 | public B setEnd(int duration, TimeUnit unit) 144 | { 145 | requireNonNull(unit, "unit cannot be null"); 146 | checkArgument(duration > 0, "duration must be greater than 0"); 147 | checkArgument(endAbsolute == null, "Both relative and absolute end times cannot be set."); 148 | endRelative = new RelativeTime(duration, unit); 149 | return (B) this; 150 | } 151 | 152 | 153 | /** 154 | * Returns the JSON string built by the builder. This is the JSON that can be used by the client to query KairosDB 155 | * 156 | * @return JSON 157 | */ 158 | public String build() 159 | { 160 | validate(); 161 | return mapper.toJson(this); 162 | } 163 | 164 | void validate() 165 | { 166 | BuilderUtils.validateTimes(startAbsolute, endAbsolute, startRelative, endRelative); 167 | } 168 | 169 | @SuppressWarnings("SimplifiableIfStatement") 170 | @Override 171 | public boolean equals(Object o) 172 | { 173 | if (this == o) 174 | return true; 175 | if (o == null || getClass() != o.getClass()) 176 | return false; 177 | 178 | AbstractQueryBuilder that = (AbstractQueryBuilder) o; 179 | 180 | if (startAbsolute != null ? !startAbsolute.equals(that.startAbsolute) : that.startAbsolute != null) 181 | return false; 182 | if (endAbsolute != null ? !endAbsolute.equals(that.endAbsolute) : that.endAbsolute != null) 183 | return false; 184 | if (startRelative != null ? !startRelative.equals(that.startRelative) : that.startRelative != null) 185 | return false; 186 | return endRelative != null ? endRelative.equals(that.endRelative) : that.endRelative == null; 187 | } 188 | 189 | @Override 190 | public int hashCode() 191 | { 192 | int result = startAbsolute != null ? startAbsolute.hashCode() : 0; 193 | result = 31 * result + (endAbsolute != null ? endAbsolute.hashCode() : 0); 194 | result = 31 * result + (startRelative != null ? startRelative.hashCode() : 0); 195 | result = 31 * result + (endRelative != null ? endRelative.hashCode() : 0); 196 | return result; 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/Aggregator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import java.util.Objects; 19 | 20 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 21 | 22 | /** 23 | * An aggregator manipulates data points. For example, a sum aggregator would add data points together. 24 | */ 25 | public class Aggregator 26 | { 27 | private String name; 28 | 29 | protected Aggregator(String name) 30 | { 31 | this.name = checkNotNullOrEmpty(name); 32 | } 33 | 34 | /** 35 | * Returns the aggregator's name. 36 | * @return aggregator name 37 | */ 38 | public String getName() 39 | { 40 | return name; 41 | } 42 | 43 | @Override 44 | public boolean equals(Object o) 45 | { 46 | if (this == o) return true; 47 | if (o == null || getClass() != o.getClass()) return false; 48 | Aggregator that = (Aggregator) o; 49 | return Objects.equals(name, that.name); 50 | } 51 | 52 | @Override 53 | public int hashCode() 54 | { 55 | return Objects.hash(name); 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/BuilderUtils.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import static org.kairosdb.client.util.Preconditions.checkState; 4 | 5 | public class BuilderUtils 6 | { 7 | private BuilderUtils() 8 | { 9 | } 10 | 11 | public static void validateTimes(Long startAbsolute, Long endAbsolute, RelativeTime startRelative, RelativeTime endRelative) 12 | { 13 | checkState(startAbsolute != null || startRelative != null, "Start time must be specified"); 14 | 15 | if (endAbsolute != null) 16 | { 17 | if (startAbsolute != null) 18 | TimeValidator.validateEndTimeLaterThanStartTime(startAbsolute, endAbsolute); 19 | else 20 | TimeValidator.validateEndTimeLaterThanStartTime(startRelative, endAbsolute); 21 | } 22 | else if (endRelative != null) 23 | { 24 | if (startAbsolute != null) 25 | TimeValidator.validateEndTimeLaterThanStartTime(startAbsolute, endRelative); 26 | else 27 | TimeValidator.validateEndTimeLaterThanStartTime(startRelative, endRelative); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/DataFormatException.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | public class DataFormatException extends Exception 4 | { 5 | public DataFormatException() 6 | { 7 | super(); 8 | } 9 | 10 | public DataFormatException(String s) 11 | { 12 | super(s); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/DataPoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import java.util.Objects; 19 | 20 | /** 21 | * A measurement. Contains the time when the measurement occurred and its value. 22 | */ 23 | public class DataPoint 24 | { 25 | private long timestamp; 26 | private Object value; 27 | 28 | public DataPoint(long timestamp, Object value) 29 | { 30 | this.timestamp = timestamp; 31 | this.value = value; 32 | } 33 | 34 | /** 35 | * Time when the data point was measured. 36 | * 37 | * @return time when the data point was measured 38 | */ 39 | public long getTimestamp() 40 | { 41 | return timestamp; 42 | } 43 | 44 | public Object getValue() 45 | { 46 | return value; 47 | } 48 | 49 | public String stringValue() throws DataFormatException 50 | { 51 | if (value == null) 52 | { 53 | throw new DataFormatException("Value is not a string"); 54 | } 55 | return value.toString(); 56 | } 57 | 58 | public long longValue() throws DataFormatException 59 | { 60 | try 61 | { 62 | return ((Number)value).longValue(); 63 | } 64 | catch (Exception e) 65 | { 66 | throw new DataFormatException("Value is not a long"); 67 | } 68 | } 69 | 70 | public double doubleValue() throws DataFormatException 71 | { 72 | try 73 | { 74 | return ((Number)value).doubleValue(); 75 | } 76 | catch (Exception e) 77 | { 78 | throw new DataFormatException("Value is not a double"); 79 | } 80 | } 81 | 82 | public boolean isDoubleValue() 83 | { 84 | return value != null && !(((Number) value).doubleValue() == Math.floor(((Number) value).doubleValue())); 85 | } 86 | 87 | public boolean isIntegerValue() 88 | { 89 | return value != null && ((Number) value).doubleValue() == Math.floor(((Number) value).doubleValue()); 90 | } 91 | 92 | @Override 93 | public String toString() 94 | { 95 | return "DataPoint{" + 96 | "timestamp=" + timestamp + 97 | ", value=" + value + 98 | '}'; 99 | } 100 | 101 | @Override 102 | public boolean equals(Object o) 103 | { 104 | if (this == o) return true; 105 | if (o == null || getClass() != o.getClass()) return false; 106 | DataPoint dataPoint = (DataPoint) o; 107 | return timestamp == dataPoint.timestamp && Objects.equals(value, dataPoint.value); 108 | } 109 | 110 | @Override 111 | public int hashCode() 112 | { 113 | return Objects.hash(timestamp, value); 114 | } 115 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/Grouper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 19 | 20 | /** 21 | * Specifies how data is grouped. This is used by the JSON parser to deserialize a JSON response. 22 | */ 23 | public abstract class Grouper 24 | { 25 | private String name; 26 | 27 | protected Grouper(String name) 28 | { 29 | this.name = checkNotNullOrEmpty(name); 30 | } 31 | 32 | /** 33 | * Returns the name of the group by. 34 | * @return group by name 35 | */ 36 | public String getName() 37 | { 38 | return name; 39 | } 40 | 41 | @Override 42 | public boolean equals(Object o) 43 | { 44 | if (this == o) 45 | return true; 46 | if (o == null || getClass() != o.getClass()) 47 | return false; 48 | 49 | Grouper grouper = (Grouper) o; 50 | return name.equals(grouper.name); 51 | } 52 | 53 | @Override 54 | public int hashCode() 55 | { 56 | return name.hashCode(); 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/Metric.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import com.google.gson.annotations.SerializedName; 19 | 20 | import java.util.*; 21 | 22 | import static java.util.Objects.requireNonNull; 23 | import static org.kairosdb.client.util.Preconditions.checkArgument; 24 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 25 | 26 | /** 27 | * A metric contains measurements or data points. Each data point has a time stamp of when the measurement occurred 28 | * and a value that is either a long or double and optionally contains tags. Tags are labels that can be added to better 29 | * identify the metric. For example, if the measurement was done on server1 then you might add a tag named "host" 30 | * with a value of "server1". Note that a metric must have at least one tag. 31 | */ 32 | public class Metric 33 | { 34 | private String name; 35 | private Map tags = new HashMap(); 36 | private String type; 37 | private int ttl; 38 | 39 | @SerializedName("datapoints") 40 | private List dataPoints = new ArrayList(); 41 | 42 | protected Metric(String name) 43 | { 44 | this.name = checkNotNullOrEmpty(name); 45 | } 46 | 47 | protected Metric(String name, String registeredType) 48 | { 49 | this(name); 50 | type = registeredType; 51 | } 52 | 53 | /** 54 | * Adds a tag to the data point. 55 | * 56 | * @param name tag identifier 57 | * @param value tag value 58 | * @return the metric the tag was added to 59 | */ 60 | public Metric addTag(String name, String value) 61 | { 62 | checkNotNullOrEmpty(name); 63 | checkNotNullOrEmpty(value); 64 | tags.put(name, value); 65 | 66 | return this; 67 | } 68 | 69 | /** 70 | * Adds tags to the data point. 71 | * @param tags map of tags 72 | * @return the metric the tags were added to 73 | */ 74 | public Metric addTags(Map tags) 75 | { 76 | requireNonNull(tags); 77 | this.tags.putAll(tags); 78 | 79 | return this; 80 | } 81 | 82 | /** 83 | * Adds the data point to the metric. 84 | * 85 | * @param timestamp when the measurement occurred 86 | * @param value the measurement value 87 | * @return the metric 88 | */ 89 | public Metric addDataPoint(long timestamp, long value) 90 | { 91 | dataPoints.add(new DataPoint(timestamp, value)); 92 | return this; 93 | } 94 | 95 | /** 96 | * Adds the data point to the metric with a timestamp of now. 97 | * 98 | * @param value the measurement value 99 | * @return the metric 100 | */ 101 | public Metric addDataPoint(long value) 102 | { 103 | return addDataPoint(System.currentTimeMillis(), value); 104 | } 105 | 106 | public Metric addDataPoint(long timestamp, Object value) 107 | { 108 | dataPoints.add(new DataPoint(timestamp, value)); 109 | return this; 110 | } 111 | 112 | /** 113 | * Adds the data point to the metric. 114 | * 115 | * @param timestamp when the measurement occurred 116 | * @param value the measurement value 117 | * @return the metric 118 | */ 119 | public Metric addDataPoint(long timestamp, double value) 120 | { 121 | dataPoints.add(new DataPoint(timestamp, value)); 122 | return this; 123 | } 124 | 125 | /** 126 | * Adds the data point to the metric with a timestamp of now. 127 | * 128 | * @param value the measurement value 129 | * @return the metric 130 | */ 131 | public Metric addDataPoint(double value) 132 | { 133 | return addDataPoint(System.currentTimeMillis(), value); 134 | } 135 | 136 | /** 137 | * Adds a time-to-live for this metric specified in seconds. TTL is off by 138 | * default. Setting ttl to 0 turns it off. 139 | * 140 | * @param ttl number of seconds that the metric will live 141 | * @return the metric 142 | */ 143 | public Metric addTtl(int ttl) 144 | { 145 | checkArgument(ttl >= 0, "tll must be greater than or equal to zero"); 146 | this.ttl = ttl; 147 | return this; 148 | } 149 | 150 | /** 151 | * Returns the time-to-live. If zero, the metric lives forever. 152 | * @return time to live 153 | */ 154 | public int getTtl() 155 | { 156 | return ttl; 157 | } 158 | 159 | public List getDataPoints() 160 | { 161 | return Collections.unmodifiableList(dataPoints); 162 | } 163 | 164 | /** 165 | * Returns the metric name. 166 | * 167 | * @return metric name 168 | */ 169 | public String getName() 170 | { 171 | return name; 172 | } 173 | 174 | /** 175 | * Returns the tags associated with the data point. 176 | * 177 | * @return tag for the data point 178 | */ 179 | public Map getTags() 180 | { 181 | return Collections.unmodifiableMap(tags); 182 | } 183 | 184 | /** 185 | * Returns the custom type name. Null if the type is a number. 186 | * 187 | * @return custom type name 188 | */ 189 | public String getType() 190 | { 191 | return type; 192 | } 193 | 194 | 195 | @Override 196 | public boolean equals(Object o) 197 | { 198 | if (this == o) return true; 199 | if (o == null || getClass() != o.getClass()) return false; 200 | Metric metric = (Metric) o; 201 | return ttl == metric.ttl && Objects.equals(name, metric.name) && Objects.equals(tags, metric.tags) && Objects.equals(type, metric.type) && Objects.equals(dataPoints, metric.dataPoints); 202 | } 203 | 204 | @Override 205 | public int hashCode() 206 | { 207 | return Objects.hash(name, tags, type, ttl, dataPoints); 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/MetricBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import com.google.gson.Gson; 19 | import com.google.gson.GsonBuilder; 20 | import org.kairosdb.client.builder.aggregator.CustomAggregator; 21 | import org.kairosdb.client.builder.grouper.CustomGrouper; 22 | import org.kairosdb.client.serializer.CustomAggregatorSerializer; 23 | import org.kairosdb.client.serializer.CustomGrouperSerializer; 24 | import org.kairosdb.client.serializer.DataPointSerializer; 25 | 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | import static org.kairosdb.client.util.Preconditions.checkState; 30 | 31 | /** 32 | * Builder used to create the JSON to push metrics to KairosDB. 33 | */ 34 | public class MetricBuilder 35 | { 36 | private List metrics = new ArrayList<>(); 37 | private transient Gson mapper; 38 | private boolean useCompression = false; 39 | 40 | private MetricBuilder() 41 | { 42 | GsonBuilder builder = new GsonBuilder(); 43 | builder.registerTypeAdapter(CustomAggregator.class, new CustomAggregatorSerializer()); 44 | builder.registerTypeAdapter(CustomGrouper.class, new CustomGrouperSerializer()); 45 | builder.registerTypeAdapter(DataPoint.class, new DataPointSerializer()); 46 | mapper = builder.create(); 47 | } 48 | 49 | /** 50 | * Returns a new metric builder. 51 | * 52 | * @return metric builder 53 | */ 54 | public static MetricBuilder getInstance() 55 | { 56 | return new MetricBuilder(); 57 | } 58 | 59 | /** 60 | * Adds a metric to the builder. 61 | * 62 | * @param metricName metric name 63 | * @return the new metric 64 | */ 65 | public Metric addMetric(String metricName) 66 | { 67 | Metric metric = new Metric(metricName); 68 | metrics.add(metric); 69 | return metric; 70 | } 71 | 72 | /** 73 | * Adds a metric to the builder with a customer type. 74 | * 75 | * @param metricName metric name 76 | * @param registeredType type used to deserialize the json on the server 77 | * @return the new metric 78 | */ 79 | public Metric addMetric(String metricName, String registeredType) 80 | { 81 | Metric metric = new Metric(metricName, registeredType); 82 | metrics.add(metric); 83 | return metric; 84 | } 85 | 86 | /** 87 | * Returns a list of metrics added to the builder. 88 | * 89 | * @return list of metrics 90 | */ 91 | public List getMetrics() 92 | { 93 | return metrics; 94 | } 95 | 96 | /** 97 | * Sets the compression flag for http post. 98 | * @param compressionEnabled compresss post data 99 | */ 100 | @SuppressWarnings("WeakerAccess") 101 | public void setCompression(boolean compressionEnabled) 102 | { 103 | useCompression = compressionEnabled; 104 | } 105 | 106 | /** 107 | * Returns the compression flag 108 | * @return return whether compression is being used 109 | */ 110 | public boolean isCompressionEnabled() { return useCompression; } 111 | 112 | /** 113 | * Returns the JSON string built by the builder. This is the JSON that can be used by the client add metrics. 114 | * 115 | * @return JSON 116 | */ 117 | public String build() 118 | { 119 | for (Metric metric : metrics) 120 | { 121 | // verify that there is at least one tag for each metric 122 | checkState(metric.getTags().size() > 0, metric.getName() + " must contain at least one tag."); 123 | } 124 | return mapper.toJson(metrics); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/QueryBuilder.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.common.collect.ListMultimap; 4 | import com.google.gson.Gson; 5 | import com.google.gson.GsonBuilder; 6 | import com.google.gson.annotations.SerializedName; 7 | import org.kairosdb.client.builder.aggregator.CustomAggregator; 8 | import org.kairosdb.client.builder.grouper.CustomGrouper; 9 | import org.kairosdb.client.serializer.*; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.TimeZone; 14 | 15 | import static java.util.Objects.requireNonNull; 16 | import static org.kairosdb.client.util.Preconditions.checkArgument; 17 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 18 | 19 | /** 20 | * Builder used to create the JSON to query KairosDB. 21 | *
22 | *
23 | * The query returns the data points for the given metrics for the specified time range. The time range can 24 | * be specified as absolute or relative. Absolute times are a given point in time. Relative times are relative to now. 25 | * The end time is not required and defaults to now. 26 | *
27 | *
28 | * For example, if you specify a relative start time of 30 minutes, all matching data points for the last 30 minutes 29 | * will be returned. If you specify a relative start time of 30 minutes and a relative end time of 10 minutes, then 30 | * all matching data points that occurred between the last 30 minutes up to and including the last 10 minutes are returned. 31 | */ 32 | @SuppressWarnings("UnusedDeclaration") 33 | public class QueryBuilder extends AbstractQueryBuilder 34 | { 35 | @SerializedName("cache_time") 36 | private int cacheTime; 37 | 38 | @SerializedName("time_zone") 39 | private TimeZone timeZone; 40 | 41 | private List metrics = new ArrayList<>(); 42 | 43 | private QueryBuilder() 44 | { 45 | super(); 46 | } 47 | 48 | @Override 49 | protected Gson buildGson() 50 | { 51 | GsonBuilder builder = new GsonBuilder(); 52 | builder.registerTypeAdapter(CustomAggregator.class, new CustomAggregatorSerializer()); 53 | builder.registerTypeAdapter(CustomGrouper.class, new CustomGrouperSerializer()); 54 | builder.registerTypeAdapter(ListMultimap.class, new ListMultiMapSerializer()); 55 | builder.registerTypeAdapter(QueryMetric.Order.class, new OrderSerializer()); 56 | builder.registerTypeAdapter(TimeZone.class, new TimeZoneSerializer()); 57 | 58 | return builder.create(); 59 | } 60 | 61 | /** 62 | * How long to cache this exact query. The default is to never cache. 63 | * 64 | * @param cacheTime cache time in milliseconds 65 | * @return the builder 66 | */ 67 | public QueryBuilder setCacheTime(int cacheTime) 68 | { 69 | checkArgument(cacheTime > 0, "Cache time must be greater than 0."); 70 | this.cacheTime = cacheTime; 71 | return this; 72 | } 73 | 74 | /** 75 | * Adds a QueryMetric object to the QueryBuilder 76 | * 77 | * @param metric a QueryMetric object 78 | * @return the builder 79 | */ 80 | public QueryMetric addMetric(QueryMetric metric) 81 | { 82 | requireNonNull(metric,"metric cannot be null"); 83 | metrics.add(metric); 84 | return metric; 85 | } 86 | 87 | 88 | /** 89 | * Returns a new query builder. 90 | * 91 | * @return new query builder 92 | */ 93 | public static QueryBuilder getInstance() 94 | { 95 | return new QueryBuilder(); 96 | } 97 | 98 | /** 99 | * The metric to query for. 100 | * 101 | * @param name metric name 102 | * @return the builder 103 | */ 104 | public QueryMetric addMetric(String name) 105 | { 106 | checkNotNullOrEmpty(name, "Name cannot be null or empty."); 107 | 108 | QueryMetric metric = new QueryMetric(name); 109 | metrics.add(metric); 110 | return metric; 111 | } 112 | 113 | /** 114 | * Returns the cache time. 115 | * 116 | * @return cache time 117 | */ 118 | public int getCacheTime() 119 | { 120 | return cacheTime; 121 | } 122 | 123 | /** 124 | * Returns the list metrics to query for. 125 | * 126 | * @return metrics 127 | */ 128 | public List getMetrics() 129 | { 130 | return metrics; 131 | } 132 | 133 | /** 134 | * Returns the time zone. The default time zone is UTC. 135 | * 136 | * @return time zone 137 | */ 138 | public TimeZone getTimeZone() 139 | { 140 | if (timeZone == null) 141 | return TimeZone.getTimeZone("UTC"); 142 | return timeZone; 143 | } 144 | 145 | @SuppressWarnings("ConstantConditions") 146 | public QueryBuilder setTimeZone(TimeZone timeZone) 147 | { 148 | requireNonNull(timeZone, "timezone cannot be null"); 149 | 150 | this.timeZone = timeZone; 151 | return this; 152 | } 153 | 154 | @Override 155 | public boolean equals(Object o) 156 | { 157 | if (this == o) { 158 | return true; 159 | } 160 | if (o == null || getClass() != o.getClass()) { 161 | return false; 162 | } 163 | if (!super.equals(o)) { 164 | return false; 165 | } 166 | 167 | QueryBuilder that = (QueryBuilder) o; 168 | 169 | if (cacheTime != that.cacheTime) { 170 | return false; 171 | } 172 | if (timeZone == null) 173 | { 174 | if (that.timeZone != null) 175 | { 176 | return false; 177 | } 178 | } else if (!timeZone.equals(that.timeZone)) 179 | { 180 | return false; 181 | } 182 | return metrics.equals(that.metrics); 183 | } 184 | 185 | @Override 186 | public int hashCode() 187 | { 188 | int result = super.hashCode(); 189 | result = 31 * result + cacheTime; 190 | result = 31 * result + timeZone.hashCode(); 191 | result = 31 * result + metrics.hashCode(); 192 | return result; 193 | } 194 | 195 | @Override 196 | public String toString() 197 | { 198 | return "QueryBuilder{" + 199 | "cacheTime=" + cacheTime + 200 | ", timeZone=" + timeZone + 201 | ", metrics=" + metrics + 202 | ", startAbsolute=" + startAbsolute + 203 | ", endAbsolute=" + endAbsolute + 204 | ", startRelative=" + startRelative + 205 | ", endRelative=" + endRelative + 206 | '}'; 207 | } 208 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/QueryTagBuilder.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.common.collect.ListMultimap; 4 | import com.google.gson.Gson; 5 | import com.google.gson.GsonBuilder; 6 | import org.kairosdb.client.serializer.ListMultiMapSerializer; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 12 | 13 | /** 14 | * Builder used to create the JSON to query tags from KairosDB. 15 | *
16 | *
17 | * This is similar to a regular query but just returns the tags (no data points) 18 | * for the range specified. The time range can be specified as absolute or relative. 19 | * Absolute times are a given point in time. Relative times are relative to now. 20 | * The end time is not required and defaults to now. 21 | *
22 | *
23 | * For example, if you specify a relative start time of 30 minutes, all matching data points for the last 30 minutes 24 | * will be returned. If you specify a relative start time of 30 minutes and a relative end time of 10 minutes, then 25 | * all matching data points that occurred between the last 30 minutes up to and including the last 10 minutes are returned. 26 | */ 27 | public class QueryTagBuilder extends AbstractQueryBuilder 28 | { 29 | private List metrics = new ArrayList(); 30 | 31 | private QueryTagBuilder() 32 | { 33 | super(); 34 | } 35 | 36 | @Override 37 | protected Gson buildGson() 38 | { 39 | GsonBuilder builder = new GsonBuilder(); 40 | builder.registerTypeAdapter(ListMultimap.class, new ListMultiMapSerializer()); 41 | return builder.create(); 42 | } 43 | 44 | /** 45 | * Returns a new query tag builder. 46 | * 47 | * @return new query tag builder 48 | */ 49 | public static QueryTagBuilder getInstance() 50 | { 51 | return new QueryTagBuilder(); 52 | } 53 | 54 | /** 55 | * The metric to query tag for. 56 | * 57 | * @param name metric name 58 | * @return the builder 59 | */ 60 | public QueryTagMetric addMetric(String name) 61 | { 62 | checkNotNullOrEmpty(name, "Name cannot be null or empty."); 63 | 64 | QueryTagMetric metric = new QueryTagMetric(name); 65 | metrics.add(metric); 66 | return metric; 67 | } 68 | 69 | /** 70 | * Returns the list metrics to query for tags. 71 | * 72 | * @return metrics 73 | */ 74 | public List getMetrics() 75 | { 76 | return metrics; 77 | } 78 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/QueryTagMetric.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.common.collect.ArrayListMultimap; 4 | import com.google.common.collect.ListMultimap; 5 | 6 | import java.util.Arrays; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | import static java.util.Objects.requireNonNull; 11 | import static org.kairosdb.client.util.Preconditions.checkArgument; 12 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 13 | 14 | /** 15 | * Query request for tags. You can narrow down the query by adding tags. 16 | * Only metrics that include the tag and matches one of the values are returned. 17 | */ 18 | public class QueryTagMetric 19 | { 20 | @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 21 | private final String name; 22 | 23 | private final ListMultimap tags = ArrayListMultimap.create(); 24 | 25 | public QueryTagMetric(String name) 26 | { 27 | this.name = checkNotNullOrEmpty(name, "name cannot be null or empty"); 28 | } 29 | 30 | /** 31 | * Add a map of tags. This narrows the query to only show metadata associated with the tags' values. 32 | * 33 | * @param tags tags to add 34 | * @return the metric 35 | */ 36 | public QueryTagMetric addTags(Map tags) 37 | { 38 | requireNonNull(tags); 39 | 40 | for (String key : tags.keySet()) 41 | { 42 | this.tags.put(key, tags.get(key)); 43 | } 44 | 45 | return this; 46 | } 47 | 48 | /** 49 | * Adds a tag with multiple values. This narrows the query to only show metadata associated with the tag's values. 50 | * 51 | * @param name tag name 52 | * @param values tag values 53 | * @return the metric 54 | */ 55 | public QueryTagMetric addTag(String name, String... values) 56 | { 57 | checkNotNullOrEmpty(name, "name cannot be null or empty"); 58 | checkArgument(values.length > 0, "value must be greater than 0"); 59 | 60 | for (String value : values) 61 | { 62 | checkNotNullOrEmpty(value, "value cannot be null or empty"); 63 | } 64 | 65 | tags.putAll(name, Arrays.asList(values)); 66 | 67 | return (this); 68 | } 69 | 70 | public QueryTagMetric addTag(String name, Set values) 71 | { 72 | checkNotNullOrEmpty(name, "name cannot be null or empty"); 73 | checkArgument(values.size() > 0, "value must be greater than 0"); 74 | 75 | for (String value : values) 76 | { 77 | checkNotNullOrEmpty(value, "value cannot be null or empty"); 78 | } 79 | 80 | tags.putAll(name, values); 81 | 82 | return (this); 83 | } 84 | 85 | public String getName() 86 | { 87 | return name; 88 | } 89 | 90 | public ListMultimap getTags() 91 | { 92 | return tags; 93 | } 94 | 95 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/RelativeTime.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import java.util.Calendar; 19 | import java.util.Objects; 20 | import java.util.StringJoiner; 21 | import java.util.TimeZone; 22 | 23 | /** 24 | * A time unit relative to now. 25 | */ 26 | public class RelativeTime 27 | { 28 | private int value; 29 | private TimeUnit unit; 30 | private transient Calendar calendar; 31 | 32 | public RelativeTime() 33 | { //used by gson 34 | calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); 35 | } 36 | 37 | public RelativeTime(int value, TimeUnit unit) 38 | { 39 | this.value = value; 40 | this.unit = unit; 41 | calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); 42 | } 43 | 44 | /** 45 | * The time's value. 46 | * 47 | * @return time value 48 | */ 49 | public int getValue() 50 | { 51 | return value; 52 | } 53 | 54 | /** 55 | * The unit of time. 56 | * 57 | * @return time unit 58 | */ 59 | public String getUnit() 60 | { 61 | return unit.toString(); 62 | } 63 | 64 | /** 65 | * Returns the time in milliseconds relative to the specified time. For example, if this object is set to 3 days, 66 | * this method returns 3 days from time. 67 | * 68 | * @param time time to calculate the relative time. 69 | * @return time in milliseconds relative to the specified time 70 | */ 71 | @SuppressWarnings("MagicConstant") 72 | public long getTimeRelativeTo(long time) 73 | { 74 | int field = 0; 75 | if (unit == TimeUnit.SECONDS) 76 | { 77 | field = Calendar.SECOND; 78 | } 79 | else if (unit == TimeUnit.MINUTES) 80 | { 81 | field = Calendar.MINUTE; 82 | } 83 | else if (unit == TimeUnit.HOURS) 84 | { 85 | field = Calendar.HOUR; 86 | } 87 | else if (unit == TimeUnit.DAYS) 88 | { 89 | field = Calendar.DATE; 90 | } 91 | else if (unit == TimeUnit.WEEKS) 92 | { 93 | field = Calendar.WEEK_OF_MONTH; 94 | } 95 | else if (unit == TimeUnit.MONTHS) 96 | { 97 | field = Calendar.MONTH; 98 | } 99 | else if (unit == TimeUnit.YEARS) 100 | { 101 | field = Calendar.YEAR; 102 | } 103 | 104 | calendar.setTimeInMillis(time); 105 | calendar.add(field, -value); 106 | 107 | return calendar.getTime().getTime(); 108 | } 109 | 110 | //Intentionally leaving out the calendar, it messes up unit tests and is not needed for equality 111 | @Override 112 | public boolean equals(Object o) 113 | { 114 | if (this == o) return true; 115 | if (o == null || getClass() != o.getClass()) return false; 116 | RelativeTime that = (RelativeTime) o; 117 | return value == that.value && unit == that.unit; 118 | } 119 | 120 | @Override 121 | public int hashCode() 122 | { 123 | return Objects.hash(value, unit); 124 | } 125 | 126 | @Override 127 | public String toString() 128 | { 129 | return new StringJoiner(", ", RelativeTime.class.getSimpleName() + "[", "]") 130 | .add("value=" + value) 131 | .add("unit=" + unit) 132 | .add("calendar=" + calendar) 133 | .toString(); 134 | } 135 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/Rollup.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.Date; 6 | import java.util.List; 7 | import java.util.Objects; 8 | import java.util.TimeZone; 9 | 10 | import static java.util.Objects.requireNonNull; 11 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 12 | 13 | public class Rollup 14 | { 15 | @SerializedName("save_as") 16 | private final String saveAs; 17 | 18 | @SerializedName("query") 19 | private QueryBuilder builder; 20 | 21 | Rollup(String saveAs) 22 | { 23 | this.saveAs = checkNotNullOrEmpty(saveAs, "saveAs cannot be null or empty"); 24 | } 25 | 26 | public QueryBuilder addQuery() 27 | { 28 | builder = QueryBuilder.getInstance(); 29 | return builder; 30 | } 31 | 32 | public Date getStartAbsolute() 33 | { 34 | return builder.getStartAbsolute(); 35 | } 36 | 37 | public Date getEndAbsolute() 38 | { 39 | return builder.getEndAbsolute(); 40 | } 41 | 42 | public RelativeTime getStartRelative() 43 | { 44 | return builder.getStartRelative(); 45 | } 46 | 47 | public int getCacheTime() 48 | { 49 | return builder.getCacheTime(); 50 | } 51 | 52 | public TimeZone getTimeZone() 53 | { 54 | return builder.getTimeZone(); 55 | } 56 | 57 | public List getMetrics() 58 | { 59 | return builder.getMetrics(); 60 | } 61 | 62 | public String getSaveAs() 63 | { 64 | return saveAs; 65 | } 66 | 67 | void validate() 68 | { 69 | requireNonNull(builder, "No queries added to rollup " + saveAs); 70 | builder.validate(); 71 | } 72 | 73 | @Override 74 | public boolean equals(Object o) 75 | { 76 | if (this == o) return true; 77 | if (o == null || getClass() != o.getClass()) return false; 78 | Rollup rollup = (Rollup) o; 79 | return Objects.equals(saveAs, rollup.saveAs) && Objects.equals(builder, rollup.builder); 80 | } 81 | 82 | @Override 83 | public int hashCode() 84 | { 85 | return Objects.hash(saveAs, builder); 86 | } 87 | 88 | @Override 89 | public String toString() 90 | { 91 | return "Rollup{" + 92 | "saveAs='" + saveAs + '\'' + 93 | ", builder=" + builder + 94 | '}'; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/RollupBuilder.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.common.collect.ListMultimap; 4 | import com.google.gson.Gson; 5 | import com.google.gson.GsonBuilder; 6 | import com.google.gson.annotations.SerializedName; 7 | import org.kairosdb.client.builder.aggregator.CustomAggregator; 8 | import org.kairosdb.client.builder.grouper.CustomGrouper; 9 | import org.kairosdb.client.serializer.*; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.TimeZone; 14 | 15 | import static java.util.Objects.requireNonNull; 16 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 17 | import static org.kairosdb.client.util.Preconditions.checkState; 18 | 19 | public class RollupBuilder 20 | { 21 | private final transient Gson mapper; 22 | 23 | @SuppressWarnings({"FieldCanBeLocal", "unused"}) 24 | private final String name; 25 | 26 | @SuppressWarnings({"FieldCanBeLocal", "unused"}) 27 | @SerializedName("execution_interval") 28 | private final RelativeTime executionInterval; 29 | 30 | private final List rollups = new ArrayList<>(); 31 | 32 | private RollupBuilder(String name, RelativeTime executionInterval) 33 | { 34 | this.name = checkNotNullOrEmpty(name, "name cannot be null or empty"); 35 | this.executionInterval = requireNonNull(executionInterval, "executionInterval cannot be null"); 36 | 37 | GsonBuilder builder = new GsonBuilder(); 38 | builder.registerTypeAdapter(CustomAggregator.class, new CustomAggregatorSerializer()); 39 | builder.registerTypeAdapter(CustomGrouper.class, new CustomGrouperSerializer()); 40 | builder.registerTypeAdapter(ListMultimap.class, new ListMultiMapSerializer()); 41 | builder.registerTypeAdapter(QueryMetric.Order.class, new OrderSerializer()); 42 | builder.registerTypeAdapter(TimeZone.class, new TimeZoneSerializer()); 43 | 44 | mapper = builder.create(); 45 | } 46 | 47 | /** 48 | * Returns a new query builder. 49 | * 50 | * @return new query builder 51 | */ 52 | public static RollupBuilder getInstance(String name, RelativeTime executionInterval) 53 | { 54 | checkNotNullOrEmpty(name, "name cannot be null or empty"); 55 | requireNonNull(executionInterval, "executionInterval cannot be null"); 56 | 57 | return new RollupBuilder(name, executionInterval); 58 | } 59 | 60 | public Rollup addRollup(String saveAs) 61 | { 62 | Rollup rollup = new Rollup(saveAs); 63 | rollups.add(rollup); 64 | 65 | return rollup; 66 | } 67 | 68 | public String build() 69 | { 70 | validate(); 71 | return mapper.toJson(this); 72 | } 73 | 74 | private void validate() 75 | { 76 | checkState(rollups.size() > 0, "No roll-ups added"); 77 | for (Rollup rollup : rollups) { 78 | rollup.validate(); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/RollupTask.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.time.Duration; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Objects; 9 | 10 | import static java.util.Objects.requireNonNull; 11 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 12 | 13 | public class RollupTask 14 | { 15 | private final String id; 16 | private final List rollups = new ArrayList<>(); 17 | 18 | private final String name; 19 | 20 | @SerializedName("execution_interval") 21 | private final RelativeTime executionInterval; 22 | 23 | private final long lastModified; 24 | 25 | public RollupTask(String id, String name, RelativeTime executionInterval, long lastModified) 26 | { 27 | this.id = checkNotNullOrEmpty(id, "id cannot be null or empty"); 28 | this.name = checkNotNullOrEmpty(name, "name cannot be null or empty"); 29 | this.executionInterval = requireNonNull(executionInterval, "executionInterval cannot be null"); 30 | this.lastModified = lastModified; 31 | } 32 | 33 | public String getId() 34 | { 35 | return id; 36 | } 37 | 38 | public List getRollups() 39 | { 40 | return rollups; 41 | } 42 | 43 | public String getName() 44 | { 45 | return name; 46 | } 47 | 48 | public RelativeTime getExecutionInterval() 49 | { 50 | return executionInterval; 51 | } 52 | 53 | public long getLastModified() 54 | { 55 | return lastModified; 56 | } 57 | 58 | @Override 59 | public boolean equals(Object o) 60 | { 61 | if (this == o) return true; 62 | if (o == null || getClass() != o.getClass()) return false; 63 | RollupTask that = (RollupTask) o; 64 | return lastModified == that.lastModified && Objects.equals(id, that.id) && Objects.equals(rollups, that.rollups) && Objects.equals(name, that.name) && Objects.equals(executionInterval, that.executionInterval); 65 | } 66 | 67 | @Override 68 | public int hashCode() 69 | { 70 | return Objects.hash(id, rollups, name, executionInterval, lastModified); 71 | } 72 | 73 | @Override 74 | public String toString() 75 | { 76 | return "RollupTask{" + 77 | "id='" + id + '\'' + 78 | ", rollups=" + rollups + 79 | ", name='" + name + '\'' + 80 | ", executionInterval=" + executionInterval + 81 | ", lastModified=" + lastModified + 82 | '}'; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/TimeUnit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | public enum TimeUnit 19 | { 20 | MILLISECONDS, 21 | SECONDS, 22 | MINUTES, 23 | HOURS, 24 | DAYS, 25 | WEEKS, 26 | MONTHS, 27 | YEARS 28 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/TimeValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import static org.kairosdb.client.util.Preconditions.checkState; 19 | 20 | /** 21 | * Validates start and end times. 22 | */ 23 | public class TimeValidator 24 | { 25 | private static final String START_TIME_EARLIER = "Start time must be equal to or earlier than the ending time"; 26 | 27 | private TimeValidator() 28 | { 29 | } 30 | 31 | public static void validateEndTimeLaterThanStartTime(long startTime, long endTime) 32 | { 33 | checkState(endTime >= startTime, START_TIME_EARLIER); 34 | } 35 | 36 | public static void validateEndTimeLaterThanStartTime(RelativeTime startTime, RelativeTime endTime) 37 | { 38 | long now = System.currentTimeMillis(); 39 | checkState(startTime.getTimeRelativeTo(now) <= endTime.getTimeRelativeTo(now), START_TIME_EARLIER); 40 | } 41 | 42 | public static void validateEndTimeLaterThanStartTime(long startTime, RelativeTime endTime) 43 | { 44 | long now = System.currentTimeMillis(); 45 | checkState(startTime <= endTime.getTimeRelativeTo(now), START_TIME_EARLIER); 46 | } 47 | 48 | public static void validateEndTimeLaterThanStartTime(RelativeTime startTime, long endTime) 49 | { 50 | long now = System.currentTimeMillis(); 51 | checkState(startTime.getTimeRelativeTo(now) <= endTime, START_TIME_EARLIER); 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/aggregator/CustomAggregator.java: -------------------------------------------------------------------------------- 1 | // 2 | // CustomAggregator.java 3 | // 4 | // Copyright 2013, Proofpoint Inc. All rights reserved. 5 | // 6 | package org.kairosdb.client.builder.aggregator; 7 | 8 | import org.kairosdb.client.builder.Aggregator; 9 | 10 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 11 | 12 | /** 13 | * Creates an aggregator that takes custom JSON. 14 | */ 15 | public class CustomAggregator extends Aggregator 16 | { 17 | private String json; 18 | 19 | public CustomAggregator(String name, String json) 20 | { 21 | super(name); 22 | this.json = checkNotNullOrEmpty(json); 23 | } 24 | 25 | public String toJson() 26 | { 27 | return "{\"name\":\"" + getName() + "\"," + json + "}"; 28 | } 29 | 30 | @Override 31 | public boolean equals(Object o) 32 | { 33 | if (this == o) 34 | return true; 35 | if (o == null || getClass() != o.getClass()) 36 | return false; 37 | if (!super.equals(o)) 38 | return false; 39 | 40 | CustomAggregator that = (CustomAggregator) o; 41 | return json.equals(that.json); 42 | } 43 | 44 | @Override 45 | public int hashCode() 46 | { 47 | int result = super.hashCode(); 48 | result = 31 * result + json.hashCode(); 49 | return result; 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/aggregator/DeserializedAggregator.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder.aggregator; 2 | 3 | import com.google.common.collect.ImmutableMap; 4 | import org.kairosdb.client.builder.Aggregator; 5 | 6 | import java.util.Map; 7 | 8 | import static java.util.Objects.requireNonNull; 9 | 10 | public class DeserializedAggregator extends Aggregator 11 | { 12 | private final Map properties; 13 | public DeserializedAggregator(Map properties) 14 | { 15 | super((String)properties.get("name")); 16 | this.properties = requireNonNull(properties, "properties cannot be null"); 17 | } 18 | 19 | public ImmutableMap getProperties() 20 | { 21 | return ImmutableMap.copyOf(properties); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/aggregator/PercentileAggregator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder.aggregator; 17 | 18 | import static org.kairosdb.client.util.Preconditions.checkArgument; 19 | 20 | import org.kairosdb.client.builder.TimeUnit; 21 | 22 | public class PercentileAggregator extends SamplingAggregator 23 | { 24 | private double percentile; 25 | 26 | public PercentileAggregator(double percentile, long value, TimeUnit unit) 27 | { 28 | super("percentile", value, unit); 29 | 30 | checkArgument(percentile >= 0, "value must be greater than or equal to 0."); 31 | checkArgument(percentile <= 1, "value must be less than or equal to 1."); 32 | 33 | this.percentile = percentile; 34 | 35 | } 36 | 37 | public double getPercentile() 38 | { 39 | return percentile; 40 | } 41 | 42 | @Override 43 | public boolean equals(Object o) 44 | { 45 | if (this == o) 46 | return true; 47 | if (o == null || getClass() != o.getClass()) 48 | return false; 49 | if (!super.equals(o)) 50 | return false; 51 | 52 | PercentileAggregator that = (PercentileAggregator) o; 53 | return Double.compare(that.percentile, percentile) == 0; 54 | } 55 | 56 | @Override 57 | public int hashCode() 58 | { 59 | int result = super.hashCode(); 60 | long temp; 61 | temp = Double.doubleToLongBits(percentile); 62 | result = 31 * result + (int) (temp ^ (temp >>> 32)); 63 | return result; 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/aggregator/RateAggregator.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder.aggregator; 2 | 3 | import org.kairosdb.client.builder.Aggregator; 4 | import org.kairosdb.client.builder.TimeUnit; 5 | 6 | import static java.util.Objects.requireNonNull; 7 | 8 | public class RateAggregator extends Aggregator 9 | { 10 | private TimeUnit unit; 11 | 12 | public RateAggregator(TimeUnit unit) 13 | { 14 | super("rate"); 15 | this.unit = requireNonNull(unit); 16 | } 17 | 18 | public TimeUnit getUnit() 19 | { 20 | return unit; 21 | } 22 | 23 | @Override 24 | public boolean equals(Object o) 25 | { 26 | if (this == o) 27 | return true; 28 | if (o == null || getClass() != o.getClass()) 29 | return false; 30 | if (!super.equals(o)) 31 | return false; 32 | 33 | RateAggregator that = (RateAggregator) o; 34 | return unit == that.unit; 35 | } 36 | 37 | @Override 38 | public int hashCode() 39 | { 40 | int result = super.hashCode(); 41 | result = 31 * result + unit.hashCode(); 42 | return result; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/aggregator/SamplingAggregator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder.aggregator; 17 | 18 | import com.google.gson.annotations.SerializedName; 19 | import org.kairosdb.client.builder.Aggregator; 20 | import org.kairosdb.client.builder.TimeUnit; 21 | 22 | import static java.util.Objects.requireNonNull; 23 | import static org.kairosdb.client.util.Preconditions.checkArgument; 24 | 25 | 26 | public class SamplingAggregator extends Aggregator 27 | { 28 | private Sampling sampling; 29 | 30 | @SerializedName("align_start_time") 31 | private Boolean alignStartTime; 32 | 33 | @SerializedName("align_end_time") 34 | private Boolean alignEndTime; 35 | 36 | @SerializedName("align_sampling") 37 | private Boolean alignSampling; 38 | 39 | @SerializedName("start_time") 40 | private Long startTime; 41 | 42 | public SamplingAggregator(String name, long value, TimeUnit unit) 43 | { 44 | super(name); 45 | checkArgument(value > 0, "value must be greater than 0."); 46 | 47 | sampling = new Sampling(value, unit); 48 | } 49 | 50 | public long getValue() 51 | { 52 | return sampling.value; 53 | } 54 | 55 | public TimeUnit getUnit() 56 | { 57 | return sampling.unit; 58 | } 59 | 60 | /** 61 | *

62 | * Alignment based on the sampling size. For example if your sample size is either milliseconds, 63 | * seconds, minutes or hours then the start of the range will always be at the top 64 | * of the hour. The effect of setting this to true is that your data will 65 | * take the same shape when graphed as you refresh the data. 66 | *

67 | *

68 | * Only one alignment type can be used. 69 | *

70 | * 71 | * @return the SamplingAggregator 72 | */ 73 | public SamplingAggregator withSamplingAlignment() 74 | { 75 | alignSampling = true; 76 | 77 | return this; 78 | } 79 | 80 | /** 81 | *

82 | * Alignment based on the aggregation range rather than the value of the first 83 | * data point within that range. 84 | * Only one alignment type can be used. 85 | *

86 | * 87 | * @return the SamplingAggregator 88 | */ 89 | public SamplingAggregator withStartTimeAlignment() 90 | { 91 | alignStartTime = true; 92 | 93 | return this; 94 | } 95 | 96 | /** 97 | *

98 | * Alignment based on the aggregation range rather than the value of the last 99 | * data point within that range. 100 | * Only one alignment type can be used. 101 | *

102 | * 103 | * @return the SamplingAggregator 104 | */ 105 | public SamplingAggregator withEndTimeAlignment() 106 | { 107 | alignEndTime = true; 108 | 109 | return this; 110 | } 111 | 112 | /** 113 | *

114 | * Alignment that starts based on the specified time. For example, if startTime 115 | * is set to noon today,then alignment starts at noon today. 116 | *

117 | *

118 | * Only one alignment type can be used. 119 | *

120 | * 121 | * @param startTime the alignment start time 122 | * @return the SamplingAggregator 123 | */ 124 | public SamplingAggregator withStartTimeAlignment(long startTime) 125 | { 126 | checkArgument(startTime >= 0, "startTime cannot be negative"); 127 | alignStartTime = true; 128 | this.startTime = startTime; 129 | 130 | return this; 131 | } 132 | 133 | /** 134 | *

135 | * Alignment that starts based on the specified time. For example, if startTime 136 | * is set to noon today,then alignment starts at noon today. 137 | *

138 | *

139 | * Only one alignment type can be used. 140 | *

141 | * 142 | * @param startTime the alignment start time 143 | * @return the SamplingAggregator 144 | */ 145 | public SamplingAggregator withEndTimeAlignment(long startTime) 146 | { 147 | checkArgument(startTime >= 0, "startTime cannot be negative"); 148 | alignEndTime = true; 149 | this.startTime = startTime; 150 | 151 | return this; 152 | } 153 | 154 | @Deprecated 155 | /** 156 | * @deprecated Use withSamplingAlignment() and withStartTimeAlignment() 157 | */ 158 | public SamplingAggregator withAlignment(Boolean alignStartTime, Boolean alignSampling) 159 | { 160 | this.alignStartTime = alignStartTime; 161 | this.alignSampling = alignSampling; 162 | 163 | return this; 164 | } 165 | 166 | public Boolean isAlignStartTime() 167 | { 168 | return alignStartTime != null ? alignStartTime : false; 169 | } 170 | 171 | public Boolean isAlignEndTime() 172 | { 173 | return alignEndTime != null ? alignEndTime : false; 174 | } 175 | 176 | public Boolean isAlignSampling() 177 | { 178 | return alignSampling != null ? alignSampling : false; 179 | } 180 | 181 | public long getStartTimeAlignmentStartTime() 182 | { 183 | return startTime != null ? startTime : 0; 184 | } 185 | 186 | private class Sampling 187 | { 188 | private Sampling(long value, TimeUnit unit) 189 | { 190 | this.value = value; 191 | this.unit = requireNonNull(unit); 192 | } 193 | 194 | private long value; 195 | private TimeUnit unit; 196 | } 197 | 198 | @SuppressWarnings("SimplifiableIfStatement") 199 | @Override 200 | public boolean equals(Object o) 201 | { 202 | if (this == o) 203 | return true; 204 | if (o == null || getClass() != o.getClass()) 205 | return false; 206 | if (!super.equals(o)) 207 | return false; 208 | 209 | SamplingAggregator that = (SamplingAggregator) o; 210 | 211 | if (sampling != null ? !sampling.equals(that.sampling) : that.sampling != null) 212 | return false; 213 | if (alignStartTime != null ? !alignStartTime.equals(that.alignStartTime) : that.alignStartTime != null) 214 | return false; 215 | if (alignEndTime != null ? !alignEndTime.equals(that.alignEndTime) : that.alignEndTime != null) 216 | return false; 217 | if (alignSampling != null ? !alignSampling.equals(that.alignSampling) : that.alignSampling != null) 218 | return false; 219 | return !(startTime != null ? !startTime.equals(that.startTime) : that.startTime != null); 220 | } 221 | 222 | @Override 223 | public int hashCode() 224 | { 225 | int result = super.hashCode(); 226 | result = 31 * result + (sampling != null ? sampling.hashCode() : 0); 227 | result = 31 * result + (alignStartTime != null ? alignStartTime.hashCode() : 0); 228 | result = 31 * result + (alignEndTime != null ? alignEndTime.hashCode() : 0); 229 | result = 31 * result + (alignSampling != null ? alignSampling.hashCode() : 0); 230 | result = 31 * result + (startTime != null ? startTime.hashCode() : 0); 231 | return result; 232 | } 233 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/grouper/BinGrouper.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder.grouper; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | import org.kairosdb.client.builder.Grouper; 5 | 6 | import java.util.Arrays; 7 | import java.util.List; 8 | import java.util.Objects; 9 | 10 | import static java.util.Objects.requireNonNull; 11 | import static org.kairosdb.client.util.Preconditions.checkArgument; 12 | 13 | 14 | public class BinGrouper extends Grouper 15 | { 16 | 17 | @SerializedName("bins") 18 | private List bins; 19 | 20 | public BinGrouper(Double... bins) 21 | { 22 | super("bin"); 23 | 24 | requireNonNull(bins, "bins cannot be null"); 25 | checkArgument(bins.length > 0, "bins cannot be empty"); 26 | this.bins = Arrays.asList(bins); 27 | } 28 | 29 | public BinGrouper(List bins) 30 | { 31 | super("bin"); 32 | requireNonNull(bins, "bins cannot be null"); 33 | checkArgument(bins.size() > 0, "bins cannot be empty"); 34 | this.bins = bins; 35 | } 36 | 37 | public List getBins() 38 | { 39 | return bins; 40 | } 41 | 42 | 43 | @Override 44 | public boolean equals(Object o) 45 | { 46 | if (this == o) return true; 47 | if (o == null || getClass() != o.getClass()) return false; 48 | if (!super.equals(o)) return false; 49 | BinGrouper that = (BinGrouper) o; 50 | return Objects.equals(bins, that.bins); 51 | } 52 | 53 | @Override 54 | public int hashCode() 55 | { 56 | return Objects.hash(super.hashCode(), bins); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/grouper/CustomGrouper.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder.grouper; 2 | 3 | import org.kairosdb.client.builder.Grouper; 4 | 5 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 6 | 7 | /** 8 | * Grouper that that takes custom json. 9 | */ 10 | public class CustomGrouper extends Grouper 11 | { 12 | private String json; 13 | 14 | public CustomGrouper(String name, String json) 15 | { 16 | super(name); 17 | this.json = checkNotNullOrEmpty(json); 18 | } 19 | 20 | public String toJson() 21 | { 22 | return "{\"name\": \"" + getName() + "\", " + json + "}"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/grouper/TagGrouper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder.grouper; 17 | 18 | import com.google.gson.annotations.SerializedName; 19 | import org.kairosdb.client.builder.Grouper; 20 | 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | 24 | import static java.util.Objects.requireNonNull; 25 | import static org.kairosdb.client.util.Preconditions.checkArgument; 26 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 27 | 28 | /** 29 | * Grouper used to group by tag names. 30 | */ 31 | public class TagGrouper extends Grouper 32 | { 33 | @SerializedName("tags") 34 | private List tagNames = new ArrayList(); 35 | 36 | public TagGrouper(String... tagNames) 37 | { 38 | super("tag"); 39 | checkArgument(tagNames.length > 0); 40 | for (String tagName : tagNames) 41 | { 42 | this.tagNames.add(checkNotNullOrEmpty(tagName)); 43 | } 44 | } 45 | 46 | public TagGrouper(List tagNames) 47 | { 48 | super("tag"); 49 | requireNonNull(tagNames); 50 | this.tagNames = tagNames; 51 | } 52 | 53 | public List getTagNames() 54 | { 55 | return tagNames; 56 | } 57 | 58 | @Override 59 | public boolean equals(Object o) 60 | { 61 | if (this == o) 62 | return true; 63 | if (o == null || getClass() != o.getClass()) 64 | return false; 65 | if (!super.equals(o)) 66 | return false; 67 | 68 | TagGrouper that = (TagGrouper) o; 69 | return !(tagNames != null ? !tagNames.equals(that.tagNames) : that.tagNames != null); 70 | } 71 | 72 | @Override 73 | public int hashCode() 74 | { 75 | int result = super.hashCode(); 76 | result = 31 * result + (tagNames != null ? tagNames.hashCode() : 0); 77 | return result; 78 | } 79 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/grouper/TimeGrouper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder.grouper; 17 | 18 | import com.google.gson.annotations.SerializedName; 19 | import org.kairosdb.client.builder.Grouper; 20 | import org.kairosdb.client.builder.RelativeTime; 21 | 22 | import static java.util.Objects.requireNonNull; 23 | import static org.kairosdb.client.util.Preconditions.checkArgument; 24 | 25 | /** 26 | * Grouper used to group by time range. The combination of rangeSize and count determine the grouping range. The 27 | * rangeSize is the time unit and the count is the number of time units in the range. For example, a rangeSize of 28 | * 1 days with a count of 7, creates 1 day groups for a week. A rangeSize of 1 hours with a count of 168 (7 * 24), 29 | * creates groups for each hour of the week. 30 | */ 31 | public class TimeGrouper extends Grouper 32 | { 33 | @SerializedName("range_size") 34 | private RelativeTime rangeSize; 35 | 36 | @SerializedName("group_count") 37 | private int count; 38 | 39 | public TimeGrouper(RelativeTime rangeSize, int count) 40 | { 41 | super("time"); 42 | checkArgument(count > 0); 43 | this.rangeSize = requireNonNull(rangeSize); 44 | this.count = count; 45 | } 46 | 47 | public RelativeTime getRangeSize() 48 | { 49 | return rangeSize; 50 | } 51 | 52 | public int getCount() 53 | { 54 | return count; 55 | } 56 | 57 | @Override 58 | public boolean equals(Object o) 59 | { 60 | if (this == o) 61 | return true; 62 | if (o == null || getClass() != o.getClass()) 63 | return false; 64 | if (!super.equals(o)) 65 | return false; 66 | 67 | TimeGrouper that = (TimeGrouper) o; 68 | return count == that.count && !(rangeSize != null ? !rangeSize.equals(that.rangeSize) : that.rangeSize != null); 69 | } 70 | 71 | @Override 72 | public int hashCode() 73 | { 74 | int result = super.hashCode(); 75 | result = 31 * result + (rangeSize != null ? rangeSize.hashCode() : 0); 76 | result = 31 * result + count; 77 | return result; 78 | } 79 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/builder/grouper/ValueGrouper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder.grouper; 17 | 18 | import com.google.gson.annotations.SerializedName; 19 | import org.kairosdb.client.builder.Grouper; 20 | 21 | import static org.kairosdb.client.util.Preconditions.checkArgument; 22 | 23 | /** 24 | * Grouper used to group by metric value. Groups are a range of values specified by range size. For example, 25 | * if rangeSize is 10, then all values between 0 and 9 are put into the first group, 10-19 in the second group, etc. 26 | */ 27 | public class ValueGrouper extends Grouper 28 | { 29 | @SerializedName("range_size") 30 | private int rangeSize; 31 | 32 | public ValueGrouper(int rangeSize) 33 | { 34 | super("value"); 35 | checkArgument(rangeSize > 0); 36 | this.rangeSize = rangeSize; 37 | } 38 | 39 | public int getRangeSize() 40 | { 41 | return rangeSize; 42 | } 43 | 44 | @Override 45 | public boolean equals(Object o) 46 | { 47 | if (this == o) 48 | return true; 49 | if (o == null || getClass() != o.getClass()) 50 | return false; 51 | if (!super.equals(o)) 52 | return false; 53 | 54 | ValueGrouper that = (ValueGrouper) o; 55 | return rangeSize == that.rangeSize; 56 | } 57 | 58 | @Override 59 | public int hashCode() 60 | { 61 | int result = super.hashCode(); 62 | result = 31 * result + rangeSize; 63 | return result; 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/deserializer/AggregatorDeserializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.deserializer; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.JsonDeserializationContext; 5 | import com.google.gson.JsonDeserializer; 6 | import com.google.gson.JsonElement; 7 | import com.google.gson.JsonParseException; 8 | import com.google.gson.reflect.TypeToken; 9 | import org.kairosdb.client.builder.Aggregator; 10 | import org.kairosdb.client.builder.aggregator.DeserializedAggregator; 11 | 12 | import java.lang.reflect.Type; 13 | import java.util.Map; 14 | 15 | 16 | public class AggregatorDeserializer implements JsonDeserializer 17 | { 18 | private Gson gson = new Gson(); 19 | 20 | @Override 21 | public Aggregator deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) 22 | throws JsonParseException 23 | { 24 | Type mapType = new TypeToken>(){}.getType(); 25 | Map map = gson.fromJson(jsonElement, mapType); 26 | return new DeserializedAggregator(map); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/deserializer/GroupByDeserializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.deserializer; 2 | 3 | import com.google.gson.*; 4 | import com.google.gson.reflect.TypeToken; 5 | import org.kairosdb.client.response.GroupResult; 6 | import org.kairosdb.client.response.grouping.*; 7 | 8 | import java.lang.reflect.Type; 9 | import java.util.Map; 10 | 11 | /** 12 | * Called by the JSON parser to deserialize groub-by. 13 | */ 14 | public class GroupByDeserializer implements JsonDeserializer 15 | { 16 | @Override 17 | public GroupResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) 18 | throws JsonParseException 19 | { 20 | JsonObject jsGroupBy = jsonElement.getAsJsonObject(); 21 | 22 | JsonElement nameElement = jsGroupBy.get("name"); 23 | if (nameElement == null || nameElement.getAsString().isEmpty()) 24 | { 25 | throw new JsonParseException("name cannot be null"); 26 | } 27 | 28 | String name = nameElement.getAsString(); 29 | if (name.equals("type")) 30 | { 31 | return jsonDeserializationContext.deserialize(jsonElement, DefaultGroupResult.class); 32 | } 33 | else if (name.equals("bin")) 34 | { 35 | return jsonDeserializationContext.deserialize(jsonElement, BinGroupResult.class); 36 | } 37 | else if (name.equals("tag")) 38 | { 39 | return jsonDeserializationContext.deserialize(jsonElement, TagGroupResult.class); 40 | } 41 | else if (name.equals("time")) 42 | { 43 | return jsonDeserializationContext.deserialize(jsonElement, TimeGroupResult.class); 44 | } 45 | else if (name.equals("value")) 46 | { 47 | return jsonDeserializationContext.deserialize(jsonElement, ValueGroupResult.class); 48 | } 49 | else 50 | { 51 | Map result = jsonDeserializationContext.deserialize(jsGroupBy, new TypeToken>(){}.getType()); 52 | return new CustomGroupResult(result); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/deserializer/GrouperDeserializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.deserializer; 2 | 3 | import com.google.gson.JsonDeserializationContext; 4 | import com.google.gson.JsonDeserializer; 5 | import com.google.gson.JsonElement; 6 | import com.google.gson.JsonObject; 7 | import com.google.gson.JsonParseException; 8 | import org.kairosdb.client.builder.Grouper; 9 | import org.kairosdb.client.builder.grouper.TagGrouper; 10 | import org.kairosdb.client.builder.grouper.TimeGrouper; 11 | import org.kairosdb.client.builder.grouper.ValueGrouper; 12 | 13 | import java.lang.reflect.Type; 14 | 15 | public class GrouperDeserializer implements JsonDeserializer 16 | { 17 | @Override 18 | public Grouper deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) 19 | throws JsonParseException 20 | { 21 | JsonObject jsGroupBy = jsonElement.getAsJsonObject(); 22 | 23 | JsonElement nameElement = jsGroupBy.get("name"); 24 | if (nameElement == null || nameElement.getAsString().isEmpty()) { 25 | throw new JsonParseException("name cannot be null"); 26 | } 27 | 28 | String name = nameElement.getAsString(); 29 | switch (name) { 30 | case "tag": 31 | return jsonDeserializationContext.deserialize(jsonElement, TagGrouper.class); 32 | case "time": 33 | return jsonDeserializationContext.deserialize(jsonElement, TimeGrouper.class); 34 | case "value": 35 | return jsonDeserializationContext.deserialize(jsonElement, ValueGrouper.class); 36 | default: 37 | throw new JsonParseException("Invalid group_by: " + name); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/deserializer/ListMultiMapDeserializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.deserializer; 2 | 3 | import com.google.common.collect.ArrayListMultimap; 4 | import com.google.common.collect.ListMultimap; 5 | import com.google.gson.JsonDeserializationContext; 6 | import com.google.gson.JsonDeserializer; 7 | import com.google.gson.JsonElement; 8 | import com.google.gson.JsonObject; 9 | import com.google.gson.JsonParseException; 10 | 11 | import java.lang.reflect.Type; 12 | import java.util.Map; 13 | 14 | public class ListMultiMapDeserializer implements JsonDeserializer> 15 | { 16 | @Override 17 | public ListMultimap deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) 18 | throws JsonParseException 19 | { 20 | ListMultimap map = ArrayListMultimap.create(); 21 | JsonObject asJsonObject = jsonElement.getAsJsonObject(); 22 | for (Map.Entry entry : asJsonObject.entrySet()) { 23 | map.put(entry.getKey(), entry.getValue().getAsString()); 24 | } 25 | return map; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/deserializer/ResultsDeserializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.deserializer; 2 | 3 | import com.google.gson.*; 4 | import com.google.gson.reflect.TypeToken; 5 | import org.kairosdb.client.DataPointTypeRegistry; 6 | import org.kairosdb.client.builder.DataPoint; 7 | import org.kairosdb.client.response.GroupResult; 8 | import org.kairosdb.client.response.Result; 9 | import org.kairosdb.client.response.grouping.DefaultGroupResult; 10 | 11 | import java.lang.reflect.Type; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | import static java.util.Objects.requireNonNull; 17 | import static org.kairosdb.client.util.Preconditions.checkState; 18 | 19 | public class ResultsDeserializer implements JsonDeserializer 20 | { 21 | private DataPointTypeRegistry typeRegistry; 22 | 23 | public ResultsDeserializer(DataPointTypeRegistry typeRegistry) 24 | { 25 | this.typeRegistry = requireNonNull(typeRegistry); 26 | } 27 | 28 | @Override 29 | public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException 30 | { 31 | // Name 32 | String name = json.getAsJsonObject().get("name").getAsString(); 33 | checkState(name != null, "Missing name"); 34 | 35 | // Tags 36 | JsonElement tagsElement = json.getAsJsonObject().get("tags"); 37 | Map> tags = context.deserialize(tagsElement, new TypeToken>>() 38 | { 39 | }.getType()); 40 | 41 | // Group_By 42 | JsonElement group_by = json.getAsJsonObject().get("group_by"); 43 | List groupResults = context.deserialize(group_by, new TypeToken>() 44 | { 45 | }.getType()); 46 | 47 | List dataPoints = new ArrayList(); 48 | if (group_by != null) 49 | { 50 | String type = null; 51 | for (GroupResult groupResult : groupResults) 52 | { 53 | if (groupResult.getName().equals("type")) 54 | { 55 | type = ((DefaultGroupResult) groupResult).getType(); 56 | } 57 | } 58 | checkState(type != null, "Missing type"); 59 | 60 | // Data points 61 | final Class dataPointValueClass = typeRegistry.getDataPointValueClass(type); 62 | checkState(dataPointValueClass != null, "type: " + type + " is not registered to a custom data type."); 63 | 64 | JsonArray array = (JsonArray) json.getAsJsonObject().get("values"); 65 | for (JsonElement element : array) 66 | { 67 | JsonArray pair = element.getAsJsonArray(); 68 | dataPoints.add(new DataPoint(pair.get(0).getAsLong(), context.deserialize(pair.get(1), dataPointValueClass))); 69 | } 70 | } 71 | 72 | return new Result(name, tags, dataPoints, groupResults); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/deserializer/TimeZoneDeserializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.deserializer; 2 | 3 | import com.google.gson.JsonDeserializationContext; 4 | import com.google.gson.JsonDeserializer; 5 | import com.google.gson.JsonElement; 6 | import com.google.gson.JsonParseException; 7 | 8 | import java.lang.reflect.Type; 9 | import java.util.TimeZone; 10 | 11 | public class TimeZoneDeserializer implements JsonDeserializer 12 | { 13 | @Override 14 | public TimeZone deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) 15 | throws JsonParseException 16 | { 17 | return TimeZone.getTimeZone(jsonElement.getAsString()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/DefaultJsonResponseHandler.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | 4 | import com.google.common.collect.ImmutableSet; 5 | import com.google.common.net.MediaType; 6 | import com.google.common.reflect.TypeToken; 7 | import com.google.gson.JsonIOException; 8 | import com.google.gson.JsonSyntaxException; 9 | import org.apache.http.client.methods.HttpUriRequest; 10 | import org.kairosdb.client.DataPointTypeRegistry; 11 | import org.kairosdb.client.JsonMapper; 12 | 13 | import java.io.IOException; 14 | import java.io.InputStreamReader; 15 | import java.io.Reader; 16 | import java.lang.reflect.Type; 17 | import java.nio.charset.StandardCharsets; 18 | import java.util.Set; 19 | 20 | import static com.google.common.net.HttpHeaders.CONTENT_TYPE; 21 | import static java.util.Objects.requireNonNull; 22 | import static org.kairosdb.client.util.Exceptions.propagate; 23 | 24 | public class DefaultJsonResponseHandler implements JsonResponseHandler 25 | { 26 | private static final MediaType MEDIA_TYPE_JSON = MediaType.create("application", "json"); 27 | private final Set successfulResponseCodes; 28 | 29 | private final JsonMapper mapper; 30 | private final Type type; 31 | 32 | @SuppressWarnings({"unused", "WeakerAccess"}) 33 | public DefaultJsonResponseHandler(Class clazz) 34 | { 35 | this(clazz, new DataPointTypeRegistry()); 36 | } 37 | 38 | @SuppressWarnings({"WeakerAccess", "unused"}) 39 | public DefaultJsonResponseHandler(Type type) 40 | { 41 | this(type, new DataPointTypeRegistry()); 42 | } 43 | 44 | public DefaultJsonResponseHandler(Class clazz, DataPointTypeRegistry typeRegistry) 45 | { 46 | this(TypeToken.of(clazz).getType(), typeRegistry); 47 | } 48 | 49 | public DefaultJsonResponseHandler(Type type, DataPointTypeRegistry typeRegistry) 50 | { 51 | requireNonNull(typeRegistry, "typeRegistry must not be null"); 52 | mapper = new JsonMapper(typeRegistry); 53 | successfulResponseCodes = ImmutableSet.of(200, 204); 54 | this.type = requireNonNull(type, "type must not be null"); 55 | } 56 | 57 | @Override 58 | public Object handleException(HttpUriRequest request, Exception exception) throws RuntimeException 59 | { 60 | throw propagate(request, exception); 61 | } 62 | 63 | @Override 64 | public T handle(HttpUriRequest request, ResponseHelper response) throws RuntimeException 65 | { 66 | if (!successfulResponseCodes.contains(response.getStatusCode()) && response.getStatusCode() != 400) 67 | { 68 | throw new UnexpectedResponseException( 69 | String.format("Expected response code to be %s, but was %d: %s", successfulResponseCodes, response.getStatusCode(), response.getStatusMessage()), 70 | request, 71 | response); 72 | } 73 | if (response.getStatusCode() == 204) { 74 | // Apparently some proxies/gateways return 204 but with content 75 | return null; 76 | } 77 | String contentType = response.getFirstHeader(CONTENT_TYPE); 78 | if (contentType == null) 79 | { 80 | throw new UnexpectedResponseException("Content-Type is not set for response", request, response); 81 | } 82 | if (!MediaType.parse(contentType).is(MEDIA_TYPE_JSON)) 83 | { 84 | throw new UnexpectedResponseException("Expected application/json response from server but got " + contentType, request, response); 85 | } 86 | 87 | Reader reader = null; 88 | try{ 89 | if (response.getInputStream() == null) 90 | { 91 | return null; 92 | } 93 | 94 | reader = new InputStreamReader(response.getInputStream(), StandardCharsets.UTF_8); 95 | 96 | if (response.getStatusCode() == 400) 97 | { 98 | ErrorResponse error = mapper.fromJson(reader, ErrorResponse.class); 99 | throw new UnexpectedResponseException( 100 | String.format("Expected response code to be %s, but was %d: %s", successfulResponseCodes, response.getStatusCode(), error.toString()), 101 | request, 102 | response); 103 | } 104 | else 105 | { 106 | return mapper.fromJson(reader, type); 107 | } 108 | } 109 | catch (IOException e) 110 | { 111 | throw new RuntimeException("Error reading JSON response from server", e); 112 | } 113 | catch (JsonIOException | JsonSyntaxException e) 114 | { 115 | throw new IllegalArgumentException("Unable to create parse JSON response:\n", e); 116 | } 117 | finally 118 | { 119 | if (reader != null) 120 | { 121 | try 122 | { 123 | reader.close(); 124 | } 125 | catch (IOException e) 126 | { 127 | //noinspection ThrowFromFinallyBlock 128 | throw new RuntimeException("Error closing reader ", e); 129 | } 130 | } 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/ErrorResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response; 17 | 18 | import java.util.Collections; 19 | import java.util.List; 20 | 21 | /** 22 | * List of errors returned by KairosDB. 23 | */ 24 | public class ErrorResponse 25 | { 26 | private List errors; 27 | 28 | @SuppressWarnings("unused") 29 | public ErrorResponse(List errors) 30 | { 31 | this.errors = errors; 32 | } 33 | 34 | @SuppressWarnings("unused") 35 | public ErrorResponse(String error) 36 | { 37 | errors = Collections.singletonList(error); 38 | } 39 | 40 | @SuppressWarnings("unused") 41 | public List getErrors() 42 | { 43 | return (errors); 44 | } 45 | 46 | @Override 47 | public String toString() 48 | { 49 | StringBuilder builder = new StringBuilder("Errors: "); 50 | for (String error : errors) 51 | { 52 | builder.append(error).append("\n"); 53 | } 54 | 55 | return builder.toString(); 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/Group.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response; 17 | 18 | public interface Group 19 | { 20 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/GroupResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response; 17 | 18 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 19 | 20 | public abstract class GroupResult 21 | { 22 | private String name; 23 | 24 | protected GroupResult(String name) 25 | { 26 | this.name = checkNotNullOrEmpty(name); 27 | } 28 | 29 | public String getName() 30 | { 31 | return name; 32 | } 33 | 34 | @Override 35 | public boolean equals(Object o) 36 | { 37 | if (this == o) return true; 38 | if (!(o instanceof GroupResult)) return false; 39 | 40 | GroupResult that = (GroupResult) o; 41 | 42 | if (!name.equals(that.name)) return false; 43 | 44 | return true; 45 | } 46 | 47 | @Override 48 | public int hashCode() 49 | { 50 | return name.hashCode(); 51 | } 52 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/JsonResponseHandler.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | import org.apache.http.client.methods.HttpUriRequest; 4 | 5 | public interface JsonResponseHandler 6 | { 7 | T handleException(HttpUriRequest request, Exception exception) 8 | throws RuntimeException; 9 | 10 | T handle(HttpUriRequest request, ResponseHelper response) 11 | throws RuntimeException; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/QueryResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response; 17 | 18 | import com.google.common.base.MoreObjects; 19 | import com.google.common.collect.ImmutableList; 20 | 21 | import java.util.List; 22 | 23 | import static java.util.Objects.requireNonNull; 24 | 25 | /** 26 | Response returned by KairosDB. 27 | */ 28 | public class QueryResponse 29 | { 30 | private List queries; 31 | 32 | public QueryResponse(List queries) 33 | { 34 | requireNonNull(queries, "queries cannot be null"); 35 | this.queries = queries; 36 | } 37 | 38 | @SuppressWarnings("unused") 39 | public List getQueries() 40 | { 41 | return queries == null ? ImmutableList.of() : queries; 42 | } 43 | 44 | @Override 45 | public boolean equals(Object o) 46 | { 47 | if (this == o) return true; 48 | if (o == null || getClass() != o.getClass()) return false; 49 | 50 | QueryResponse that = (QueryResponse) o; 51 | 52 | return queries.equals(that.queries); 53 | 54 | } 55 | 56 | @Override 57 | public int hashCode() 58 | { 59 | return queries.hashCode(); 60 | } 61 | 62 | @Override 63 | public String toString() 64 | { 65 | return MoreObjects.toStringHelper(this) 66 | .add("queries", queries) 67 | .toString(); 68 | } 69 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/QueryResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response; 17 | 18 | import com.google.common.base.MoreObjects; 19 | import com.google.gson.annotations.SerializedName; 20 | 21 | import java.util.List; 22 | 23 | /** 24 | * Resulting object from a Query. 25 | */ 26 | public class QueryResult 27 | { 28 | private List results; 29 | 30 | @SerializedName("sample_size") 31 | private long sampleSize; 32 | 33 | public QueryResult(List results, long sampleSize) 34 | { 35 | this.results = results; 36 | this.sampleSize = sampleSize; 37 | } 38 | 39 | public List getResults() 40 | { 41 | return results; 42 | } 43 | 44 | /** 45 | * Returns the number of data points returned by the query prior to aggregation. Aggregation by reduce the number 46 | * of data points actually returned. 47 | * 48 | * @return number of data points returned by the query 49 | */ 50 | public long getSampleSize() 51 | { 52 | return sampleSize; 53 | } 54 | 55 | public Result getFirstResultByGroup(GroupResult matchingGroup) 56 | { 57 | for (Result result : results) 58 | { 59 | if (result != null) 60 | { 61 | for (GroupResult groupResult : result.getGroupResults()) 62 | { 63 | if (matchingGroup.equals(groupResult)) 64 | return (result); 65 | } 66 | } 67 | } 68 | 69 | return null; 70 | } 71 | 72 | @Override 73 | public boolean equals(Object o) 74 | { 75 | if (this == o) return true; 76 | if (o == null || getClass() != o.getClass()) return false; 77 | 78 | QueryResult that = (QueryResult) o; 79 | 80 | if (sampleSize != that.sampleSize) return false; 81 | return results != null ? results.equals(that.results) : that.results == null; 82 | 83 | } 84 | 85 | @Override 86 | public int hashCode() 87 | { 88 | int result = results != null ? results.hashCode() : 0; 89 | result = 31 * result + (int) (sampleSize ^ (sampleSize >>> 32)); 90 | return result; 91 | } 92 | 93 | @Override 94 | public String toString() 95 | { 96 | return MoreObjects.toStringHelper(this) 97 | .add("results", results) 98 | .add("sampleSize", sampleSize) 99 | .toString(); 100 | } 101 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/QueryTagResponse.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | import com.google.common.base.MoreObjects; 4 | import com.google.common.collect.ImmutableList; 5 | 6 | import static java.util.Objects.requireNonNull; 7 | 8 | import java.util.List; 9 | 10 | 11 | /** 12 | * Response returned by KairosDB. 13 | */ 14 | public class QueryTagResponse 15 | { 16 | private List queries; 17 | 18 | @SuppressWarnings("WeakerAccess") 19 | public QueryTagResponse(List queries) 20 | { 21 | requireNonNull(queries, "queries cannot be null"); 22 | this.queries = queries; 23 | } 24 | 25 | @SuppressWarnings("unused") 26 | public List getQueries() 27 | { 28 | return queries == null ? ImmutableList.of() : queries; 29 | } 30 | 31 | @Override 32 | public boolean equals(Object o) 33 | { 34 | if (this == o) return true; 35 | if (o == null || getClass() != o.getClass()) return false; 36 | 37 | QueryTagResponse that = (QueryTagResponse) o; 38 | 39 | return queries != null ? queries.equals(that.queries) : that.queries == null; 40 | } 41 | 42 | @Override 43 | public int hashCode() 44 | { 45 | return queries != null ? queries.hashCode() : 0; 46 | } 47 | 48 | @Override 49 | public String toString() 50 | { 51 | return MoreObjects.toStringHelper(this) 52 | .add("queries", queries) 53 | .toString(); 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/ResponseHelper.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | import org.apache.commons.lang.NotImplementedException; 4 | import org.apache.http.Header; 5 | import org.apache.http.HttpResponse; 6 | 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | 10 | public class ResponseHelper 11 | { 12 | private final HttpResponse response; 13 | 14 | public ResponseHelper(HttpResponse response) 15 | { 16 | this.response = response; 17 | } 18 | 19 | public int getStatusCode() 20 | { 21 | return response.getStatusLine().getStatusCode(); 22 | } 23 | 24 | public String getStatusMessage() 25 | { 26 | return response.getStatusLine().getReasonPhrase(); 27 | } 28 | 29 | public HttpResponse getResponse() 30 | { 31 | return response; 32 | } 33 | 34 | public String getFirstHeader(String key) 35 | { 36 | Header header = response.getFirstHeader(key); 37 | if (header != null) 38 | return header.getValue(); 39 | else 40 | return null; 41 | } 42 | 43 | /*public ListMultimap getHeaders() 44 | { 45 | ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); 46 | for (Header header : response.getAllHeaders()) 47 | { 48 | builder.put(HeaderName.of(header.getName()), header.getValue()); 49 | } 50 | return builder.build(); 51 | }*/ 52 | 53 | public long getBytesRead() 54 | { 55 | throw new NotImplementedException(); 56 | } 57 | 58 | public InputStream getInputStream() throws IOException 59 | { 60 | if (response.getEntity() != null) 61 | return response.getEntity().getContent(); 62 | return null; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/Result.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response; 17 | 18 | import com.google.common.base.MoreObjects; 19 | import com.google.gson.annotations.SerializedName; 20 | import org.kairosdb.client.builder.DataPoint; 21 | 22 | import java.util.Collections; 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | /** 27 | * Query Results. This is the results of a single query. 28 | */ 29 | public class Result 30 | { 31 | private String name; 32 | private Map> tags; 33 | 34 | @SerializedName("values") 35 | private List dataPoints; 36 | 37 | @SerializedName("group_by") 38 | private List groupResults; 39 | 40 | public Result(String name, 41 | Map> tags, 42 | List dataPoints, 43 | List groupResults) 44 | { 45 | this.name = name; 46 | this.tags = tags; 47 | this.groupResults = groupResults; 48 | this.dataPoints = dataPoints; 49 | } 50 | 51 | public String getName() 52 | { 53 | return name; 54 | } 55 | 56 | public List getDataPoints() 57 | { 58 | return dataPoints != null ? dataPoints : Collections.EMPTY_LIST; 59 | } 60 | 61 | public Map> getTags() 62 | { 63 | return tags != null ? tags : Collections.emptyMap(); 64 | } 65 | 66 | @SuppressWarnings("WeakerAccess") 67 | public List getGroupResults() 68 | { 69 | return groupResults != null ? groupResults : Collections.EMPTY_LIST; 70 | } 71 | 72 | @Override 73 | public boolean equals(Object o) 74 | { 75 | if (this == o) return true; 76 | if (o == null || getClass() != o.getClass()) return false; 77 | 78 | Result result = (Result) o; 79 | 80 | if (!name.equals(result.name)) return false; 81 | if (!tags.equals(result.tags)) return false; 82 | if (!dataPoints.equals(result.dataPoints)) return false; 83 | return groupResults.equals(result.groupResults); 84 | 85 | } 86 | 87 | @Override 88 | public int hashCode() 89 | { 90 | int result = name.hashCode(); 91 | result = 31 * result + tags.hashCode(); 92 | result = 31 * result + dataPoints.hashCode(); 93 | result = 31 * result + groupResults.hashCode(); 94 | return result; 95 | } 96 | 97 | @Override 98 | public String toString() 99 | { 100 | return MoreObjects.toStringHelper(this) 101 | .add("name", name) 102 | .add("tags", tags) 103 | .add("dataPoints", dataPoints) 104 | .add("groupResults", groupResults) 105 | .toString(); 106 | } 107 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/TagQueryResult.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | import com.google.common.base.MoreObjects; 4 | import com.google.common.collect.ImmutableList; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * Resulting object from a tag query. 10 | */ 11 | public class TagQueryResult 12 | { 13 | private List results; 14 | 15 | public TagQueryResult(List results) 16 | { 17 | this.results = results; 18 | } 19 | 20 | public List getResults() 21 | { 22 | return results == null ? ImmutableList.of(): results; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object o) 27 | { 28 | if (this == o) return true; 29 | if (o == null || getClass() != o.getClass()) return false; 30 | 31 | TagQueryResult that = (TagQueryResult) o; 32 | 33 | return results != null ? results.equals(that.results) : that.results == null; 34 | 35 | } 36 | 37 | @Override 38 | public int hashCode() 39 | { 40 | return results != null ? results.hashCode() : 0; 41 | } 42 | 43 | @Override 44 | public String toString() 45 | { 46 | return MoreObjects.toStringHelper(this) 47 | .add("results", results) 48 | .toString(); 49 | } 50 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/TagResult.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | import com.google.common.base.MoreObjects; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * Tag Query Results. This is the results of a single query. 10 | */ 11 | public class TagResult 12 | { 13 | private String name; 14 | private Map> tags; 15 | 16 | public TagResult(String name, Map> tags) 17 | { 18 | this.name = name; 19 | this.tags = tags; 20 | } 21 | 22 | public String getName() 23 | { 24 | return name; 25 | } 26 | 27 | public Map> getTags() 28 | { 29 | return tags; 30 | } 31 | 32 | @Override 33 | public boolean equals(Object o) 34 | { 35 | if (this == o) return true; 36 | if (o == null || getClass() != o.getClass()) return false; 37 | 38 | TagResult tagResult = (TagResult) o; 39 | 40 | return name != null ? name.equals(tagResult.name) : tagResult.name == null && 41 | (tags != null ? tags.equals(tagResult.tags) : tagResult.tags == null); 42 | } 43 | 44 | @Override 45 | public int hashCode() 46 | { 47 | int result = name != null ? name.hashCode() : 0; 48 | result = 31 * result + (tags != null ? tags.hashCode() : 0); 49 | return result; 50 | } 51 | 52 | @Override 53 | public String toString() 54 | { 55 | return MoreObjects.toStringHelper(this) 56 | .add("name", name) 57 | .add("tags", tags) 58 | .toString(); 59 | } 60 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/UnexpectedResponseException.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | import org.apache.http.Header; 4 | import org.apache.http.client.methods.HttpUriRequest; 5 | 6 | import javax.annotation.Nullable; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import static com.google.common.base.MoreObjects.toStringHelper; 11 | 12 | public class UnexpectedResponseException extends RuntimeException 13 | { 14 | private final HttpUriRequest request; 15 | private final int statusCode; 16 | private final String statusMessage; 17 | private final ResponseHelper response; 18 | 19 | public UnexpectedResponseException(HttpUriRequest request, ResponseHelper response) 20 | { 21 | this(String.format("%d: %s", response.getStatusCode(), response.getStatusMessage()), 22 | request, 23 | response.getStatusCode(), 24 | response.getStatusMessage(), 25 | response); 26 | } 27 | 28 | public UnexpectedResponseException(String message, HttpUriRequest request, ResponseHelper response) 29 | { 30 | this(message, 31 | request, 32 | response.getStatusCode(), 33 | response.getStatusMessage(), 34 | response); 35 | } 36 | 37 | public UnexpectedResponseException(String message, HttpUriRequest request, int statusCode, String statusMessage, ResponseHelper response) 38 | { 39 | super(message); 40 | this.request = request; 41 | this.statusCode = statusCode; 42 | this.statusMessage = statusMessage; 43 | this.response = response; 44 | } 45 | 46 | public int getStatusCode() 47 | { 48 | return statusCode; 49 | } 50 | 51 | public String getStatusMessage() 52 | { 53 | return statusMessage; 54 | } 55 | 56 | @Nullable 57 | public String getHeader(String name) 58 | { 59 | List values = getHeaders(name); 60 | if (values.isEmpty()) { 61 | return null; 62 | } 63 | return values.get(0); 64 | } 65 | 66 | public List getHeaders(String name) 67 | { 68 | Header[] headers = response.getResponse().getHeaders(name); 69 | List ret = new ArrayList<>(); 70 | if (headers != null) 71 | { 72 | for (Header header : headers) 73 | { 74 | ret.add(header.getValue()); 75 | } 76 | } 77 | 78 | return ret; 79 | } 80 | 81 | 82 | @Override 83 | public String toString() 84 | { 85 | return toStringHelper(this) 86 | .add("request", request) 87 | .add("statusCode", statusCode) 88 | .add("statusMessage", statusMessage) 89 | .add("headers", response.getResponse().getAllHeaders()) 90 | .toString(); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/grouping/BinGroupResult.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | import org.kairosdb.client.response.GroupResult; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import static java.util.Objects.requireNonNull; 10 | 11 | 12 | /** 13 | * Grouping by bins. 14 | */ 15 | public class BinGroupResult extends GroupResult 16 | { 17 | @SerializedName("bins") 18 | private List bins; 19 | 20 | @SerializedName("group") 21 | private Map group; 22 | 23 | public BinGroupResult(List bins, Map group) 24 | { 25 | super("bin"); 26 | this.bins = requireNonNull(bins); 27 | this.group = requireNonNull(group); 28 | } 29 | 30 | /** 31 | * List of bins that the results were grouped by. 32 | * 33 | * @return bins bins that results were grouped by 34 | */ 35 | public List getBins() 36 | { 37 | return bins; 38 | } 39 | 40 | /** 41 | * Returns the bin number. 42 | * 43 | * @return bin number 44 | */ 45 | public int getBinNumber() 46 | { 47 | return group.get("bin_number"); 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/grouping/CustomGroupResult.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import org.kairosdb.client.response.GroupResult; 4 | 5 | import java.util.Map; 6 | 7 | public class CustomGroupResult extends GroupResult 8 | { 9 | private Map properties; 10 | 11 | public CustomGroupResult(Map properties) 12 | { 13 | super((String) properties.get("name")); 14 | this.properties = properties; 15 | } 16 | 17 | public Map getProperties() 18 | { 19 | return properties; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/grouping/DefaultGroupResult.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import com.google.common.base.MoreObjects; 4 | import org.kairosdb.client.response.GroupResult; 5 | 6 | import static org.kairosdb.client.util.Preconditions.checkNotNullOrEmpty; 7 | 8 | /** 9 | * Group that represents natural grouping based on the type of the data. 10 | */ 11 | public class DefaultGroupResult extends GroupResult 12 | { 13 | private String type; 14 | 15 | @SuppressWarnings("WeakerAccess") 16 | public DefaultGroupResult(String name, String type) 17 | { 18 | super(name); 19 | this.type = checkNotNullOrEmpty(type); 20 | } 21 | 22 | /** 23 | * Returns the type of data. 24 | * 25 | * @return type of the data 26 | */ 27 | public String getType() 28 | { 29 | return type; 30 | } 31 | 32 | @Override 33 | public boolean equals(Object o) 34 | { 35 | if (this == o) return true; 36 | if (!(o instanceof DefaultGroupResult)) return false; 37 | if (!super.equals(o)) return false; 38 | 39 | DefaultGroupResult that = (DefaultGroupResult) o; 40 | 41 | return type.equals(that.type); 42 | } 43 | 44 | @Override 45 | public int hashCode() 46 | { 47 | int result = super.hashCode(); 48 | result = 31 * result + type.hashCode(); 49 | return result; 50 | } 51 | 52 | @Override 53 | public String toString() 54 | { 55 | return MoreObjects.toStringHelper(this) 56 | .add("type", type) 57 | .toString(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/grouping/GroupingNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response.grouping; 17 | 18 | import com.google.common.base.MoreObjects; 19 | import com.google.gson.annotations.SerializedName; 20 | import org.kairosdb.client.response.Group; 21 | 22 | /** 23 | * How the results were grouped. This indicates the group number. 24 | */ 25 | public class GroupingNumber implements Group 26 | { 27 | @SerializedName("group_number") 28 | private int groupNumber; 29 | 30 | @SuppressWarnings("WeakerAccess") 31 | public GroupingNumber(int groupNumber) 32 | { 33 | this.groupNumber = groupNumber; 34 | } 35 | 36 | public int getGroupNumber() 37 | { 38 | return groupNumber; 39 | } 40 | 41 | @Override 42 | public boolean equals(Object o) 43 | { 44 | if (this == o) return true; 45 | if (o == null || getClass() != o.getClass()) return false; 46 | 47 | GroupingNumber that = (GroupingNumber) o; 48 | 49 | return groupNumber == that.groupNumber; 50 | } 51 | 52 | @Override 53 | public int hashCode() 54 | { 55 | return groupNumber; 56 | } 57 | 58 | @Override 59 | public String toString() 60 | { 61 | return MoreObjects.toStringHelper(this) 62 | .add("groupNumber", groupNumber) 63 | .toString(); 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/grouping/TagGroupResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response.grouping; 17 | 18 | import com.google.common.base.MoreObjects; 19 | import org.kairosdb.client.response.GroupResult; 20 | 21 | import java.util.List; 22 | import java.util.Map; 23 | 24 | import static java.util.Objects.requireNonNull; 25 | 26 | 27 | /** 28 | * Grouping by tags. 29 | */ 30 | public class TagGroupResult extends GroupResult 31 | { 32 | private List tags; 33 | private Map group; 34 | 35 | @SuppressWarnings("WeakerAccess") 36 | public TagGroupResult(List tags, Map group) 37 | { 38 | super("tag"); 39 | this.tags = requireNonNull(tags); 40 | this.group = requireNonNull(group); 41 | } 42 | 43 | /** 44 | * List of tag names that the results were grouped by. 45 | * 46 | * @return tag name that the results were grouped by 47 | */ 48 | public List getTags() 49 | { 50 | return tags; 51 | } 52 | 53 | /** 54 | * List of tag names and their corresponding values for this group. 55 | * 56 | * @return tags for this grouping 57 | */ 58 | public Map getGroup() 59 | { 60 | return group; 61 | } 62 | 63 | @Override 64 | public boolean equals(Object o) 65 | { 66 | if (this == o) return true; 67 | if (!(o instanceof TagGroupResult)) return false; 68 | if (!super.equals(o)) return false; 69 | 70 | TagGroupResult that = (TagGroupResult) o; 71 | 72 | if (!group.equals(that.group)) return false; 73 | return tags.equals(that.tags); 74 | } 75 | 76 | @Override 77 | public int hashCode() 78 | { 79 | int result = super.hashCode(); 80 | result = 31 * result + tags.hashCode(); 81 | result = 31 * result + group.hashCode(); 82 | return result; 83 | } 84 | 85 | @Override 86 | public String toString() 87 | { 88 | return MoreObjects.toStringHelper(this) 89 | .add("tags", tags) 90 | .add("group", group) 91 | .toString(); 92 | } 93 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/grouping/TimeGroupResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response.grouping; 17 | 18 | import com.google.common.base.MoreObjects; 19 | import com.google.gson.annotations.SerializedName; 20 | import org.kairosdb.client.builder.RelativeTime; 21 | import org.kairosdb.client.response.GroupResult; 22 | 23 | import static java.util.Objects.requireNonNull; 24 | import static org.kairosdb.client.util.Preconditions.checkArgument; 25 | 26 | 27 | public class TimeGroupResult extends GroupResult 28 | { 29 | @SerializedName("range_size") 30 | private RelativeTime rangeSize; 31 | 32 | @SerializedName("group_count") 33 | private int groupCount; 34 | private GroupingNumber group; 35 | 36 | @SuppressWarnings("WeakerAccess") 37 | public TimeGroupResult(RelativeTime rangeSize, 38 | int groupCount, 39 | GroupingNumber group) 40 | { 41 | super("time"); 42 | 43 | checkArgument(groupCount > 0); 44 | 45 | this.rangeSize = requireNonNull(rangeSize); 46 | this.groupCount = groupCount; 47 | this.group = requireNonNull(group); 48 | } 49 | 50 | /** 51 | * The size of each range for the group. 52 | * 53 | * @return range size of the group 54 | */ 55 | public RelativeTime getRangeSize() 56 | { 57 | return rangeSize; 58 | } 59 | 60 | /** 61 | * Number of groups. 62 | * 63 | * @return number of groups 64 | */ 65 | public int getGroupCount() 66 | { 67 | return groupCount; 68 | } 69 | 70 | /** 71 | * How the results were group. This indicates the group number. 72 | * 73 | * @return group number 74 | */ 75 | public GroupingNumber getGroup() 76 | { 77 | return group; 78 | } 79 | 80 | @Override 81 | public boolean equals(Object o) 82 | { 83 | if (this == o) return true; 84 | if (!(o instanceof TimeGroupResult)) return false; 85 | if (!super.equals(o)) return false; 86 | 87 | TimeGroupResult that = (TimeGroupResult) o; 88 | 89 | if (groupCount != that.groupCount) return false; 90 | if (!group.equals(that.group)) return false; 91 | return rangeSize.equals(that.rangeSize); 92 | } 93 | 94 | @Override 95 | public int hashCode() 96 | { 97 | int result = super.hashCode(); 98 | result = 31 * result + rangeSize.hashCode(); 99 | result = 31 * result + groupCount; 100 | result = 31 * result + group.hashCode(); 101 | return result; 102 | } 103 | 104 | @Override 105 | public String toString() 106 | { 107 | return MoreObjects.toStringHelper(this) 108 | .add("rangeSize", rangeSize) 109 | .add("groupCount", groupCount) 110 | .add("group", group) 111 | .toString(); 112 | } 113 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/response/grouping/ValueGroupResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.response.grouping; 17 | 18 | import com.google.common.base.MoreObjects; 19 | import com.google.gson.annotations.SerializedName; 20 | import org.kairosdb.client.response.GroupResult; 21 | 22 | import static java.util.Objects.requireNonNull; 23 | import static org.kairosdb.client.util.Preconditions.checkArgument; 24 | 25 | 26 | /** 27 | * Results from a ValueGrouper. The group field is group number the results were placed into. 28 | */ 29 | public class ValueGroupResult extends GroupResult 30 | { 31 | @SerializedName("range_size") 32 | private int rangeSize; 33 | 34 | private GroupingNumber group; 35 | 36 | @SuppressWarnings("WeakerAccess") 37 | public ValueGroupResult(int rangeSize, GroupingNumber group) 38 | { 39 | super("value"); 40 | 41 | checkArgument(rangeSize > 0); 42 | 43 | this.rangeSize = rangeSize; 44 | this.group = requireNonNull(group); 45 | } 46 | 47 | /** 48 | * The size of each range for the group. 49 | * 50 | * @return range size of the group 51 | */ 52 | public int getRangeSize() 53 | { 54 | return rangeSize; 55 | } 56 | 57 | /** 58 | * How the results were group. This indicates the group number. 59 | * 60 | * @return group number 61 | */ 62 | public GroupingNumber getGroup() 63 | { 64 | return group; 65 | } 66 | 67 | @Override 68 | public boolean equals(Object o) 69 | { 70 | if (this == o) return true; 71 | if (!(o instanceof ValueGroupResult)) return false; 72 | if (!super.equals(o)) return false; 73 | 74 | ValueGroupResult that = (ValueGroupResult) o; 75 | 76 | if (rangeSize != that.rangeSize) return false; 77 | return group.equals(that.group); 78 | } 79 | 80 | @Override 81 | public int hashCode() 82 | { 83 | int result = super.hashCode(); 84 | result = 31 * result + rangeSize; 85 | result = 31 * result + group.hashCode(); 86 | return result; 87 | } 88 | 89 | @Override 90 | public String toString() 91 | { 92 | return MoreObjects.toStringHelper(this) 93 | .add("rangeSize", rangeSize) 94 | .add("group", group) 95 | .toString(); 96 | } 97 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/serializer/CustomAggregatorSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.serializer; 17 | 18 | 19 | import com.google.gson.*; 20 | import org.kairosdb.client.builder.aggregator.CustomAggregator; 21 | 22 | import java.lang.reflect.Type; 23 | 24 | /** 25 | * Used by the JSON parser to serialize a custom aggregator. 26 | */ 27 | public class CustomAggregatorSerializer implements JsonSerializer 28 | { 29 | @Override 30 | public JsonElement serialize(CustomAggregator src, Type typeOfSrc, JsonSerializationContext context) 31 | { 32 | JsonParser parser = new JsonParser(); 33 | return parser.parse(src.toJson()); 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/serializer/CustomGrouperSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.serializer; 17 | 18 | import com.google.gson.*; 19 | import org.kairosdb.client.builder.grouper.CustomGrouper; 20 | 21 | import java.lang.reflect.Type; 22 | 23 | public class CustomGrouperSerializer implements JsonSerializer 24 | { 25 | @Override 26 | public JsonElement serialize(CustomGrouper src, Type typeOfSrc, JsonSerializationContext context) 27 | { 28 | JsonParser parser = new JsonParser(); 29 | return parser.parse(src.toJson()); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/serializer/DataPointSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.serializer; 17 | 18 | import com.google.gson.*; 19 | import org.kairosdb.client.builder.DataPoint; 20 | 21 | import java.lang.reflect.Type; 22 | 23 | /** 24 | * Used by the JSON parser to serialize a DataPoint. 25 | */ 26 | public class DataPointSerializer implements JsonSerializer 27 | { 28 | @Override 29 | public JsonElement serialize(DataPoint src, Type typeOfSrc, JsonSerializationContext context) 30 | { 31 | JsonArray array = new JsonArray(); 32 | array.add(new JsonPrimitive(src.getTimestamp())); 33 | array.add(context.serialize(src.getValue())); 34 | return array; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/serializer/ListMultiMapSerializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.serializer; 2 | 3 | import com.google.common.collect.ListMultimap; 4 | import com.google.gson.JsonElement; 5 | import com.google.gson.JsonSerializationContext; 6 | import com.google.gson.JsonSerializer; 7 | 8 | import java.lang.reflect.Type; 9 | 10 | public class ListMultiMapSerializer implements JsonSerializer 11 | { 12 | @Override 13 | public JsonElement serialize(ListMultimap src, Type typeOfSrc, JsonSerializationContext context) 14 | { 15 | return context.serialize(src.asMap()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/serializer/OrderSerializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.serializer; 2 | 3 | import com.google.gson.JsonElement; 4 | import com.google.gson.JsonParser; 5 | import com.google.gson.JsonSerializationContext; 6 | import com.google.gson.JsonSerializer; 7 | import org.kairosdb.client.builder.QueryMetric; 8 | 9 | import java.lang.reflect.Type; 10 | 11 | public class OrderSerializer implements JsonSerializer 12 | { 13 | @Override 14 | public JsonElement serialize(QueryMetric.Order order, Type type, JsonSerializationContext jsonSerializationContext) 15 | { 16 | JsonParser parser = new JsonParser(); 17 | return parser.parse(order.toString()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/serializer/TimeZoneSerializer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.serializer; 2 | 3 | import com.google.gson.*; 4 | 5 | import java.lang.reflect.Type; 6 | import java.util.TimeZone; 7 | 8 | public class TimeZoneSerializer implements JsonSerializer 9 | { 10 | @Override 11 | public JsonElement serialize(TimeZone timeZone, Type type, JsonSerializationContext jsonSerializationContext) 12 | { 13 | return new JsonPrimitive(timeZone.getID()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/util/Exceptions.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.util; 2 | 3 | import com.google.common.base.Throwables; 4 | import org.apache.http.client.methods.HttpUriRequest; 5 | 6 | import java.io.IOException; 7 | import java.net.ConnectException; 8 | 9 | public class Exceptions 10 | { 11 | public static RuntimeException propagate(HttpUriRequest request, Throwable exception) 12 | { 13 | if (exception instanceof ConnectException) { 14 | throw new RuntimeException("Server refused connection: " + request.getURI().toASCIIString(), (ConnectException) exception); 15 | } 16 | if (exception instanceof IOException) { 17 | throw new RuntimeException((IOException) exception); 18 | } 19 | throw Throwables.propagate(exception); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/kairosdb/client/util/Preconditions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.util; 17 | 18 | import com.google.common.annotations.VisibleForTesting; 19 | import javax.annotation.Nullable; 20 | 21 | import static java.util.Objects.requireNonNull; 22 | 23 | public class Preconditions 24 | { 25 | public static String checkNotNullOrEmpty(String reference) { 26 | requireNonNull(reference); 27 | if (reference.isEmpty()) 28 | { 29 | throw new IllegalArgumentException(); 30 | } 31 | return reference; 32 | } 33 | 34 | public static String checkNotNullOrEmpty(String reference, 35 | @Nullable String errorMessageTemplate, 36 | @Nullable Object... errorMessageArgs) { 37 | if (reference == null) 38 | throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); 39 | 40 | if (reference.isEmpty()) 41 | { 42 | throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); 43 | 44 | } 45 | return reference; 46 | } 47 | 48 | public static void checkArgument(boolean expression, @Nullable Object errorMessage) { 49 | if (!expression) { 50 | throw new IllegalArgumentException(String.valueOf(errorMessage)); 51 | } 52 | } 53 | 54 | public static void checkArgument(boolean expression) { 55 | if (!expression) { 56 | throw new IllegalArgumentException(); 57 | } 58 | } 59 | 60 | public static void checkState(boolean expression, @Nullable Object errorMessage) { 61 | if (!expression) { 62 | throw new IllegalStateException(String.valueOf(errorMessage)); 63 | } 64 | } 65 | 66 | /** 67 | * Copied from Google's Precondition class because it is package protected. 68 | * 69 | * Substitutes each {@code %s} in {@code template} with an argument. These 70 | * are matched by position - the first {@code %s} gets {@code args[0]}, etc. 71 | * If there are more arguments than placeholders, the unmatched arguments will 72 | * be appended to the end of the formatted message in square braces. 73 | * 74 | * @param template a non-null string containing 0 or more {@code %s} 75 | * placeholders. 76 | * @param args the arguments to be substituted into the message 77 | * template. Arguments are converted to strings using 78 | * {@link String#valueOf(Object)}. Arguments can be null. 79 | */ 80 | @VisibleForTesting 81 | static String format(String template, 82 | @Nullable Object... args) { 83 | template = String.valueOf(template); // null -> "null" 84 | 85 | // start substituting the arguments into the '%s' placeholders 86 | StringBuilder builder = new StringBuilder( 87 | template.length() + 16 * args.length); 88 | int templateStart = 0; 89 | int i = 0; 90 | while (i < args.length) { 91 | int placeholderStart = template.indexOf("%s", templateStart); 92 | if (placeholderStart == -1) { 93 | break; 94 | } 95 | builder.append(template.substring(templateStart, placeholderStart)); 96 | builder.append(args[i++]); 97 | templateStart = placeholderStart + 2; 98 | } 99 | builder.append(template.substring(templateStart)); 100 | 101 | // if we run out of placeholders, append the extra args in square braces 102 | if (i < args.length) { 103 | builder.append(" ["); 104 | builder.append(args[i++]); 105 | while (i < args.length) { 106 | builder.append(", "); 107 | builder.append(args[i++]); 108 | } 109 | builder.append(']'); 110 | } 111 | 112 | return builder.toString(); 113 | } 114 | 115 | 116 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/ComplexNumberDataPoint.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | 4 | import com.google.inject.Inject; 5 | import org.json.JSONException; 6 | import org.json.JSONWriter; 7 | import org.kairosdb.core.DataPoint; 8 | import org.kairosdb.core.datastore.DataPointGroup; 9 | 10 | import java.io.DataOutput; 11 | import java.io.IOException; 12 | 13 | public class ComplexNumberDataPoint implements DataPoint 14 | { 15 | private long real; 16 | private long imaginary; 17 | private long timestamp; 18 | 19 | @Inject 20 | public ComplexNumberDataPoint(long timestamp, long real, long imaginary) 21 | { 22 | this.real = real; 23 | this.imaginary = imaginary; 24 | this.timestamp = timestamp; 25 | } 26 | 27 | public long getReal() 28 | { 29 | return real; 30 | } 31 | 32 | public long getImaginary() 33 | { 34 | return imaginary; 35 | } 36 | 37 | @Override 38 | public long getTimestamp() 39 | { 40 | return timestamp; 41 | } 42 | 43 | @Override 44 | public void setTimestamp(long timestamp) 45 | { 46 | this.timestamp = timestamp; 47 | } 48 | 49 | @Override 50 | public void writeValueToBuffer(DataOutput buffer) throws IOException 51 | { 52 | buffer.writeLong(real); 53 | buffer.writeLong(imaginary); 54 | } 55 | 56 | @Override 57 | public void writeValueToJson(JSONWriter writer) throws JSONException 58 | { 59 | writer.object().key("real").value(real).key("imaginary").value(imaginary).endObject(); 60 | } 61 | 62 | @Override 63 | public String getApiDataType() 64 | { 65 | return null; 66 | } 67 | 68 | @Override 69 | public String getDataStoreDataType() 70 | { 71 | return "jsabin-complex"; 72 | } 73 | 74 | @Override 75 | public boolean isLong() 76 | { 77 | return false; 78 | } 79 | 80 | @Override 81 | public long getLongValue() 82 | { 83 | return 0; 84 | } 85 | 86 | @Override 87 | public boolean isDouble() 88 | { 89 | return false; 90 | } 91 | 92 | @Override 93 | public double getDoubleValue() 94 | { 95 | return 0; 96 | } 97 | 98 | @Override 99 | public DataPointGroup getDataPointGroup() 100 | { 101 | return null; 102 | } 103 | 104 | @Override 105 | public void setDataPointGroup(DataPointGroup dataPointGroup) 106 | { 107 | } 108 | 109 | @Override 110 | public boolean equals(Object o) 111 | { 112 | if (this == o) 113 | { 114 | return true; 115 | } 116 | if (o == null || getClass() != o.getClass()) 117 | { 118 | return false; 119 | } 120 | 121 | ComplexNumberDataPoint that = (ComplexNumberDataPoint) o; 122 | 123 | return imaginary == that.imaginary && real == that.real && timestamp == that.timestamp; 124 | 125 | } 126 | 127 | @Override 128 | public int hashCode() 129 | { 130 | int result = (int) (real ^ (real >>> 32)); 131 | result = 31 * result + (int) (imaginary ^ (imaginary >>> 32)); 132 | result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); 133 | return result; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/ComplexNumberDataPointFactory.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import com.google.gson.JsonElement; 4 | import com.google.gson.JsonObject; 5 | import org.kairosdb.core.DataPoint; 6 | import org.kairosdb.core.datapoints.DataPointFactory; 7 | import org.kairosdb.util.KDataInput; 8 | 9 | import java.io.DataInput; 10 | import java.io.IOException; 11 | 12 | public class ComplexNumberDataPointFactory implements DataPointFactory 13 | { 14 | @Override 15 | public String getDataStoreType() 16 | { 17 | return "jsabin-complex"; 18 | } 19 | 20 | @Override 21 | public String getGroupType() 22 | { 23 | return "complex"; 24 | } 25 | 26 | @Override 27 | public DataPoint getDataPoint(long timestamp, JsonElement json) throws IOException 28 | { 29 | JsonObject complex = json.getAsJsonObject(); 30 | return new ComplexNumberDataPoint(timestamp, complex.get("real").getAsLong(), complex.get("imaginary").getAsLong()); 31 | } 32 | 33 | @Override 34 | public DataPoint getDataPoint(long timestamp, KDataInput buffer) throws IOException 35 | { 36 | return new ComplexNumberDataPoint(timestamp, buffer.readLong(), buffer.readLong()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/CustomDataModule.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import com.google.inject.Binder; 4 | import com.google.inject.Module; 5 | import com.google.inject.Scopes; 6 | 7 | public class CustomDataModule implements Module 8 | { 9 | @Override 10 | public void configure(Binder binder) 11 | { 12 | binder.bind(ComplexNumberDataPointFactory.class).in(Scopes.SINGLETON); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/InMemoryKairosServer.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import org.apache.commons.io.FileUtils; 4 | import org.kairosdb.core.Main; 5 | import org.kairosdb.core.exception.DatastoreException; 6 | import org.kairosdb.core.exception.KairosDBException; 7 | 8 | import java.io.File; 9 | import java.io.IOException; 10 | 11 | public class InMemoryKairosServer extends Thread 12 | { 13 | private Main kairos; 14 | private boolean started; 15 | private File properties; 16 | 17 | public InMemoryKairosServer() 18 | { 19 | } 20 | 21 | public InMemoryKairosServer(File properties) 22 | { 23 | this.properties = properties; 24 | } 25 | 26 | public void run() 27 | { 28 | try 29 | { 30 | // delete H2DB cache 31 | File h2db = new File("build/h2db"); 32 | if (h2db.exists()) 33 | { 34 | FileUtils.deleteDirectory(h2db); 35 | } 36 | 37 | kairos = new Main(properties); 38 | kairos.startServices(); 39 | setStarted(); 40 | } 41 | catch (KairosDBException e) 42 | { 43 | e.printStackTrace(); 44 | } 45 | catch (IOException e) 46 | { 47 | e.printStackTrace(); 48 | } 49 | } 50 | 51 | public TestDataPointListener getDataPointListener() 52 | { 53 | return ListenerModule.listener; 54 | } 55 | 56 | public synchronized boolean isStarted() 57 | { 58 | return started; 59 | } 60 | 61 | private synchronized void setStarted() 62 | { 63 | started = true; 64 | } 65 | 66 | public void shutdown() throws InterruptedException, DatastoreException 67 | { 68 | kairos.stopServices(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/ListenerModule.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import com.google.inject.Binder; 4 | import com.google.inject.Module; 5 | 6 | public class ListenerModule implements Module 7 | { 8 | public static TestDataPointListener listener = new TestDataPointListener(); 9 | 10 | @Override 11 | public void configure(Binder binder) 12 | { 13 | binder.bind(TestDataPointListener.class).toInstance(listener); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/TestDataPointListener.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client; 2 | 3 | import org.kairosdb.eventbus.Subscribe; 4 | import org.kairosdb.events.DataPointEvent; 5 | 6 | public class TestDataPointListener 7 | { 8 | private org.kairosdb.events.DataPointEvent event; 9 | 10 | @Subscribe 11 | public void dataPoint(org.kairosdb.events.DataPointEvent event) 12 | { 13 | this.event = event; 14 | } 15 | 16 | public DataPointEvent getEvent() 17 | { 18 | return event; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/CustomAggregatorTest.java: -------------------------------------------------------------------------------- 1 | // 2 | // CustomAggregatorTest.java 3 | // 4 | // Copyright 2013, Proofpoint Inc. All rights reserved. 5 | // 6 | package org.kairosdb.client.builder; 7 | 8 | import org.junit.Test; 9 | import org.kairosdb.client.builder.aggregator.CustomAggregator; 10 | 11 | import static org.hamcrest.CoreMatchers.equalTo; 12 | import static org.junit.Assert.assertThat; 13 | 14 | public class CustomAggregatorTest 15 | { 16 | @Test(expected = NullPointerException.class) 17 | public void test_NullName_invalid() 18 | { 19 | new CustomAggregator(null, "json"); 20 | } 21 | 22 | @Test(expected = IllegalArgumentException.class) 23 | public void test_EmptyName_invalid() 24 | { 25 | new CustomAggregator("", "json"); 26 | } 27 | 28 | @Test(expected = NullPointerException.class) 29 | public void test_NullJSON_invalid() 30 | { 31 | new CustomAggregator("name", null); 32 | } 33 | 34 | @Test(expected = IllegalArgumentException.class) 35 | public void test_EmptyJSON_invalid() 36 | { 37 | new CustomAggregator("name", ""); 38 | } 39 | 40 | @Test 41 | public void test() 42 | { 43 | CustomAggregator aggregator = new CustomAggregator("testAggregator", "{\"property1\":\"value1\", \"property2\": \"value2\"}"); 44 | 45 | assertThat(aggregator.toJson(), equalTo("{\"name\":\"testAggregator\",{\"property1\":\"value1\", \"property2\": \"value2\"}}")); 46 | } 47 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/DataPointTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import org.junit.Test; 19 | 20 | import static org.hamcrest.CoreMatchers.*; 21 | import static org.hamcrest.Matchers.equalTo; 22 | import static org.junit.Assert.assertThat; 23 | 24 | public class DataPointTest 25 | { 26 | 27 | @Test 28 | public void test_timestampNegative_valid() 29 | { 30 | DataPoint dataPoint = new DataPoint(-1, 3); 31 | 32 | assertThat(dataPoint.getTimestamp(), equalTo(-1L)); 33 | } 34 | 35 | @Test 36 | public void test_timestampZero_valid() 37 | { 38 | DataPoint dataPoint = new DataPoint(0, 3); 39 | 40 | assertThat(dataPoint.getTimestamp(), equalTo(0L)); 41 | } 42 | 43 | @Test 44 | public void test_constructor_longValue() throws DataFormatException 45 | { 46 | DataPoint dataPoint = new DataPoint(93939393, 30L); 47 | 48 | assertThat(dataPoint.longValue(), equalTo(30L)); 49 | assertThat(dataPoint.getValue(), instanceOf(Long.class)); 50 | assertThat(dataPoint.isIntegerValue(), equalTo(true)); 51 | assertThat(dataPoint.isDoubleValue(), equalTo(false)); 52 | } 53 | 54 | @Test 55 | public void test_constructor_doubleValue() throws DataFormatException 56 | { 57 | DataPoint dataPoint = new DataPoint(93939393, 30.3); 58 | 59 | assertThat(dataPoint.doubleValue(), equalTo(30.3)); 60 | assertThat(dataPoint.getValue(), instanceOf(Double.class)); 61 | assertThat(dataPoint.isIntegerValue(), equalTo(false)); 62 | assertThat(dataPoint.isDoubleValue(), equalTo(true)); 63 | } 64 | 65 | @Test 66 | public void test_constructor_integerValue() throws DataFormatException 67 | { 68 | DataPoint dataPoint = new DataPoint(93939393, 30); 69 | 70 | assertThat(dataPoint.longValue(), equalTo(30L)); 71 | assertThat(dataPoint.getValue(), instanceOf(Integer.class)); 72 | assertThat(dataPoint.isIntegerValue(), equalTo(true)); 73 | assertThat(dataPoint.isDoubleValue(), equalTo(false)); 74 | } 75 | 76 | @Test(expected = DataFormatException.class) 77 | public void test_longValue_wrong_type_invalid() throws DataFormatException 78 | { 79 | DataPoint dataPoint = new DataPoint(388383, "foo"); 80 | 81 | dataPoint.longValue(); 82 | } 83 | 84 | @Test(expected = DataFormatException.class) 85 | public void test_doubleValue_wrong_type_invalid() throws DataFormatException 86 | { 87 | DataPoint dataPoint = new DataPoint(388383, "foo"); 88 | 89 | dataPoint.doubleValue(); 90 | } 91 | 92 | @Test 93 | public void test_constructor_wholeValueIsDouble() throws DataFormatException 94 | { 95 | DataPoint dataPoint = new DataPoint(93939393, 5.0); 96 | 97 | assertThat(dataPoint.longValue(), equalTo(5L)); 98 | assertThat(dataPoint.getValue(), instanceOf(Double.class)); 99 | assertThat(dataPoint.isIntegerValue(), equalTo(true)); 100 | assertThat(dataPoint.isDoubleValue(), equalTo(false)); 101 | } 102 | 103 | @Test 104 | public void test_nullValue() throws DataFormatException 105 | { 106 | DataPoint dataPoint = new DataPoint(93939393, null); 107 | 108 | assertThat(dataPoint.getValue(), is(nullValue())); 109 | assertThat(dataPoint.isIntegerValue(), equalTo(false)); 110 | assertThat(dataPoint.isDoubleValue(), equalTo(false)); 111 | } 112 | 113 | @Test(expected = DataFormatException.class) 114 | public void test_nullValue_toDouble() throws DataFormatException 115 | { 116 | DataPoint dataPoint = new DataPoint(93939393, null); 117 | 118 | dataPoint.doubleValue(); 119 | } 120 | 121 | @Test(expected = DataFormatException.class) 122 | public void test_nullValue_toLong() throws DataFormatException 123 | { 124 | DataPoint dataPoint = new DataPoint(93939393, null); 125 | 126 | dataPoint.longValue(); 127 | } 128 | 129 | @Test(expected = DataFormatException.class) 130 | public void test_longValue_valueNull() throws DataFormatException 131 | { 132 | DataPoint dataPoint = new DataPoint(93939393, null); 133 | 134 | dataPoint.longValue(); 135 | } 136 | 137 | @Test(expected = DataFormatException.class) 138 | public void test_doubleValue_valueNull() throws DataFormatException 139 | { 140 | DataPoint dataPoint = new DataPoint(93939393, null); 141 | 142 | dataPoint.doubleValue(); 143 | } 144 | 145 | @Test(expected = DataFormatException.class) 146 | public void test_stringValue_valueNull() throws DataFormatException 147 | { 148 | DataPoint dataPoint = new DataPoint(93939393, null); 149 | 150 | dataPoint.stringValue(); 151 | } 152 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/MetricBuilderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import com.google.common.base.Charsets; 19 | import com.google.common.io.Resources; 20 | import org.junit.Test; 21 | import org.kairosdb.client.testUtils.MetricParser; 22 | 23 | import java.io.IOException; 24 | 25 | import static org.hamcrest.CoreMatchers.equalTo; 26 | import static org.junit.Assert.assertThat; 27 | 28 | public class MetricBuilderTest 29 | { 30 | @Test 31 | public void testBuild() throws IOException 32 | { 33 | MetricParser parser = new MetricParser(); 34 | String json = Resources.toString(Resources.getResource("multiple_metrics.json"), Charsets.UTF_8); 35 | 36 | MetricBuilder builder = MetricBuilder.getInstance(); 37 | 38 | builder.addMetric("metric1") 39 | .addDataPoint(1, 10) 40 | .addDataPoint(2, 30L) 41 | .addTag("tag1", "tab1value") 42 | .addTag("tag2", "tab2value"); 43 | 44 | builder.addMetric("metric2") 45 | .addDataPoint(2, 30L) 46 | .addDataPoint(3, 2.3) 47 | .addTag("tag3", "tab3value"); 48 | 49 | assertThat(parser.parse(builder.build()), equalTo(parser.parse(json))); 50 | } 51 | 52 | @Test(expected = IllegalStateException.class) 53 | public void test_metricContainsTags() throws IOException 54 | { 55 | MetricBuilder builder = MetricBuilder.getInstance(); 56 | builder.addMetric("metric1"); 57 | builder.addMetric("metric2").addTag("tag", "value"); 58 | 59 | builder.build(); 60 | } 61 | 62 | @Test 63 | public void test_timestampNegative_valid() 64 | { 65 | MetricBuilder.getInstance().addMetric("metric").addDataPoint(-1, 3); 66 | } 67 | 68 | @Test 69 | public void test_timestampZero_valid() 70 | { 71 | MetricBuilder.getInstance().addMetric("metric").addDataPoint(0, 3); 72 | } 73 | 74 | @Test(expected = NullPointerException.class) 75 | public void test_nullMetricName_invalid() 76 | { 77 | MetricBuilder builder = MetricBuilder.getInstance(); 78 | 79 | builder.addMetric(null); 80 | } 81 | 82 | @Test(expected = IllegalArgumentException.class) 83 | public void test_emptyMetricName_invalid() 84 | { 85 | MetricBuilder builder = MetricBuilder.getInstance(); 86 | 87 | builder.addMetric(""); 88 | } 89 | 90 | @Test(expected = NullPointerException.class) 91 | public void test_nullTagName_invalid() 92 | { 93 | MetricBuilder builder = MetricBuilder.getInstance(); 94 | 95 | builder.addMetric("metric1").addTag(null, "value"); 96 | } 97 | 98 | @Test(expected = IllegalArgumentException.class) 99 | public void test_emptyTagName_invalid() 100 | { 101 | MetricBuilder builder = MetricBuilder.getInstance(); 102 | 103 | builder.addMetric("metric1").addTag("", "value"); 104 | } 105 | 106 | @Test(expected = NullPointerException.class) 107 | public void test_nullTagValue_invalid() 108 | { 109 | MetricBuilder builder = MetricBuilder.getInstance(); 110 | 111 | builder.addMetric("metric1").addTag("tag", null); 112 | } 113 | 114 | @Test(expected = IllegalArgumentException.class) 115 | public void test_emptyTagValue_invalid() 116 | { 117 | MetricBuilder builder = MetricBuilder.getInstance(); 118 | 119 | builder.addMetric("metric1").addTag("tag", ""); 120 | } 121 | 122 | @Test 123 | public void test_compression_flag_set() 124 | { 125 | MetricBuilder builder = MetricBuilder.getInstance(); 126 | builder.addMetric("sample"); 127 | builder.setCompression(true); 128 | assert (builder.isCompressionEnabled()); 129 | } 130 | 131 | @Test 132 | public void test_compression_default() 133 | { 134 | MetricBuilder builder = MetricBuilder.getInstance(); 135 | builder.addMetric("sample"); 136 | assert (!builder.isCompressionEnabled()); 137 | } 138 | 139 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/MetricTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import org.junit.Test; 19 | 20 | public class MetricTest 21 | { 22 | @Test(expected = NullPointerException.class) 23 | public void test_nullMetricName_invalid() 24 | { 25 | MetricBuilder builder = MetricBuilder.getInstance(); 26 | 27 | builder.addMetric(null); 28 | } 29 | 30 | @Test(expected = IllegalArgumentException.class) 31 | public void test_emptyMetricName_invalid() 32 | { 33 | MetricBuilder builder = MetricBuilder.getInstance(); 34 | 35 | builder.addMetric(""); 36 | } 37 | 38 | @Test(expected = NullPointerException.class) 39 | public void test_nullTagName_invalid() 40 | { 41 | MetricBuilder builder = MetricBuilder.getInstance(); 42 | 43 | builder.addMetric("metric1").addTag(null, "value"); 44 | } 45 | 46 | @Test(expected = IllegalArgumentException.class) 47 | public void test_emptyTagName_invalid() 48 | { 49 | MetricBuilder builder = MetricBuilder.getInstance(); 50 | 51 | builder.addMetric("metric1").addTag("", "value"); 52 | } 53 | 54 | @Test(expected = NullPointerException.class) 55 | public void test_nullTagValue_invalid() 56 | { 57 | MetricBuilder builder = MetricBuilder.getInstance(); 58 | 59 | builder.addMetric("metric1").addTag("tag", null); 60 | } 61 | 62 | @Test(expected = IllegalArgumentException.class) 63 | public void test_emptyTagValue_invalid() 64 | { 65 | MetricBuilder builder = MetricBuilder.getInstance(); 66 | 67 | builder.addMetric("metric1").addTag("tag", ""); 68 | } 69 | 70 | @Test(expected = IllegalArgumentException.class) 71 | public void test_ttl_less_than_zero_invalid() 72 | { 73 | MetricBuilder builder = MetricBuilder.getInstance(); 74 | 75 | builder.addMetric("metric1").addTtl(-1); 76 | } 77 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/QueryMetricTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import org.junit.Test; 19 | 20 | public class QueryMetricTest 21 | { 22 | @Test(expected = NullPointerException.class) 23 | public void test_constructor_NullName_Invalid() 24 | { 25 | new QueryMetric(null); 26 | } 27 | 28 | @Test(expected = IllegalArgumentException.class) 29 | public void test_constructor_EmptyName_Invalid() 30 | { 31 | new QueryMetric(""); 32 | } 33 | 34 | @Test(expected = NullPointerException.class) 35 | public void test_addTag_nullName_Invalid() 36 | { 37 | QueryMetric queryMetric = new QueryMetric("metric"); 38 | 39 | queryMetric.addTag(null, "value"); 40 | } 41 | 42 | @Test(expected = NullPointerException.class) 43 | public void testAddTags_nullMap_invalid() 44 | { 45 | QueryMetric queryMetric = new QueryMetric("metric"); 46 | 47 | queryMetric.addTags(null); 48 | } 49 | 50 | @Test(expected = NullPointerException.class) 51 | public void testAddMultiValuedTags_nullMap_invalid() 52 | { 53 | QueryMetric queryMetric = new QueryMetric("metric"); 54 | 55 | queryMetric.addMultiValuedTags(null); 56 | } 57 | 58 | @Test(expected = IllegalArgumentException.class) 59 | public void test_addTag_emptyName_Invalid() 60 | { 61 | QueryMetric queryMetric = new QueryMetric("metric"); 62 | 63 | queryMetric.addTag("", "value"); 64 | } 65 | 66 | @Test(expected = NullPointerException.class) 67 | public void test_addTag_nullValue_Invalid() 68 | { 69 | QueryMetric queryMetric = new QueryMetric("metric"); 70 | 71 | queryMetric.addTag("tag", (String)null); 72 | } 73 | 74 | @Test(expected = IllegalArgumentException.class) 75 | public void test_addTag_emptyValue_Invalid() 76 | { 77 | QueryMetric queryMetric = new QueryMetric("metric"); 78 | 79 | queryMetric.addTag("tag", ""); 80 | } 81 | 82 | @Test(expected = NullPointerException.class) 83 | public void test_nullAggregator_invalid() 84 | { 85 | QueryMetric queryMetric = new QueryMetric("metric"); 86 | 87 | queryMetric.addAggregator(null); 88 | } 89 | 90 | @Test(expected = NullPointerException.class) 91 | public void test_nullGrouper_invalid() 92 | { 93 | QueryMetric queryMetric = new QueryMetric("metric"); 94 | 95 | queryMetric.addGrouper(null); 96 | } 97 | 98 | @Test(expected = IllegalArgumentException.class) 99 | public void test_setLimit_lessThanZero_invalid() 100 | { 101 | QueryMetric queryMetric = new QueryMetric("metric"); 102 | 103 | queryMetric.setLimit(0); 104 | } 105 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/QueryTagBuilderTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import java.util.Collections; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import org.junit.Test; 7 | 8 | import java.io.IOException; 9 | import java.util.Date; 10 | 11 | import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; 12 | import static net.javacrumbs.jsonunit.JsonAssert.when; 13 | import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; 14 | import static org.hamcrest.CoreMatchers.equalTo; 15 | import static org.junit.Assert.assertThat; 16 | 17 | public class QueryTagBuilderTest 18 | { 19 | @Test(expected = NullPointerException.class) 20 | public void test_MetricNameNull_Invalid() 21 | { 22 | QueryTagBuilder.getInstance().addMetric(null); 23 | } 24 | 25 | @Test(expected = IllegalArgumentException.class) 26 | public void test_MetricNameEmpty_Invalid() 27 | { 28 | QueryTagBuilder.getInstance().addMetric(""); 29 | } 30 | 31 | @Test(expected = NullPointerException.class) 32 | public void test_AbsoluteStartNull_Invalid() 33 | { 34 | QueryTagBuilder.getInstance().setStart(null); 35 | } 36 | 37 | @Test(expected = IllegalArgumentException.class) 38 | public void test_AbsoluteStartAndRelativeStartSet_Invalid() 39 | { 40 | QueryTagBuilder.getInstance().setStart(new Date()).setStart(3, TimeUnit.DAYS); 41 | } 42 | 43 | @Test(expected = IllegalArgumentException.class) 44 | public void test_RelativeStartAndAbsoluteStartSet_Invalid() 45 | { 46 | QueryTagBuilder.getInstance().setStart(3, TimeUnit.DAYS).setStart(new Date()); 47 | } 48 | 49 | @Test(expected = NullPointerException.class) 50 | public void test_RelativeStartUnitNull_Invalid() throws IOException 51 | { 52 | QueryTagBuilder.getInstance().setStart(3, null); 53 | } 54 | 55 | @Test(expected = IllegalArgumentException.class) 56 | public void test_RelativeStartValueZero_Invalid() throws IOException 57 | { 58 | QueryTagBuilder.getInstance().setStart(0, TimeUnit.DAYS); 59 | } 60 | 61 | @Test(expected = IllegalArgumentException.class) 62 | public void test_RelativeStartValueNegative_Invalid() throws IOException 63 | { 64 | QueryTagBuilder.getInstance().setStart(-1, TimeUnit.DAYS); 65 | } 66 | 67 | @Test(expected = NullPointerException.class) 68 | public void test_RelativeEndUnitNull_Invalid() throws IOException 69 | { 70 | QueryTagBuilder.getInstance().setEnd(3, null); 71 | } 72 | 73 | @Test(expected = IllegalArgumentException.class) 74 | public void test_RelativeEndValueZero_Invalid() throws IOException 75 | { 76 | QueryTagBuilder.getInstance().setEnd(0, TimeUnit.DAYS); 77 | } 78 | 79 | @Test(expected = IllegalArgumentException.class) 80 | public void test_RelativeEndValueNegative_Invalid() throws IOException 81 | { 82 | QueryTagBuilder.getInstance().setEnd(-1, TimeUnit.DAYS); 83 | } 84 | 85 | @Test(expected = IllegalStateException.class) 86 | public void test_startTimeNotSpecified_Invalid() throws IOException 87 | { 88 | QueryTagBuilder.getInstance().build(); 89 | } 90 | 91 | @Test(expected = IllegalStateException.class) 92 | public void test_endTimeAbsoluteBeforeStartTimeAbsolute_invalid() throws IOException 93 | { 94 | QueryTagBuilder.getInstance() 95 | .setStart(new Date()) 96 | .setEnd(new Date(System.currentTimeMillis() - 10000)) 97 | .build(); 98 | } 99 | 100 | @Test(expected = IllegalStateException.class) 101 | public void test_endTimeRelativeBeforeThanStartTimeRelative_invalid() throws IOException 102 | { 103 | QueryTagBuilder.getInstance() 104 | .setStart(2, TimeUnit.DAYS) 105 | .setEnd(2, TimeUnit.WEEKS) 106 | .build(); 107 | } 108 | 109 | @Test(expected = IllegalStateException.class) 110 | public void test_endTimeRelativeBeforeStartTimeAbsolute_invalid() throws IOException 111 | { 112 | QueryTagBuilder.getInstance() 113 | .setStart(new Date()) 114 | .setEnd(2, TimeUnit.WEEKS) 115 | .build(); 116 | } 117 | 118 | @Test(expected = IllegalStateException.class) 119 | public void test_endTimeAbsoluteBeforeStartTimeRelative_invalid() throws IOException 120 | { 121 | QueryTagBuilder.getInstance() 122 | .setStart(60, TimeUnit.SECONDS) 123 | .setEnd(new Date(1000)) 124 | .build(); 125 | } 126 | 127 | @Test 128 | public void test() throws IOException 129 | { 130 | QueryTagBuilder builder = QueryTagBuilder.getInstance() 131 | .setStart(1, TimeUnit.HOURS); 132 | builder.addMetric("metricName") 133 | .addTag("foo", "bar") 134 | .addTag("fi", Collections.singleton("fum")); 135 | 136 | assertThat(builder.build(), equalTo("{\"metrics\":[{\"name\":\"metricName\",\"tags\":{\"fi\":[\"fum\"],\"foo\":[\"bar\"]}}],\"start_relative\":{\"value\":1,\"unit\":\"HOURS\"}}")); 137 | } 138 | 139 | @Test 140 | public void testMultipleTags() throws IOException 141 | { 142 | QueryTagBuilder builder = QueryTagBuilder.getInstance() 143 | .setStart(1, TimeUnit.HOURS); 144 | Set tags = new HashSet<>(); 145 | Set tags1 = new HashSet<>(); 146 | tags.add("bar"); 147 | tags.add("Bar"); 148 | tags.add("bars"); 149 | 150 | tags1.add("fum"); 151 | tags1.add("Fum"); 152 | tags1.add("fums"); 153 | 154 | builder.addMetric("metricName") 155 | .addTag("foo",tags) 156 | .addTag("fi",tags1); 157 | assertJsonEquals( 158 | builder.build(), 159 | "{\"metrics\":[{\"name\":\"metricName\",\"tags\":{\"foo\":[\"bar\",\"Bar\",\"bars\"],\"fi\":[\"fum\",\"Fum\",\"fums\"]}}],\"start_relative\":{\"value\":1,\"unit\":\"HOURS\"}}", 160 | when(IGNORING_ARRAY_ORDER)); 161 | } 162 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/RollupBuilderTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.io.Resources; 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.rules.ExpectedException; 8 | import org.kairosdb.client.DataPointTypeRegistry; 9 | import org.kairosdb.client.JsonMapper; 10 | import org.kairosdb.client.builder.grouper.TagGrouper; 11 | 12 | import java.io.IOException; 13 | 14 | import static org.hamcrest.CoreMatchers.equalTo; 15 | import static org.junit.Assert.assertThat; 16 | 17 | 18 | public class RollupBuilderTest 19 | { 20 | @Rule 21 | public ExpectedException thrown = ExpectedException.none(); 22 | 23 | @Test 24 | public void test_build_noRollups() 25 | { 26 | thrown.expect(IllegalStateException.class); 27 | thrown.expectMessage("No roll-ups added"); 28 | 29 | RollupBuilder builder = RollupBuilder.getInstance("rollup1", new RelativeTime(2, TimeUnit.DAYS)); 30 | builder.build(); 31 | } 32 | 33 | @Test 34 | public void test_build_noQueries() 35 | { 36 | thrown.expect(NullPointerException.class); 37 | thrown.expectMessage("No queries added to rollup rollup1"); 38 | 39 | RollupBuilder builder = RollupBuilder.getInstance("rollup1", new RelativeTime(2, TimeUnit.DAYS)); 40 | builder.addRollup("rollup1"); 41 | builder.build(); 42 | } 43 | 44 | @Test 45 | public void test_build_invalidQueryTime() 46 | { 47 | thrown.expect(IllegalStateException.class); 48 | thrown.expectMessage("Start time must be specified"); 49 | 50 | RollupBuilder builder = RollupBuilder.getInstance("rollup1", new RelativeTime(2, TimeUnit.DAYS)); 51 | Rollup rollup = builder.addRollup("rollup1"); 52 | rollup.addQuery().setEnd(1, TimeUnit.MINUTES); 53 | builder.build(); 54 | } 55 | 56 | @Test 57 | public void test() 58 | throws IOException 59 | { 60 | JsonMapper mapper = new JsonMapper(new DataPointTypeRegistry()); 61 | String expectedJson = Resources.toString(Resources.getResource("rollup.json"), Charsets.UTF_8); 62 | 63 | RollupBuilder builder = RollupBuilder.getInstance("rollupTask", new RelativeTime(1, TimeUnit.HOURS)); 64 | Rollup rollup = builder.addRollup("myRollupMetric"); 65 | rollup.addQuery() 66 | .setStart(1, TimeUnit.HOURS) 67 | .addMetric("metric1") 68 | .addAggregator(AggregatorFactory.createMaxAggregator(1, TimeUnit.MINUTES)) 69 | .addAggregator(AggregatorFactory.createCountAggregator(1, TimeUnit.MINUTES)) 70 | .addGrouper(new TagGrouper("tag1", "tag2")); 71 | 72 | String json = builder.build(); 73 | 74 | assertThat(mapper.fromJson(json, RollupTask.class), equalTo(mapper.fromJson(expectedJson, RollupTask.class))); 75 | } 76 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/SamplingAggregatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import org.junit.Test; 19 | import org.kairosdb.client.builder.aggregator.SamplingAggregator; 20 | 21 | import static org.hamcrest.CoreMatchers.equalTo; 22 | import static org.junit.Assert.assertFalse; 23 | import static org.junit.Assert.assertThat; 24 | import static org.junit.Assert.assertTrue; 25 | 26 | public class SamplingAggregatorTest 27 | { 28 | 29 | @Test(expected = NullPointerException.class) 30 | public void test_nullName_invalid() 31 | { 32 | new SamplingAggregator(null, 1 ,TimeUnit.DAYS); 33 | } 34 | 35 | @Test(expected = IllegalArgumentException.class) 36 | public void test_emptyName_invalid() 37 | { 38 | new SamplingAggregator("", 1 ,TimeUnit.DAYS); 39 | } 40 | 41 | @Test(expected = IllegalArgumentException.class) 42 | public void test_valueNegative_invalid() 43 | { 44 | new SamplingAggregator("sum", -1 ,TimeUnit.DAYS); 45 | } 46 | 47 | @Test(expected = IllegalArgumentException.class) 48 | public void test_valueZero_invalid() 49 | { 50 | new SamplingAggregator("sum", 0 ,TimeUnit.DAYS); 51 | } 52 | 53 | @Test(expected = NullPointerException.class) 54 | public void test_unitNull_invalid() 55 | { 56 | new SamplingAggregator("sum", 1, null); 57 | } 58 | 59 | @Test(expected = IllegalArgumentException.class) 60 | public void testWithStartTimeAlignmentNegativeStartTimeInvalid() 61 | { 62 | new SamplingAggregator("sum", 1, TimeUnit.DAYS).withStartTimeAlignment(-1); 63 | } 64 | 65 | @Test 66 | public void testWithSamplingAlignment() 67 | { 68 | SamplingAggregator aggregator = new SamplingAggregator("sum", 1, TimeUnit.DAYS).withSamplingAlignment(); 69 | 70 | assertFalse(aggregator.isAlignStartTime()); 71 | assertTrue(aggregator.isAlignSampling()); 72 | } 73 | 74 | @Test 75 | public void testWithStartTimeAlignment() 76 | { 77 | SamplingAggregator aggregator = new SamplingAggregator("sum", 1, TimeUnit.DAYS).withStartTimeAlignment(); 78 | 79 | assertFalse(aggregator.isAlignSampling()); 80 | assertTrue(aggregator.isAlignStartTime()); 81 | assertFalse(aggregator.isAlignEndTime()); 82 | assertThat(aggregator.getStartTimeAlignmentStartTime(), equalTo(0L)); 83 | } 84 | 85 | @Test 86 | public void testWithEndTimeAlignment() 87 | { 88 | SamplingAggregator aggregator = new SamplingAggregator("sum", 1, TimeUnit.DAYS).withEndTimeAlignment(); 89 | 90 | assertFalse(aggregator.isAlignSampling()); 91 | assertFalse(aggregator.isAlignStartTime()); 92 | assertTrue(aggregator.isAlignEndTime()); 93 | assertThat(aggregator.getStartTimeAlignmentStartTime(), equalTo(0L)); 94 | } 95 | 96 | @Test 97 | public void testWithStartTimeAlignmentWithStartTime() 98 | { 99 | SamplingAggregator aggregator = new SamplingAggregator("sum", 1, TimeUnit.DAYS).withStartTimeAlignment(444); 100 | 101 | assertFalse(aggregator.isAlignSampling()); 102 | assertTrue(aggregator.isAlignStartTime()); 103 | assertFalse(aggregator.isAlignEndTime()); 104 | assertThat(aggregator.getStartTimeAlignmentStartTime(), equalTo(444L)); 105 | } 106 | 107 | @Test 108 | public void testWithEndTimeAlignmentWithStartTime() 109 | { 110 | SamplingAggregator aggregator = new SamplingAggregator("sum", 1, TimeUnit.DAYS).withEndTimeAlignment(444); 111 | 112 | assertFalse(aggregator.isAlignSampling()); 113 | assertFalse(aggregator.isAlignStartTime()); 114 | assertTrue(aggregator.isAlignEndTime()); 115 | assertThat(aggregator.getStartTimeAlignmentStartTime(), equalTo(444L)); 116 | } 117 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/TimeValidatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Proofpoint Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.kairosdb.client.builder; 17 | 18 | import org.junit.Test; 19 | 20 | public class TimeValidatorTest 21 | { 22 | 23 | @Test 24 | public void test_AbsoluteStartBeforeAbsoluteEnd_Valid() 25 | { 26 | long now = System.currentTimeMillis(); 27 | RelativeTime startTime = new RelativeTime(2, TimeUnit.WEEKS); 28 | RelativeTime endTime = new RelativeTime(2, TimeUnit.DAYS); 29 | TimeValidator.validateEndTimeLaterThanStartTime(startTime.getTimeRelativeTo(now), endTime.getTimeRelativeTo(now)); 30 | } 31 | 32 | @Test(expected = IllegalStateException.class) 33 | public void test_AbsoluteStartLaterThanAbsoluteEnd_Invalid() 34 | { 35 | long now = System.currentTimeMillis(); 36 | RelativeTime startTime = new RelativeTime(2, TimeUnit.DAYS); 37 | RelativeTime endTime = new RelativeTime(2, TimeUnit.WEEKS); 38 | TimeValidator.validateEndTimeLaterThanStartTime(startTime.getTimeRelativeTo(now), endTime.getTimeRelativeTo(now)); 39 | } 40 | 41 | @Test 42 | public void test_RelativeStartBeforeAbsoluteEnd_Valid() 43 | { 44 | RelativeTime startTime = new RelativeTime(2, TimeUnit.WEEKS); 45 | RelativeTime endTime = new RelativeTime(2, TimeUnit.DAYS); 46 | TimeValidator.validateEndTimeLaterThanStartTime(startTime, endTime.getTimeRelativeTo(System.currentTimeMillis())); 47 | } 48 | 49 | @Test(expected = IllegalStateException.class) 50 | public void test_RelativeStartLaterThanAbsoluteEnd_Invalid() 51 | { 52 | RelativeTime startTime = new RelativeTime(2, TimeUnit.DAYS); 53 | RelativeTime endTime = new RelativeTime(2, TimeUnit.WEEKS); 54 | TimeValidator.validateEndTimeLaterThanStartTime(startTime, endTime.getTimeRelativeTo(System.currentTimeMillis())); 55 | } 56 | 57 | @Test 58 | public void test_AbsoluteStartBeforeRelativeEnd_Valid() 59 | { 60 | RelativeTime startTime = new RelativeTime(2, TimeUnit.WEEKS); 61 | RelativeTime endTime = new RelativeTime(2, TimeUnit.DAYS); 62 | TimeValidator.validateEndTimeLaterThanStartTime(startTime.getTimeRelativeTo(System.currentTimeMillis()), endTime); 63 | } 64 | 65 | @Test(expected = IllegalStateException.class) 66 | public void test_AbsoluteStartLaterThanRelativeEnd_Invalid() 67 | { 68 | RelativeTime startTime = new RelativeTime(2, TimeUnit.DAYS); 69 | RelativeTime endTime = new RelativeTime(2, TimeUnit.WEEKS); 70 | TimeValidator.validateEndTimeLaterThanStartTime(startTime.getTimeRelativeTo(System.currentTimeMillis()), endTime); 71 | } 72 | 73 | @Test 74 | public void test_RelativeStartBeforeRelativeEnd_Valid() 75 | { 76 | RelativeTime startTime = new RelativeTime(2, TimeUnit.WEEKS); 77 | RelativeTime endTime = new RelativeTime(2, TimeUnit.DAYS); 78 | TimeValidator.validateEndTimeLaterThanStartTime(startTime, endTime); 79 | } 80 | 81 | @Test(expected = IllegalStateException.class) 82 | public void test_RelativeStartLaterThanRelativeEnd_Invalid() 83 | { 84 | RelativeTime startTime = new RelativeTime(2, TimeUnit.DAYS); 85 | RelativeTime endTime = new RelativeTime(2, TimeUnit.WEEKS); 86 | TimeValidator.validateEndTimeLaterThanStartTime(startTime, endTime); 87 | } 88 | 89 | @Test 90 | public void test_StartAndEndTimeEqual() 91 | { 92 | long time = System.currentTimeMillis(); 93 | RelativeTime relativetime = new RelativeTime(2, TimeUnit.DAYS); 94 | TimeValidator.validateEndTimeLaterThanStartTime(time, time); 95 | TimeValidator.validateEndTimeLaterThanStartTime(new RelativeTime(1, TimeUnit.HOURS), new RelativeTime(1, TimeUnit.HOURS)); 96 | TimeValidator.validateEndTimeLaterThanStartTime(relativetime.getTimeRelativeTo(System.currentTimeMillis()), relativetime); 97 | TimeValidator.validateEndTimeLaterThanStartTime(relativetime, relativetime.getTimeRelativeTo(System.currentTimeMillis())); 98 | } 99 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/aggregator/RateAggregatorTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder.aggregator; 2 | 3 | import org.junit.Test; 4 | import org.kairosdb.client.builder.TimeUnit; 5 | 6 | import static org.hamcrest.CoreMatchers.equalTo; 7 | import static org.junit.Assert.assertThat; 8 | 9 | public class RateAggregatorTest 10 | { 11 | @Test(expected = NullPointerException.class) 12 | public void test_constructor_null_unit_invalid() 13 | { 14 | new RateAggregator(null); 15 | } 16 | 17 | @Test 18 | public void test_getter() 19 | { 20 | RateAggregator aggregator = new RateAggregator(TimeUnit.MINUTES); 21 | 22 | assertThat(aggregator.getUnit(), equalTo(TimeUnit.MINUTES)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/grouper/BinGrouperTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder.grouper; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | import static org.hamcrest.Matchers.equalTo; 10 | import static org.hamcrest.Matchers.hasItems; 11 | import static org.junit.Assert.*; 12 | 13 | public class BinGrouperTest 14 | { 15 | 16 | @Test(expected = NullPointerException.class) 17 | public void test_constructor_nullBins_invalid() 18 | { 19 | new BinGrouper((Double[]) null); 20 | } 21 | 22 | @Test(expected = IllegalArgumentException.class) 23 | public void test_constructor_emptyBins_invalid() 24 | { 25 | new BinGrouper(); 26 | } 27 | 28 | @Test(expected = NullPointerException.class) 29 | public void test_constructor_nullBinsList_invalid() 30 | { 31 | new BinGrouper((List) null); 32 | } 33 | 34 | @Test(expected = IllegalArgumentException.class) 35 | public void test_constructor_emptyBinsList_invalid() 36 | { 37 | new BinGrouper(new ArrayList()); 38 | } 39 | 40 | @Test 41 | public void test_constructor_name() 42 | { 43 | BinGrouper grouper = new BinGrouper(2.0, 3.0, 4.0); 44 | 45 | assertThat(grouper.getName(), equalTo("bin")); 46 | } 47 | 48 | @Test 49 | public void test_constructorList_name() 50 | { 51 | BinGrouper grouper = new BinGrouper(List.of(2.1, 3.1, 4.1)); 52 | 53 | assertThat(grouper.getName(), equalTo("bin")); 54 | } 55 | 56 | @Test 57 | public void test_constructor_bins() 58 | { 59 | BinGrouper grouper = new BinGrouper(2.1, 3.1, 4.1); 60 | 61 | assertThat(grouper.getBins(), hasItems(2.1, 3.1, 4.1)); 62 | } 63 | 64 | @Test 65 | public void test_constructor_bins_from_list() 66 | { 67 | BinGrouper grouper = new BinGrouper(List.of(2.1, 3.1, 4.1)); 68 | 69 | assertThat(grouper.getBins(), hasItems(2.1, 3.1, 4.1)); 70 | } 71 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/grouper/CustomGrouperTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.builder.grouper; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.equalTo; 6 | import static org.junit.Assert.assertThat; 7 | 8 | public class CustomGrouperTest 9 | { 10 | @Test(expected = NullPointerException.class) 11 | public void test_constructor_null_json_invalid() 12 | { 13 | new CustomGrouper("name", null); 14 | } 15 | 16 | @Test(expected = IllegalArgumentException.class) 17 | public void test_constructor_empty_json_invalid() 18 | { 19 | new CustomGrouper("name", ""); 20 | } 21 | 22 | @Test 23 | public void test_toJson() 24 | { 25 | CustomGrouper grouper = new CustomGrouper("group1", "{\"foo\": 120}"); 26 | 27 | assertThat(grouper.toJson(), equalTo("{\"name\": \"group1\", {\"foo\": 120}}")); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/grouper/TagGrouperTest.java: -------------------------------------------------------------------------------- 1 | // 2 | // TagGrouperTest.java 3 | // 4 | // Copyright 2013, Proofpoint Inc. All rights reserved. 5 | // 6 | package org.kairosdb.client.builder.grouper; 7 | 8 | import org.junit.Test; 9 | 10 | import java.util.Arrays; 11 | import java.util.List; 12 | 13 | import static org.hamcrest.Matchers.equalTo; 14 | import static org.hamcrest.Matchers.hasItems; 15 | import static org.junit.Assert.assertThat; 16 | 17 | public class TagGrouperTest 18 | { 19 | 20 | @Test(expected = NullPointerException.class) 21 | public void test_constructor_nullTagNames_invalid() 22 | { 23 | new TagGrouper((String[]) null); 24 | } 25 | 26 | @Test(expected = NullPointerException.class) 27 | public void test_constructor_nullTagName_invalid() 28 | { 29 | new TagGrouper("tag1", null); 30 | } 31 | 32 | @Test(expected = IllegalArgumentException.class) 33 | public void test_constructor_emptyTagNameList_invalid() 34 | { 35 | new TagGrouper(); 36 | } 37 | 38 | @Test(expected = NullPointerException.class) 39 | public void test_constructor_null_list_invalid() 40 | { 41 | new TagGrouper((List) null); 42 | } 43 | 44 | @Test 45 | public void test_constructor_name() 46 | { 47 | TagGrouper grouper = new TagGrouper("tag1", "tag2"); 48 | 49 | assertThat(grouper.getName(), equalTo("tag")); 50 | } 51 | 52 | @Test 53 | public void test_constructor_list_name() 54 | { 55 | TagGrouper grouper = new TagGrouper(Arrays.asList("tag1", "tag2")); 56 | 57 | assertThat(grouper.getName(), equalTo("tag")); 58 | } 59 | 60 | @Test 61 | public void test_constructor_tagNames() 62 | { 63 | TagGrouper grouper = new TagGrouper("tag1", "tag2"); 64 | 65 | assertThat(grouper.getTagNames(), hasItems("tag1", "tag2")); 66 | } 67 | 68 | @Test 69 | public void test_constructor_tagNames_from_list() 70 | { 71 | TagGrouper grouper = new TagGrouper(Arrays.asList("tag1", "tag2")); 72 | 73 | assertThat(grouper.getTagNames(), hasItems("tag1", "tag2")); 74 | } 75 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/grouper/TimeGrouperTest.java: -------------------------------------------------------------------------------- 1 | // 2 | // TimeGrouperTest.java 3 | // 4 | // Copyright 2013, Proofpoint Inc. All rights reserved. 5 | // 6 | package org.kairosdb.client.builder.grouper; 7 | 8 | import org.junit.Test; 9 | import org.kairosdb.client.builder.RelativeTime; 10 | import org.kairosdb.client.builder.TimeUnit; 11 | 12 | public class TimeGrouperTest 13 | { 14 | 15 | @Test(expected = NullPointerException.class) 16 | public void test_constructor_nullRangeSize_invalid() 17 | { 18 | new TimeGrouper(null, 4); 19 | } 20 | 21 | @Test(expected = IllegalArgumentException.class) 22 | public void test_constructor_CountLessThanOne_invalid() 23 | { 24 | new TimeGrouper(new RelativeTime(1, TimeUnit.DAYS), 0); 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/builder/grouper/ValueGrouperTest.java: -------------------------------------------------------------------------------- 1 | // 2 | // ValueGrouperTest.java 3 | // 4 | // Copyright 2013, Proofpoint Inc. All rights reserved. 5 | // 6 | package org.kairosdb.client.builder.grouper; 7 | 8 | import org.junit.Test; 9 | 10 | public class ValueGrouperTest 11 | { 12 | @Test(expected = IllegalArgumentException.class) 13 | public void test_constructor_rangeSize_lessThan1() 14 | { 15 | new ValueGrouper(0); 16 | } 17 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/deserializer/GroupByDeserializerTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.deserializer; 2 | 3 | import com.google.gson.*; 4 | import org.hamcrest.CoreMatchers; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.kairosdb.client.builder.RelativeTime; 8 | import org.kairosdb.client.builder.TimeUnit; 9 | import org.kairosdb.client.response.GroupResult; 10 | import org.kairosdb.client.response.grouping.*; 11 | 12 | import static org.hamcrest.CoreMatchers.*; 13 | import static org.hamcrest.Matchers.hasItems; 14 | import static org.junit.Assert.assertThat; 15 | 16 | public class GroupByDeserializerTest 17 | { 18 | private Gson gson; 19 | 20 | @Before 21 | public void setup() 22 | { 23 | GsonBuilder builder = new GsonBuilder(); 24 | builder.registerTypeAdapter(GroupResult.class, new GroupByDeserializer()); 25 | gson = builder.create(); 26 | } 27 | 28 | @Test(expected = JsonParseException.class) 29 | public void test_missingName_invalid() 30 | { 31 | JsonObject json = new JsonObject(); 32 | json.add("value", new JsonPrimitive(5)); 33 | 34 | new GroupByDeserializer().deserialize(json, null, null); 35 | } 36 | 37 | @Test 38 | public void test_tag_grouper() 39 | { 40 | TagGroupResult result = (TagGroupResult) gson.fromJson("{'name': 'tag', 'tags': ['host'], 'group': {'host': 'server1'}}", GroupResult.class); 41 | 42 | assertThat(result, instanceOf(TagGroupResult.class)); 43 | assertThat(result.getName(), equalTo("tag")); 44 | assertThat(result.getTags(), hasItems("host")); 45 | assertThat(result.getGroup().get("host"), equalTo("server1")); 46 | } 47 | 48 | @Test 49 | public void test_time_grouper() 50 | { 51 | String json = "{'name':'time','range_size':{'value':1,'unit':'MILLISECONDS'},'group_count':5,'group':{'group_number':2}}"; 52 | 53 | TimeGroupResult result = (TimeGroupResult) gson.fromJson(json, GroupResult.class); 54 | 55 | assertThat(result, instanceOf(TimeGroupResult.class)); 56 | assertThat(result.getName(), equalTo("time")); 57 | assertThat(result.getGroupCount(), equalTo(5)); 58 | assertThat(result.getGroup().getGroupNumber(), equalTo(2)); 59 | assertThat(result.getRangeSize(), equalTo(new RelativeTime(1, TimeUnit.MILLISECONDS))); 60 | } 61 | 62 | @Test 63 | public void test_value_grouper() 64 | { 65 | String json = "{'name':'value','range_size':100,'group':{'group_number':0}}"; 66 | 67 | ValueGroupResult result = (ValueGroupResult) gson.fromJson(json, GroupResult.class); 68 | 69 | assertThat(result, instanceOf(ValueGroupResult.class)); 70 | assertThat(result.getName(), equalTo("value")); 71 | assertThat(result.getGroup().getGroupNumber(), equalTo(0)); 72 | assertThat(result.getRangeSize(), equalTo(100)); 73 | } 74 | 75 | @Test 76 | public void test_bin_grouper() 77 | { 78 | String json = "{'name': 'bin', 'bins': [5, 10, 20],'group': {'bin_number': 1}}"; 79 | BinGroupResult result = (BinGroupResult) gson.fromJson(json, GroupResult.class); 80 | 81 | assertThat(result, instanceOf(BinGroupResult.class)); 82 | assertThat(result.getName(), equalTo("bin")); 83 | assertThat(result.getBinNumber(), equalTo(1)); 84 | assertThat(result.getBins(), hasItems(5.0, 10.0, 20.0)); 85 | } 86 | 87 | @Test 88 | public void test_unknown_grouper() 89 | { 90 | CustomGroupResult result = (CustomGroupResult) gson.fromJson("{'name': 'bogus', 'value': 5}", GroupResult.class); 91 | 92 | assertThat(result, instanceOf(CustomGroupResult.class)); 93 | assertThat(result.getName(), equalTo("bogus")); 94 | assertThat(result.getProperties().get("value"), CoreMatchers.equalTo(5.0)); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/response/DefaultJsonResponseHandlerTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.io.Resources; 5 | import org.apache.http.client.methods.HttpUriRequest; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.kairosdb.client.DataPointTypeRegistry; 9 | import org.kairosdb.client.JsonMapper; 10 | import org.kairosdb.client.builder.RollupTask; 11 | 12 | import java.io.ByteArrayInputStream; 13 | import java.io.IOException; 14 | 15 | import static junit.framework.TestCase.assertNull; 16 | import static org.apache.http.HttpHeaders.CONTENT_TYPE; 17 | import static org.apache.http.entity.ContentType.APPLICATION_JSON; 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.mockito.Mockito.mock; 20 | import static org.mockito.Mockito.when; 21 | 22 | public class DefaultJsonResponseHandlerTest 23 | { 24 | private HttpUriRequest mockRequest; 25 | private ResponseHelper mockResponse; 26 | private DefaultJsonResponseHandler handler; 27 | 28 | @Before 29 | public void setup() 30 | { 31 | mockRequest = mock(HttpUriRequest.class); 32 | mockResponse = mock(ResponseHelper.class); 33 | 34 | when(mockResponse.getFirstHeader(CONTENT_TYPE)).thenReturn(APPLICATION_JSON.toString()); 35 | 36 | handler = new DefaultJsonResponseHandler<>(String.class); 37 | } 38 | 39 | @Test 40 | public void test_ErrorResponse() 41 | { 42 | when(mockResponse.getStatusCode()).thenReturn(500); 43 | when(mockResponse.getStatusMessage()).thenReturn("The status message"); 44 | 45 | try 46 | { 47 | handler.handle(mockRequest, mockResponse); 48 | assertThat(true).as("expected exception").isFalse(); 49 | 50 | } 51 | catch (UnexpectedResponseException e) 52 | { 53 | assertThat(e.getStatusCode()).isEqualTo(500); 54 | assertThat(e.getStatusMessage()).isEqualTo("The status message"); 55 | } 56 | } 57 | 58 | @Test 59 | public void test_noContentType() 60 | { 61 | when(mockResponse.getStatusCode()).thenReturn(200); 62 | when(mockResponse.getStatusMessage()).thenReturn("OK"); 63 | when(mockResponse.getFirstHeader(CONTENT_TYPE)).thenReturn(null); 64 | 65 | try 66 | { 67 | handler.handle(mockRequest, mockResponse); 68 | assertThat(true).as("expected exception").isFalse(); 69 | } 70 | catch (UnexpectedResponseException e) 71 | { 72 | assertThat(e.getMessage()).isEqualTo("Content-Type is not set for response"); 73 | } 74 | } 75 | 76 | @Test 77 | public void test_invalidMediaType() 78 | { 79 | when(mockResponse.getStatusCode()).thenReturn(200); 80 | when(mockResponse.getStatusMessage()).thenReturn("OK"); 81 | when(mockResponse.getFirstHeader(CONTENT_TYPE)).thenReturn("application/bogus"); 82 | 83 | try 84 | { 85 | handler.handle(mockRequest, mockResponse); 86 | assertThat(true).as("expected exception").isFalse(); 87 | } 88 | catch (UnexpectedResponseException e) 89 | { 90 | assertThat(e.getMessage()).isEqualTo("Expected application/json response from server but got application/bogus"); 91 | } 92 | } 93 | 94 | @Test 95 | public void test_badJsonRequest() throws IOException 96 | { 97 | when(mockResponse.getStatusCode()).thenReturn(400); 98 | when(mockResponse.getStatusMessage()).thenReturn("Bad Request"); 99 | when(mockResponse.getInputStream()).thenReturn(new ByteArrayInputStream("{\"errors\":[\"error message\"]}".getBytes())); 100 | 101 | try 102 | { 103 | handler.handle(mockRequest, mockResponse); 104 | assertThat(true).as("expected exception").isFalse(); 105 | } 106 | catch (UnexpectedResponseException e) 107 | { 108 | assertThat(e.getMessage()).isEqualTo("Expected response code to be [200, 204], but was 400: Errors: error message\n"); 109 | } 110 | } 111 | 112 | @Test 113 | public void test_JsonSyntaxException() throws IOException 114 | { 115 | when(mockResponse.getStatusCode()).thenReturn(200); 116 | when(mockResponse.getStatusMessage()).thenReturn("OK"); 117 | when(mockResponse.getInputStream()).thenReturn(new ByteArrayInputStream("{bogus}".getBytes())); 118 | 119 | try 120 | { 121 | handler.handle(mockRequest, mockResponse); 122 | assertThat(true).as("expected exception").isFalse(); 123 | } 124 | catch (IllegalArgumentException e) 125 | { 126 | assertThat(e.getMessage()).isEqualTo("Unable to create parse JSON response:\n"); 127 | } 128 | } 129 | 130 | @Test 131 | public void test_RuntimeException() throws IOException 132 | { 133 | when(mockResponse.getStatusCode()).thenReturn(200); 134 | when(mockResponse.getStatusMessage()).thenReturn("OK"); 135 | when(mockResponse.getInputStream()).thenThrow(new IOException()); 136 | 137 | try 138 | { 139 | handler.handle(mockRequest, mockResponse); 140 | assertThat(true).as("expected exception").isFalse(); 141 | } 142 | catch (RuntimeException e) 143 | { 144 | assertThat(e.getMessage()).isEqualTo("Error reading JSON response from server"); 145 | } 146 | } 147 | 148 | @Test 149 | /* 150 | Apparently some proxies/gateways return 204 with content. That's just wrong. 151 | */ 152 | public void test_NoContent() throws IOException 153 | { 154 | when(mockResponse.getStatusCode()).thenReturn(204); 155 | when(mockResponse.getStatusMessage()).thenReturn("OK"); 156 | when(mockResponse.getInputStream()).thenReturn(new ByteArrayInputStream("bogus".getBytes())); 157 | 158 | String response = handler.handle(mockRequest, mockResponse); 159 | 160 | assertNull(response); 161 | } 162 | 163 | @Test 164 | public void test() throws IOException 165 | { 166 | String json = Resources.toString(Resources.getResource("rollup.json"), Charsets.UTF_8); 167 | DefaultJsonResponseHandler handler = new DefaultJsonResponseHandler<>(RollupTask.class); 168 | when(mockResponse.getStatusCode()).thenReturn(200); 169 | when(mockResponse.getStatusMessage()).thenReturn("OK"); 170 | when(mockResponse.getInputStream()).thenReturn(new ByteArrayInputStream(json.getBytes())); 171 | 172 | RollupTask task = handler.handle(mockRequest, mockResponse); 173 | 174 | JsonMapper mapper = new JsonMapper(new DataPointTypeRegistry()); 175 | assertThat(task).isEqualTo(mapper.fromJson(json, RollupTask.class)); 176 | } 177 | } -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/response/grouping/BinGroupResultTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | import static org.hamcrest.CoreMatchers.equalTo; 11 | import static org.hamcrest.MatcherAssert.assertThat; 12 | import static org.hamcrest.Matchers.hasItems; 13 | 14 | public class BinGroupResultTest 15 | { 16 | @Test(expected = NullPointerException.class) 17 | public void test_constructor_null_bins_invalid() 18 | { 19 | new BinGroupResult(null, new HashMap()); 20 | } 21 | 22 | @Test(expected = NullPointerException.class) 23 | public void test_constructor_null_group_invalid() 24 | { 25 | new BinGroupResult(new ArrayList(), null); 26 | } 27 | 28 | @Test 29 | public void test_getBins() 30 | { 31 | BinGroupResult result = new BinGroupResult(Arrays.asList(1.0, 2.0, 3.0), new HashMap()); 32 | 33 | assertThat(result.getBins(), hasItems(1.0, 2.0, 3.0)); 34 | } 35 | 36 | @Test 37 | public void test_getBinNumber() 38 | { 39 | Map groups = new HashMap(); 40 | groups.put("bin_number", 2); 41 | 42 | BinGroupResult result = new BinGroupResult(Arrays.asList(1.0, 2.0, 3.0), groups); 43 | 44 | assertThat(result.getBinNumber(), equalTo(2)); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/response/grouping/DefaultGroupResultTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import org.junit.Test; 4 | 5 | public class DefaultGroupResultTest 6 | { 7 | @Test(expected = NullPointerException.class) 8 | public void test_constructor_type_null_invalid() 9 | { 10 | new DefaultGroupResult("name", null); 11 | } 12 | 13 | @Test(expected = IllegalArgumentException.class) 14 | public void test_constructor_type_empty_invalid() 15 | { 16 | new DefaultGroupResult("name", ""); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/response/grouping/TagGroupResultTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | 8 | public class TagGroupResultTest 9 | { 10 | @Test(expected = NullPointerException.class) 11 | public void test_constructor_null_tags_invalid() 12 | { 13 | new TagGroupResult(null, new HashMap()); 14 | } 15 | 16 | @Test(expected = NullPointerException.class) 17 | public void test_constructor_null_group_invalid() 18 | { 19 | new TagGroupResult(new ArrayList(), null); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/response/grouping/TimeGroupResultTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import org.junit.Test; 4 | import org.kairosdb.client.builder.RelativeTime; 5 | import org.kairosdb.client.builder.TimeUnit; 6 | 7 | public class TimeGroupResultTest 8 | { 9 | 10 | @Test(expected = IllegalArgumentException.class) 11 | public void test_constructor_Zero_GroupCount_invalid() 12 | { 13 | new TimeGroupResult(new RelativeTime(1, TimeUnit.MILLISECONDS), 0, new GroupingNumber(2)); 14 | } 15 | 16 | @Test(expected = NullPointerException.class) 17 | public void test_constructor_null_RelativeTime_invalid() 18 | { 19 | new TimeGroupResult(null, 2, new GroupingNumber(2)); 20 | } 21 | 22 | @Test(expected = NullPointerException.class) 23 | public void test_constructor_null_GroupNumber_invalid() 24 | { 25 | new TimeGroupResult(new RelativeTime(1, TimeUnit.MILLISECONDS), 2, null); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/response/grouping/ValueGroupResultTest.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.response.grouping; 2 | 3 | import org.junit.Test; 4 | 5 | public class ValueGroupResultTest 6 | { 7 | 8 | @Test(expected = NullPointerException.class) 9 | public void test_constructor_null_GroupingNumber_invalid() 10 | { 11 | new ValueGroupResult(1, null); 12 | } 13 | 14 | @Test(expected = IllegalArgumentException.class) 15 | public void test_constructor_rangeSize_Zero_invalid() 16 | { 17 | new ValueGroupResult(0, new GroupingNumber(1)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/testUtils/MetricParser.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.testUtils; 2 | 3 | import com.google.gson.*; 4 | import com.google.gson.reflect.TypeToken; 5 | import org.kairosdb.client.builder.DataPoint; 6 | import org.kairosdb.client.builder.Metric; 7 | 8 | import java.lang.reflect.Type; 9 | import java.util.List; 10 | 11 | public class MetricParser 12 | { 13 | private static final Type listType = new TypeToken>(){}.getType(); 14 | 15 | private final Gson gson; 16 | 17 | public MetricParser() 18 | { 19 | GsonBuilder gsonBuilder = new GsonBuilder(); 20 | gsonBuilder.registerTypeAdapter(DataPoint.class, new DataPointDeserializer()); 21 | gson = gsonBuilder.create(); 22 | } 23 | 24 | public List parse(String json) 25 | { 26 | return gson.fromJson(json, listType); 27 | } 28 | 29 | private class DataPointDeserializer implements JsonDeserializer 30 | { 31 | @Override 32 | public DataPoint deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException 33 | { 34 | JsonArray array = jsonElement.getAsJsonArray(); 35 | long timestamp = array.get(0).getAsLong(); 36 | double value = array.get(1).getAsDouble(); 37 | return new DataPoint(timestamp, value); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/org/kairosdb/client/testUtils/QueryParser.java: -------------------------------------------------------------------------------- 1 | package org.kairosdb.client.testUtils; 2 | 3 | import com.google.common.collect.ListMultimap; 4 | import com.google.gson.Gson; 5 | import com.google.gson.GsonBuilder; 6 | import org.kairosdb.client.builder.Grouper; 7 | import org.kairosdb.client.builder.QueryBuilder; 8 | import org.kairosdb.client.deserializer.GrouperDeserializer; 9 | import org.kairosdb.client.deserializer.ListMultiMapDeserializer; 10 | import org.kairosdb.client.deserializer.TimeZoneDeserializer; 11 | 12 | import java.util.TimeZone; 13 | 14 | public class QueryParser 15 | { 16 | private final Gson gson; 17 | 18 | public QueryParser() 19 | { 20 | GsonBuilder gsonBuilder = new GsonBuilder(); 21 | gsonBuilder.registerTypeAdapter(ListMultimap.class, new ListMultiMapDeserializer()); 22 | gsonBuilder.registerTypeAdapter(TimeZone.class, new TimeZoneDeserializer()); 23 | gsonBuilder.registerTypeAdapter(Grouper.class, new GrouperDeserializer()); 24 | gson = gsonBuilder.create(); 25 | } 26 | 27 | public QueryBuilder parse(String json) 28 | { 29 | return gson.fromJson(json, QueryBuilder.class); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/resources/kairos.properties: -------------------------------------------------------------------------------- 1 | kairosdb.service.datapointListener=org.kairosdb.client.ListenerModule 2 | kairosdb.service.customDataModule=org.kairosdb.client.CustomDataModule 3 | kairosdb.eventbus.filter.priority.org.kairosdb.client.TestDataPointListener=90 4 | 5 | kairosdb.datapoints.factory.complex-number=org.kairosdb.client.ComplexNumberDataPointFactory 6 | 7 | kairosdb.jetty.port=8082 8 | 9 | kairosdb.jetty.ssl.port=8443 10 | kairosdb.jetty.ssl.keystore.path=src/test/resources/ssl.jks 11 | kairosdb.jetty.ssl.keystore.password=testtest 12 | 13 | kairosdb.telnetserver.port=4245 14 | 15 | kairosdb.service.rollups=org.kairosdb.rollup.RollUpModule 16 | kairosdb.rollups.server_assignment.check_update_delay_millseconds=10000 -------------------------------------------------------------------------------- /src/test/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | %d{HH:mm:ss.SSS} [%thread] %-5level [%file:%line] - %msg%n 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/test/resources/multiple_metrics.json: -------------------------------------------------------------------------------- 1 | [{"name":"metric1","tags":{"tag2":"tab2value","tag1":"tab1value"},"datapoints":[[1,10],[2,30]]},{"name":"metric2","tags":{"tag3":"tab3value"},"datapoints":[[2,30],[3,2.3]]}] -------------------------------------------------------------------------------- /src/test/resources/query_multiple_metrics_relative_times.json: -------------------------------------------------------------------------------- 1 | {"start_relative":{"value":3,"unit":"WEEKS"},"end_relative":{"value":2,"unit":"DAYS"},"cache_time":2000,"metrics":[{"name":"metric1","tags":{"larry":["moe"],"foo":["bar"]},"group_by":[],"aggregators":[{"sampling":{"value":1,"unit":"DAYS"},"name":"max"}]},{"name":"metric2","tags":{"curly":["joe"]},"group_by":[],"aggregators":[]}]} -------------------------------------------------------------------------------- /src/test/resources/query_single_metric_absoluteStart_noEndTime_noTags.json: -------------------------------------------------------------------------------- 1 | {"start_absolute":1359774127000,"cache_time":0,"metrics":[{"name":"metric1","tags":{},"group_by":[],"aggregators":[{"sampling":{"value":1,"unit":"DAYS"},"name":"max"},{"unit":"MINUTES","name":"rate"}]}]} -------------------------------------------------------------------------------- /src/test/resources/query_single_metric_aggregator_with_alignment.json: -------------------------------------------------------------------------------- 1 | {"start_absolute":1359774127000,"end_absolute":13597745127000,"cache_time":0,"metrics":[{"name":"metric1","tags":{},"group_by":[],"aggregators":[{"sampling":{"value":1,"unit":"DAYS"},"align_sampling":true,"name":"max"}]}]} -------------------------------------------------------------------------------- /src/test/resources/query_tag_response_valid.json: -------------------------------------------------------------------------------- 1 | { 2 | "queries": [ 3 | { 4 | "results": [ 5 | { 6 | "name": "kairosdb.datastore.query_time", 7 | "tags": { 8 | "host": [ 9 | "localhost", 10 | "host2" 11 | ], 12 | "rollup": [ 13 | "kairos.import_export_unit_test_rollup" 14 | ], 15 | "status": [ 16 | "success" 17 | ] 18 | } 19 | } 20 | ] 21 | } 22 | ] 23 | } -------------------------------------------------------------------------------- /src/test/resources/query_withGroupBys.json: -------------------------------------------------------------------------------- 1 | {"start_relative":{"value":2,"unit":"MONTHS"},"cache_time":0,"metrics":[{"name":"metric1","tags":{},"group_by":[{"range_size":10,"name":"value"},{"tags":["tag1","tag2"],"name":"tag"},{"range_size":{"value":2,"unit":"HOURS"},"group_count":3,"name":"time"}],"aggregators":[]}]} -------------------------------------------------------------------------------- /src/test/resources/query_withLimitAndOrder.json: -------------------------------------------------------------------------------- 1 | {"start_relative":{"value":2,"unit":"MONTHS"},"cache_time":0,"metrics":[{"name":"metric1","tags":{},"group_by":[],"aggregators":[],"limit":10,"order":"desc"}]} -------------------------------------------------------------------------------- /src/test/resources/query_withTimeZone.json: -------------------------------------------------------------------------------- 1 | {"start_relative":{"value":2,"unit":"MONTHS"},"cache_time":0,"time_zone":"Europe/Vienna","metrics":[{"name":"metric1","tags":{},"group_by":[],"aggregators":[],"limit":10,"order":"desc"}]} -------------------------------------------------------------------------------- /src/test/resources/response_valid.json: -------------------------------------------------------------------------------- 1 | {"queries": [ 2 | { 3 | "results": [ 4 | { 5 | "name": "archive_search", 6 | "group_by": [ 7 | { 8 | "name": "type", 9 | "type": "number" 10 | }, 11 | { 12 | "name": "value", 13 | "range_size": 10, 14 | "group": { 15 | "group_number": 2 16 | } 17 | }, 18 | { 19 | "name": "tag", 20 | "tags": ["bucket", "customer", "datacenter"], 21 | "group": { 22 | "bucket": "5-10s", 23 | "customer": "Acme" 24 | } 25 | }, 26 | { 27 | "name": "time", 28 | "range_size": { 29 | "value": 1, 30 | "unit": "HOURS" 31 | }, 32 | "group_count": 168, 33 | "group": { 34 | "group_number": 3 35 | } 36 | } 37 | ], 38 | "tags": { 39 | "partner_guid": ["messagelabs"], 40 | "bucket": ["0-5s", "10-20s", "5-10s", "20s-"] 41 | }, 42 | "values": [ 43 | [1362034800000, 1], 44 | [1362121200000, 2], 45 | [1362207600000, 3] 46 | ] 47 | } 48 | ] 49 | } 50 | ]} -------------------------------------------------------------------------------- /src/test/resources/rollup.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rollupTask", 3 | "execution_interval": { 4 | "value": 1, 5 | "unit": "HOURS" 6 | }, 7 | "rollups": [{ 8 | "save_as": "myRollupMetric", 9 | "query": { 10 | "cache_time": 0, 11 | "metrics": [{ 12 | "name": "metric1", 13 | "tags": {}, 14 | "group_by": [{ 15 | "tags": ["tag1", "tag2"], 16 | "name": "tag" 17 | }], 18 | "aggregators": [{ 19 | "sampling": { 20 | "value": 1, 21 | "unit": "MINUTES" 22 | }, 23 | "name": "max" 24 | }, { 25 | "sampling": { 26 | "value": 1, 27 | "unit": "MINUTES" 28 | }, 29 | "name": "count" 30 | }], 31 | "exclude_tags": false 32 | }], 33 | "start_relative": { 34 | "value": 1, 35 | "unit": "HOURS" 36 | } 37 | } 38 | }] 39 | } -------------------------------------------------------------------------------- /src/test/resources/rollupResponse.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "7b2893fc-7654-4764-851a-a311e854ee75", 3 | "name": "MyRollupTaskName", 4 | "attributes": { 5 | "url": "/api/v1/rollups/7b2893fc-7654-4764-851a-a311e854ee75" 6 | } 7 | } -------------------------------------------------------------------------------- /src/test/resources/rollups.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "id": "6cfeaf58-2c6d-485a-9d19-1ea8a47db7ee", 3 | "name": "Rollup1", 4 | "rollups": [{ 5 | "save_as": "metric1_rollup", 6 | "query": { 7 | "metrics": [{ 8 | "name": "metric1", 9 | "tags": {}, 10 | "aggregators": [{ 11 | "sampling": { 12 | "value": 1, 13 | "unit": "MINUTES" 14 | }, 15 | "name": "max", 16 | "align_end_time": false, 17 | "align_sampling": true, 18 | "align_start_time": false 19 | }] 20 | }], 21 | "start_relative": { 22 | "value": 1, 23 | "unit": "hours" 24 | } 25 | } 26 | }], 27 | "execution_interval": { 28 | "value": 1, 29 | "unit": "days" 30 | } 31 | }, { 32 | "id": "62acaf73-3af1-4bb9-a975-bbdff408c511", 33 | "name": "Rollup2", 34 | "rollups": [{ 35 | "save_as": "metric1_rollup", 36 | "query": { 37 | "metrics": [{ 38 | "name": "metric1", 39 | "tags": {}, 40 | "aggregators": [{ 41 | "sampling": { 42 | "value": 1, 43 | "unit": "MINUTES" 44 | }, 45 | "name": "max", 46 | "align_end_time": false, 47 | "align_sampling": true, 48 | "align_start_time": false 49 | }] 50 | }], 51 | "start_relative": { 52 | "value": 1, 53 | "unit": "hours" 54 | } 55 | } 56 | }], 57 | "execution_interval": { 58 | "value": 1, 59 | "unit": "days" 60 | } 61 | }, { 62 | "id": "724432c4-6b14-4cb4-88a2-9908979fe9a5", 63 | "name": "Rollup3", 64 | "rollups": [{ 65 | "save_as": "metric1_rollup", 66 | "query": { 67 | "metrics": [{ 68 | "name": "metric1", 69 | "tags": {}, 70 | "aggregators": [{ 71 | "sampling": { 72 | "value": 1, 73 | "unit": "MINUTES" 74 | }, 75 | "name": "max", 76 | "align_end_time": false, 77 | "align_sampling": true, 78 | "align_start_time": false 79 | }] 80 | }], 81 | "start_relative": { 82 | "value": 1, 83 | "unit": "hours" 84 | } 85 | } 86 | }], 87 | "execution_interval": { 88 | "value": 1, 89 | "unit": "days" 90 | } 91 | }] -------------------------------------------------------------------------------- /src/test/resources/ssl.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kairosdb/kairosdb-client/08be6b5a60f0856851ea31bfa709bd738e3aff2c/src/test/resources/ssl.jks --------------------------------------------------------------------------------