From 9f1ca865e811baa78762e3663b4935607365a3c4 Mon Sep 17 00:00:00 2001 From: Jeremy Whitlock Date: Fri, 25 May 2012 13:39:14 -0600 Subject: [PATCH 01/73] Implement PutMetricData for CloudWatch. * Added support to create custom metrics in CloudWatch * Fixed bug in Datapoint parsing that caused Sample(Count) to be null --- .../jclouds/cloudwatch/CloudWatchClient.java | 11 +- .../binders/GetMetricStatisticsBinder.java | 12 +- .../binders/PutMetricDataBinder.java | 101 +++++++ .../domain/GetMetricStatistics.java | 17 +- .../cloudwatch/domain/MetricDatum.java | 260 ++++++++++++++++++ .../cloudwatch/domain/PutMetricData.java | 154 +++++++++++ .../cloudwatch/domain/StatisticSet.java | 172 ++++++++++++ .../features/MetricAsyncClient.java | 17 +- .../cloudwatch/features/MetricClient.java | 24 +- .../cloudwatch/xml/DatapointHandler.java | 9 +- .../binders/PutMetricDataBinderTest.java | 168 +++++++++++ .../features/MetricClientExpectTest.java | 17 +- .../features/MetricClientLiveTest.java | 117 +++++++- .../test/resources/get_metric_statistics.xml | 4 +- 14 files changed, 1028 insertions(+), 55 deletions(-) create mode 100644 apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/PutMetricDataBinder.java create mode 100644 apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java create mode 100644 apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java create mode 100644 apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java create mode 100644 apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatchClient.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatchClient.java index 2633563111..8234a035c3 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatchClient.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatchClient.java @@ -18,10 +18,7 @@ */ package org.jclouds.cloudwatch; -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; - +import com.google.inject.Provides; import org.jclouds.cloudwatch.domain.Datapoint; import org.jclouds.cloudwatch.domain.Statistics; import org.jclouds.cloudwatch.features.MetricClient; @@ -33,7 +30,9 @@ import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; import org.jclouds.rest.annotations.Delegate; import org.jclouds.rest.annotations.EndpointParam; -import com.google.inject.Provides; +import java.util.Date; +import java.util.Set; +import java.util.concurrent.TimeUnit; /** * Provides access to Amazon CloudWatch via the Query API @@ -90,7 +89,7 @@ public interface CloudWatchClient { * The statistics to be returned for the given metric. ex. Average * @param options * more filtering options (e.g. instance ID) - * @see MetricsClient#getMetricStatistics + * @see MetricClient#getMetricStatistics(org.jclouds.cloudwatch.domain.GetMetricStatistics) */ @Deprecated Set getMetricStatisticsInRegion(@Nullable String region, String metricName, String namespace, diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java index 1e2b6f49c7..bbb69ee3a0 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java @@ -18,8 +18,8 @@ */ package org.jclouds.cloudwatch.binders; -import javax.inject.Inject; - +import com.google.common.annotations.Beta; +import com.google.common.collect.ImmutableMultimap; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.GetMetricStatistics; import org.jclouds.cloudwatch.domain.Statistics; @@ -27,8 +27,7 @@ import org.jclouds.date.DateService; import org.jclouds.http.HttpRequest; import org.jclouds.http.utils.ModifyRequest; -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMultimap; +import javax.inject.Inject; /** * Binds the metrics request to the http request @@ -45,7 +44,7 @@ public class GetMetricStatisticsBinder implements org.jclouds.rest.Binder { @Inject protected GetMetricStatisticsBinder(DateService dateService){ - this.dateService =dateService; + this.dateService = dateService; } @Override @@ -54,7 +53,7 @@ public class GetMetricStatisticsBinder implements org.jclouds.rest.Binder { int dimensionIndex = 1; int statisticIndex = 1; - ImmutableMultimap.Builder formParameters = ImmutableMultimap. builder(); + ImmutableMultimap.Builder formParameters = ImmutableMultimap.builder(); for (Dimension dimension : getRequest.getDimensions()) { formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue()); @@ -77,4 +76,5 @@ public class GetMetricStatisticsBinder implements org.jclouds.rest.Binder { return ModifyRequest.putFormParams(request, formParameters.build()); } + } \ No newline at end of file diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/PutMetricDataBinder.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/PutMetricDataBinder.java new file mode 100644 index 0000000000..3a13a2bee5 --- /dev/null +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/PutMetricDataBinder.java @@ -0,0 +1,101 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudwatch.binders; + +import com.google.common.annotations.Beta; +import com.google.common.collect.ImmutableMultimap; +import com.google.inject.Inject; +import org.jclouds.cloudwatch.domain.Dimension; +import org.jclouds.cloudwatch.domain.MetricDatum; +import org.jclouds.cloudwatch.domain.PutMetricData; +import org.jclouds.cloudwatch.domain.StatisticSet; +import org.jclouds.date.DateService; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.utils.ModifyRequest; + +/** + * Binds the metrics request to the http request + * + * @see + * + * @author Jeremy Whitlock + */ +@Beta +public class PutMetricDataBinder implements org.jclouds.rest.Binder { + + private final DateService dateService; + + @Inject + protected PutMetricDataBinder(DateService dateService) { + this.dateService = dateService; + } + + /** + * {@inheritDoc} + */ + @Override + public R bindToRequest(R request, Object input) { + PutMetricData pmdRequest = PutMetricData.class.cast(input); + ImmutableMultimap.Builder formParameters = ImmutableMultimap.builder(); + int metricDatumIndex = 1; + + formParameters.put("Namespace", pmdRequest.getNamespace()); + + for (MetricDatum metricDatum : pmdRequest.getMetricData()) { + int dimensionIndex = 1; + StatisticSet statisticSet = metricDatum.getStatisticSet(); + + for (Dimension dimension : metricDatum.getDimensions()) { + formParameters.put("MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + + ".Name", dimension.getName()); + formParameters.put("MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + + ".Value", dimension.getValue()); + dimensionIndex++; + } + + formParameters.put("MetricData.member." + metricDatumIndex + ".MetricName", metricDatum.getMetricName()); + + if (statisticSet != null) { + formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Maximum", + String.valueOf(statisticSet.getMaximum())); + formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Minimum", + String.valueOf(statisticSet.getMinimum())); + formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.SampleCount", + String.valueOf(statisticSet.getSampleCount())); + formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Sum", + String.valueOf(statisticSet.getSum())); + } + if (metricDatum.getTimestamp() != null) { + formParameters.put("MetricData.member." + metricDatumIndex + ".Timestamp", + dateService.iso8601SecondsDateFormat(metricDatum.getTimestamp())); + } + + formParameters.put("MetricData.member." + metricDatumIndex + ".Unit", String.valueOf(metricDatum.getUnit())); + + if (metricDatum.getValue() != null) { + formParameters.put("MetricData.member." + metricDatumIndex + ".Value", String.valueOf(metricDatum.getValue())); + } + + metricDatumIndex++; + } + + return ModifyRequest.putFormParams(request, formParameters.build()); + } + +} diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java index 1b5167c293..9a03ecd59f 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java @@ -18,15 +18,14 @@ */ package org.jclouds.cloudwatch.domain; -import java.util.Date; -import java.util.Set; - -import org.jclouds.cloudwatch.options.ListMetricsOptions; -import org.jclouds.javax.annotation.Nullable; - import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; +import org.jclouds.cloudwatch.options.ListMetricsOptions; +import org.jclouds.javax.annotation.Nullable; + +import java.util.Date; +import java.util.Set; /** * Options use to get statistics for the specified metric. @@ -152,7 +151,7 @@ public class GetMetricStatistics { * * @return this {@code Builder} object * - * @throws IllegalArgumentException if this is invoked more than 10 times + * @throws IllegalArgumentException if the passed in dimensions has more than 10 members */ public Builder dimensions(Set dimensions) { if (dimensions != null) { @@ -335,8 +334,10 @@ public class GetMetricStatistics { Preconditions.checkNotNull(unit, "unit cannot be null."); Preconditions.checkArgument(statistics.size() >= 1, "statistics must have at least one member"); - return new GetMetricStatistics(dimensions, endTime, metricName,namespace, period, startTime, statistics, unit); + return new GetMetricStatistics(dimensions, endTime, metricName,namespace, period, startTime, statistics, + unit); } + } } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java new file mode 100644 index 0000000000..89d92eb30f --- /dev/null +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java @@ -0,0 +1,260 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudwatch.domain; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import org.jclouds.javax.annotation.Nullable; + +import java.util.Date; +import java.util.Set; + +/** + * @see + * + * @author Jeremy Whitlock + */ +public class MetricDatum { + + private final Set dimensions; + private final String metricName; + private final StatisticSet statisticSet; + private final Date timestamp; + private final Unit unit; + private final Double value; + + /** + * Private constructor to enforce using {@link Builder}. + */ + private MetricDatum(@Nullable Set dimensions, String metricName, StatisticSet statisticSet, + @Nullable Date timestamp, Unit unit, Double value) { + // Default to an empty set + if (dimensions == null) { + this.dimensions = Sets.newLinkedHashSet(); + } else { + this.dimensions = dimensions; + } + this.metricName = metricName; + this.statisticSet = statisticSet; + this.timestamp = timestamp; + this.unit = unit; + this.value = value; + } + + /** + * return the list of dimensions describing the the metric. + */ + @Nullable + public Set getDimensions() { + return dimensions; + } + + /** + * return the metric name for the metric. + */ + public String getMetricName() { + return metricName; + } + + /** + * return the object describing the set of statistical values for the metric (This and value are mutually + * exclusive.) + */ + public StatisticSet getStatisticSet() { + return statisticSet; + } + + /** + * return the time stamp used for the metric + */ + @Nullable + public Date getTimestamp() { + return timestamp; + } + + /** + * return Standard unit used for the metric. + */ + public Unit getUnit() { + return unit; + } + + /** + * return the actual value of the metric (This and statisticSet are mutually exclusive.) + * + */ + public Double getValue() { + return value; + } + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private Set dimensions = Sets.newLinkedHashSet(); + private String metricName; + private StatisticSet statisticSet; + private Date timestamp; + private Unit unit; + private Double value; + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link org.jclouds.cloudwatch.domain.MetricDatum#builder}. + */ + public Builder() {} + + /** + * A list of dimensions describing qualities of the metric. (Set can be 10 or less items.) + * + * @param dimensions the dimensions describing the qualities of the metric + * + * @return this {@code Builder} object + * + * @throws IllegalArgumentException if the passed in dimensions has more than 10 members + */ + public Builder dimensions(Set dimensions) { + if (dimensions != null) { + Preconditions.checkArgument(dimensions.size() <= 10, "dimensions can have 10 or fewer members."); + this.dimensions = dimensions; + } + return this; + } + + /** + * A dimension describing qualities of the metric. (Can be called multiple times up to a maximum of 10 times.) + * + * @param dimension the dimension describing the qualities of the metric + * + * @return this {@code Builder} object + * + * @throws IllegalArgumentException if the number of dimensions would be greater than 10 after adding + */ + public Builder dimension(Dimension dimension) { + if (dimension != null) { + Preconditions.checkArgument(dimensions.size() < 10, "dimension member maximum count of 10 exceeded."); + this.dimensions.add(dimension); + } + return this; + } + + /** + * The name of the metric. (Should be called once. Subsequent calls will overwrite the previous value.) + * + * @param metricName the metric name + * + * @return this {@code Builder} object + * + * @throws NullPointerException if metricName is null + * @throws IllegalArgumentException if metricName is empty + */ + public Builder metricName(String metricName) { + Preconditions.checkNotNull(metricName, "metricName cannot be null."); + Preconditions.checkArgument(metricName.length() > 1, "metricName must not be empty."); + this.metricName = metricName; + return this; + } + + /** + * The object describing the set of statistical values describing the metric. (Should be called once. Subsequent + * calls will overwrite the previous value. Also, this cannot be set once you've set the value.) + * + * @param statisticSet the object describing the set of statistical values for the metric + * + * @return this {@code Builder} object + * + * @throws NullPointerException if statisticSet is null + * @throws IllegalArgumentException if value has already been set + */ + public Builder statisticSet(StatisticSet statisticSet) { + Preconditions.checkArgument(value == null, "value and statisticSet are mutually exclusive"); + this.statisticSet = statisticSet; + return this; + } + + /** + * The time stamp used for the metric. If not specified, the default value is set to the time the metric data was + * received. (Should be called once. Subsequent calls will overwrite the previous value.) + * + * @param timestamp the time stamp used for the metric + * + * @return this {@code Builder} object + */ + public Builder timestamp(Date timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * The unit for the metric. (Should be called once. Subsequent calls will overwrite the previous value.) + * + * @param unit the unit for the metric + * + * @return this {@code Builder} object + * + * @throws NullPointerException if unit is null + */ + public Builder unit(Unit unit) { + Preconditions.checkNotNull(unit, "unit cannot be null."); + this.unit = unit; + return this; + } + + /** + * The value for the metric. (Should be called once. Subsequent calls will overwrite the previous value. Also, + * this cannot be set once you've set the statisticValue.) + * + * @param value the value for the metric + * + * @return this {@code Builder} object + * + * @throws IllegalArgumentException if statisticSet has already been set + */ + public Builder value(Double value) { + Preconditions.checkArgument(statisticSet == null, "statisticSet and value are mutually exclusive"); + this.value = value; + return this; + } + + /** + * Returns a newly-created {@code MetricDatum} based on the contents of the {@code Builder}. + * + * @throws NullPointerException if any of the required fields are null + * @throws IllegalArgumentException if any of the provided fields don't meet required criteria + */ + public MetricDatum build() { + Preconditions.checkNotNull(metricName, "metricName cannot be null."); + Preconditions.checkNotNull(unit, "unit cannot be null."); + Preconditions.checkArgument(metricName.length() > 1 && metricName.length() <= 255, + "metricName cannot be empty and must be 255 characters or less."); + Preconditions.checkArgument(statisticSet != null || value != null, + "statisticSet or value must be set"); + + return new MetricDatum(dimensions, metricName, statisticSet, timestamp, unit, value); + } + + } + +} diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java new file mode 100644 index 0000000000..8529fdee19 --- /dev/null +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java @@ -0,0 +1,154 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudwatch.domain; + +import com.google.common.annotations.Beta; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; + +import java.util.Set; + +/** + * Options use to get statistics for the specified metric. + * + * @see + * + * @author Jeremy Whitlock + */ +@Beta +public class PutMetricData { + + private final String namespace; + private final Set metricData; + + /** + * Private constructor to enforce using {@link Builder}. + */ + private PutMetricData(String namespace, Set metricData) { + this.namespace = namespace; + this.metricData = metricData; + } + + /** + * return the namespace for this request + */ + public String getNamespace() { + return namespace; + } + + /** + * return the metric data for this request + */ + public Set getMetricData() { + return metricData; + } + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String namespace; + private Set metricData = Sets.newLinkedHashSet(); + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link org.jclouds.cloudwatch.domain.PutMetricData#builder}. + */ + public Builder() {} + + /** + * The namespace for the metric data. (Should be called once. Subsequent calls will overwrite the previous + * value.) This value cannot start with "AWS/" as that namespace prefix is reserved for AWS CloudWatch + * metrics. + * + * @param namespace the namespace for the metric data + * + * @return this {@code Builder} object + * + * @throws NullPointerException if namespace is null + * @throws IllegalArgumentException if namespace is empty or starts with "AWS/" + */ + public Builder namespace(String namespace) { + Preconditions.checkNotNull(namespace, "namespace cannot be null."); + Preconditions.checkArgument(namespace.length() > 1, "namespace must not be empty."); + Preconditions.checkArgument(!namespace.startsWith("AWS/"), "namespace cannot start with 'AWS/' as it's " + + "reserved for AWS CloudWatch metrics."); + this.namespace = namespace; + return this; + } + + /** + * A metric to either create or aggregate to an existing metric. (Can be called multiple times up to a maximum of + * 10 times.) + * + * @param metricDatum the representation of a metric to either create a new metric or add new values to be + * aggregated into an existing metric + * + * @return this {@code Builder} object + * + * @throws IllegalArgumentException if the number of dimensions would be greater than 10 after adding + */ + public Builder metricDatum(MetricDatum metricDatum) { + if (metricDatum != null) { + Preconditions.checkArgument(metricData.size() < 10, "metric data member maximum count of 10 exceeded."); + this.metricData.add(metricDatum); + } + return this; + } + + /** + * A list of data describing the metric. (Set can be 10 or less items.) + * + * @param metricData the list of data describing the data + * + * @return this {@code Builder} object + * + * @throws IllegalArgumentException if the passed in data has more than 10 members + */ + public Builder metricData(Set metricData) { + if (metricData != null) { + Preconditions.checkArgument(metricData.size() <= 10, "metric data can have 10 or fewer members."); + this.metricData = metricData; + } + return this; + } + + /** + * Returns a newly-created {@code PutMetricData} based on the contents of the {@code Builder}. + * + * @throws NullPointerException if any of the required fields are null + * @throws IllegalArgumentException if any of the provided fields don't meet required criteria + */ + public PutMetricData build() { + Preconditions.checkNotNull(namespace, "namespace cannot be null."); + Preconditions.checkNotNull(metricData, "metricData cannot be null."); + Preconditions.checkArgument(metricData.size() > 0, "metricData must have at least one member."); + + return new PutMetricData(namespace, metricData); + } + + } + +} diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java new file mode 100644 index 0000000000..28830f5d4e --- /dev/null +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java @@ -0,0 +1,172 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudwatch.domain; + +import com.google.common.base.Preconditions; +import org.jclouds.javax.annotation.Nullable; + +/** + * @see + * + * @author Jeremy Whitlock + */ +public class StatisticSet { + + private final Double maximum; + private final Double minimum; + private final Double sampleCount; + private final Double sum; + + public StatisticSet(@Nullable Double maximum, @Nullable Double minimum, @Nullable Double sampleCount, + @Nullable Double sum) { + this.maximum = maximum; + this.minimum = minimum; + this.sampleCount = sampleCount; + this.sum = sum; + } + + /** + * return the maximum value of the sample set + */ + public Double getMaximum() { + return maximum; + } + + /** + * return the minimum value of the sample set + */ + public Double getMinimum() { + return minimum; + } + + /** + * return the number of samples used for the statistic set + */ + public Double getSampleCount() { + return sampleCount; + } + + /** + * return the sum of values for the sample set + */ + public Double getSum() { + return sum; + } + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private Double maximum; + private Double minimum; + private Double sampleCount; + private Double sum; + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link org.jclouds.cloudwatch.domain.StatisticSet#builder}. + */ + public Builder() {} + + /** + * The maximum value of the sample set. (Should be called once. Subsequent calls will overwrite the previous + * value.) + * + * @param maximum the maximum value of the sample set + * + * @return this {@code Builder} object + * + * @throws NullPointerException if maximum is null + */ + public Builder maximum(Double maximum) { + Preconditions.checkNotNull(maximum, "maximum cannot be null."); + this.maximum = maximum; + return this; + } + + /** + * The minimum value of the sample set. (Should be called once. Subsequent calls will overwrite the previous + * value.) + * + * @param minimum the minimum value of the sample set + * + * @return this {@code Builder} object + * + * @throws NullPointerException if minimum is null + */ + public Builder minimum(Double minimum) { + Preconditions.checkNotNull(minimum, "minimum cannot be null."); + this.minimum = minimum; + return this; + } + + /** + * The the number of samples used for the statistic set. (Should be called once. Subsequent calls will overwrite + * the previous value.) + * + * @param sampleCount the number of samples used for the statistic set + * + * @return this {@code Builder} object + * + * @throws NullPointerException if sampleCount is null + */ + public Builder sampleCount(Double sampleCount) { + Preconditions.checkNotNull(sampleCount, "sampleCount cannot be null."); + this.sampleCount = sampleCount; + return this; + } + + /** + * The sum of values for the sample set. (Should be called once. Subsequent calls will overwrite the previous + * value.) + * + * @param sum the sum of values for the sample set + * + * @return this {@code Builder} object + * + * @throws NullPointerException if sum is null + */ + public Builder sum(Double sum) { + Preconditions.checkNotNull(sum, "sum cannot be null."); + this.sum = sum; + return this; + } + + /** + * Returns a newly-created {@code StatisticSet} based on the contents of the {@code Builder}. + * + * @throws NullPointerException if any of the required fields are null + */ + public StatisticSet build() { + Preconditions.checkNotNull(maximum, "maximum cannot be null."); + Preconditions.checkNotNull(minimum, "minimum cannot be null."); + Preconditions.checkNotNull(sampleCount, "sampleCount cannot be null."); + Preconditions.checkNotNull(sum, "sum cannot be null."); + return new StatisticSet(maximum, minimum, sampleCount, sum); + } + + } + +} diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java index 6c1852e2c2..32f3858bf6 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java @@ -18,14 +18,14 @@ */ package org.jclouds.cloudwatch.features; -import javax.ws.rs.POST; -import javax.ws.rs.Path; - +import com.google.common.util.concurrent.ListenableFuture; import org.jclouds.aws.filters.FormSigner; import org.jclouds.cloudwatch.binders.GetMetricStatisticsBinder; +import org.jclouds.cloudwatch.binders.PutMetricDataBinder; import org.jclouds.cloudwatch.domain.GetMetricStatistics; import org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse; import org.jclouds.cloudwatch.domain.ListMetricsResponse; +import org.jclouds.cloudwatch.domain.PutMetricData; import org.jclouds.cloudwatch.options.GetMetricStatisticsOptions; import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.jclouds.cloudwatch.xml.GetMetricStatisticsResponseHandlerV2; @@ -36,7 +36,8 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; -import com.google.common.util.concurrent.ListenableFuture; +import javax.ws.rs.POST; +import javax.ws.rs.Path; /** * Provides access to Amazon CloudWatch via the Query API @@ -88,4 +89,12 @@ public interface MetricAsyncClient { @BinderParam(GetMetricStatisticsBinder.class) GetMetricStatistics statistics, GetMetricStatisticsOptions options); + /** + * @see MetricClient#putMetricData(org.jclouds.cloudwatch.domain.PutMetricData) + */ + @POST + @Path("/") + @FormParams(keys = "Action", values = "PutMetricData") + ListenableFuture putMetricData(@BinderParam(PutMetricDataBinder.class) PutMetricData putMetricData); + } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java index 7f5d465185..f70eaa746d 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java @@ -18,15 +18,16 @@ */ package org.jclouds.cloudwatch.features; -import java.util.concurrent.TimeUnit; - import org.jclouds.cloudwatch.domain.GetMetricStatistics; import org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse; import org.jclouds.cloudwatch.domain.ListMetricsResponse; +import org.jclouds.cloudwatch.domain.PutMetricData; import org.jclouds.cloudwatch.options.GetMetricStatisticsOptions; import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.jclouds.concurrent.Timeout; +import java.util.concurrent.TimeUnit; + /** * Provides access to Amazon CloudWatch via the Query API *

@@ -45,10 +46,10 @@ public interface MetricClient { * use returned NextToken ( * {@link org.jclouds.cloudwatch.domain.ListMetricsResponse#getNextToken()}) value with * subsequent calls .To retrieve all available metrics with one call, use - * {@link #list(MetricsClient, String, org.jclouds.cloudwatch.options.ListMetricsOptions)}. + * {@link org.jclouds.cloudwatch.CloudWatch#listMetrics(MetricClient, + * org.jclouds.cloudwatch.options.ListMetricsOptions)} * - * @param options - * the options describing the metrics query + * @param options the options describing the metrics query * * @return the response object */ @@ -59,10 +60,8 @@ public interface MetricClient { /** * Gets statistics for the specified metric. * - * @param statistics - * the statistics to gather - * @param options - * the options describing the metric statistics query + * @param statistics the statistics to gather + * @param options the options describing the metric statistics query * * @return the response object */ @@ -70,4 +69,11 @@ public interface MetricClient { GetMetricStatisticsResponse getMetricStatistics(GetMetricStatistics statistics); + /** + * Publishes metric data points to Amazon CloudWatch. + * + * @param putMetricData object describing the metric data + */ + void putMetricData(PutMetricData putMetricData); + } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/DatapointHandler.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/DatapointHandler.java index 33ab50729e..6be41d8bff 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/DatapointHandler.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/DatapointHandler.java @@ -18,15 +18,14 @@ */ package org.jclouds.cloudwatch.xml; -import java.util.Date; - -import javax.inject.Inject; - import org.jclouds.cloudwatch.domain.Datapoint; import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.date.DateService; import org.jclouds.http.functions.ParseSax; +import javax.inject.Inject; +import java.util.Date; + /** * * @author Adrian Cole @@ -71,7 +70,7 @@ public class DatapointHandler extends ParseSax.HandlerForGeneratedRequestWithRes minimum = doubleOrNull(); } else if (qName.equals("Timestamp")) { timestamp = dateService.iso8601SecondsDateParse(currentText.toString().trim()); - } else if (qName.equals("Samples")) { + } else if (qName.equals("SampleCount")) { samples = doubleOrNull(); } else if (qName.equals("Sum")) { sum = doubleOrNull(); diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java new file mode 100644 index 0000000000..a8395b55eb --- /dev/null +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java @@ -0,0 +1,168 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudwatch.binders; + +import com.google.common.collect.ImmutableSet; +import com.google.inject.Guice; +import com.google.inject.Injector; +import junit.framework.Assert; +import org.jclouds.cloudwatch.domain.Dimension; +import org.jclouds.cloudwatch.domain.MetricDatum; +import org.jclouds.cloudwatch.domain.PutMetricData; +import org.jclouds.cloudwatch.domain.StatisticSet; +import org.jclouds.cloudwatch.domain.Unit; +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import java.net.URI; +import java.util.Date; + +/** + * Tests behavior of {@link PutMetricDataBinder}. + * + * @author Jeremy Whitlock + */ +@Test(groups = "unit") +public class PutMetricDataBinderTest { + + Injector injector = Guice.createInjector(); + PutMetricDataBinder binder = injector.getInstance(PutMetricDataBinder.class); + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + + public void testMetricWithoutTimestamp() throws Exception { + StatisticSet ss = StatisticSet.builder() + .maximum(4.0) + .minimum(1.0) + .sampleCount(4.0) + .sum(10.0) + .build(); + MetricDatum metricDatum = MetricDatum.builder() + .metricName("TestMetricName") + .statisticSet(ss) + .dimension(new Dimension("TestDimension", "FAKE")) + .unit(Unit.COUNT) + .build(); + PutMetricData pmd = PutMetricData.builder() + .metricDatum(metricDatum) + .namespace("JCLOUDS/Test") + .build(); + + request = binder.bindToRequest(request, pmd); + + Assert.assertEquals(request.getPayload().getRawContent(), + new StringBuilder() + .append("Namespace=JCLOUDS%2FTest") + .append("&MetricData.member.1.Dimensions.member.1.Name=TestDimension") + .append("&MetricData.member.1.Dimensions.member.1.Value=FAKE") + .append("&MetricData.member.1.MetricName=TestMetricName") + .append("&MetricData.member.1.StatisticValues.Maximum=4.0") + .append("&MetricData.member.1.StatisticValues.Minimum=1.0") + .append("&MetricData.member.1.StatisticValues.SampleCount=4.0") + .append("&MetricData.member.1.StatisticValues.Sum=10.0") + .append("&MetricData.member.1.Unit=") + .append(Unit.COUNT.toString()) + .toString()); + } + + public void testMetricWithMultipleDimensions() throws Exception { + MetricDatum metricDatum = MetricDatum.builder() + .metricName("TestMetricName") + .dimension(new Dimension("TestDimension", "FAKE")) + .dimension(new Dimension("TestDimension2", "FAKE2")) + .unit(Unit.COUNT) + .timestamp(new Date(10000000l)) + .value(5.0) + .build(); + PutMetricData pmd = PutMetricData.builder() + .metricDatum(metricDatum) + .namespace("JCLOUDS/Test") + .build(); + + request = binder.bindToRequest(request, pmd); + + Assert.assertEquals(request.getPayload().getRawContent(), + new StringBuilder() + .append("Namespace=JCLOUDS%2FTest") + .append("&MetricData.member.1.Dimensions.member.1.Name=TestDimension") + .append("&MetricData.member.1.Dimensions.member.1.Value=FAKE") + .append("&MetricData.member.1.Dimensions.member.2.Name=TestDimension2") + .append("&MetricData.member.1.Dimensions.member.2.Value=FAKE2") + .append("&MetricData.member.1.MetricName=TestMetricName") + .append("&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z") + .append("&MetricData.member.1.Unit=") + .append(Unit.COUNT.toString()) + .append("&MetricData.member.1.Value=5.0") + .toString()); + } + + public void testMetricWithMultipleDatum() throws Exception { + StatisticSet ss = StatisticSet.builder() + .maximum(4.0) + .minimum(1.0) + .sampleCount(4.0) + .sum(10.0) + .build(); + MetricDatum metricDatum = MetricDatum.builder() + .metricName("TestMetricName") + .statisticSet(ss) + .dimension(new Dimension("TestDimension", "FAKE")) + .dimension(new Dimension("TestDimension2", "FAKE2")) + .unit(Unit.COUNT) + .timestamp(new Date(10000000l)) + .build(); + MetricDatum metricDatum2 = MetricDatum.builder() + .metricName("TestMetricName") + .dimension(new Dimension("TestDimension", "FAKE")) + .unit(Unit.COUNT) + .timestamp(new Date(10000000l)) + .value(5.0) + .build(); + PutMetricData pmd = PutMetricData.builder() + .metricData(ImmutableSet.of(metricDatum, metricDatum2)) + .namespace("JCLOUDS/Test") + .build(); + + request = binder.bindToRequest(request, pmd); + + Assert.assertEquals(request.getPayload().getRawContent(), + new StringBuilder() + .append("Namespace=JCLOUDS%2FTest") + .append("&MetricData.member.1.Dimensions.member.1.Name=TestDimension") + .append("&MetricData.member.1.Dimensions.member.1.Value=FAKE") + .append("&MetricData.member.1.Dimensions.member.2.Name=TestDimension2") + .append("&MetricData.member.1.Dimensions.member.2.Value=FAKE2") + .append("&MetricData.member.1.MetricName=TestMetricName") + .append("&MetricData.member.1.StatisticValues.Maximum=4.0") + .append("&MetricData.member.1.StatisticValues.Minimum=1.0") + .append("&MetricData.member.1.StatisticValues.SampleCount=4.0") + .append("&MetricData.member.1.StatisticValues.Sum=10.0") + .append("&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z") + .append("&MetricData.member.1.Unit=") + .append(Unit.COUNT.toString()) + .append("&MetricData.member.2.Dimensions.member.1.Name=TestDimension") + .append("&MetricData.member.2.Dimensions.member.1.Value=FAKE") + .append("&MetricData.member.2.MetricName=TestMetricName") + .append("&MetricData.member.2.Timestamp=1970-01-01T02%3A46%3A40Z") + .append("&MetricData.member.2.Unit=") + .append(Unit.COUNT.toString()) + .append("&MetricData.member.2.Value=5.0") + .toString()); + } + +} diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java index 18d3301dae..81e1159e81 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java @@ -18,12 +18,7 @@ */ package org.jclouds.cloudwatch.features; -import static org.testng.Assert.assertEquals; - -import java.net.URI; -import java.util.Date; -import java.util.TimeZone; - +import com.google.common.collect.ImmutableMultimap; import org.jclouds.cloudwatch.CloudWatchClient; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.EC2Constants; @@ -39,7 +34,11 @@ import org.jclouds.http.HttpResponse; import org.jclouds.rest.ResourceNotFoundException; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableMultimap; +import java.net.URI; +import java.util.Date; +import java.util.TimeZone; + +import static org.testng.Assert.assertEquals; /** * @author Jeremy Whitlock, Adrian Cole @@ -239,4 +238,8 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { "GetMetricStatisticsResponse{label=CPUUtilization, datapoints=[Datapoint{timestamp=Thu Jan 15 16:00:00 PST 2009, customUnit=null, maximum=null, minimum=null, average=0.17777777777777778, sum=null, samples=9.0, unit=Percent}, Datapoint{timestamp=Thu Jan 15 16:01:00 PST 2009, customUnit=null, maximum=null, minimum=null, average=0.1, sum=null, samples=8.0, unit=Percent}]}"); } + public void testPutMetricData() throws Exception { + + } + } diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java index ad463ae819..de4e4b2f34 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java @@ -18,13 +18,10 @@ */ package org.jclouds.cloudwatch.features; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Calendar; -import java.util.Date; -import java.util.Set; - +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import junit.framework.Assert; import org.jclouds.cloudwatch.domain.Datapoint; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.EC2Constants; @@ -32,14 +29,24 @@ import org.jclouds.cloudwatch.domain.GetMetricStatistics; import org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse; import org.jclouds.cloudwatch.domain.ListMetricsResponse; import org.jclouds.cloudwatch.domain.Metric; +import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.domain.Namespaces; +import org.jclouds.cloudwatch.domain.PutMetricData; +import org.jclouds.cloudwatch.domain.StatisticSet; import org.jclouds.cloudwatch.domain.Statistics; import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.cloudwatch.internal.BaseCloudWatchClientLiveTest; import org.jclouds.cloudwatch.options.ListMetricsOptions; +import org.jclouds.predicates.RetryablePredicate; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableSet; +import java.util.Calendar; +import java.util.Date; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; /** * @author Jeremy Whitlock, Adrian Cole @@ -47,6 +54,100 @@ import com.google.common.collect.ImmutableSet; @Test(groups = "live", testName = "MetricClientLiveTest") public class MetricClientLiveTest extends BaseCloudWatchClientLiveTest { + @Test + protected void testPutMetricData() throws Exception { + String metricName = "TestMetricName" + System.currentTimeMillis(); + String namespace = "JCLOUDS/Test"; + Date metricTimestamp = new Date(); + // CloudWatch rounds metric timestamps down to the closest minute + Date metricTimestampInCloudWatch = + new Date(metricTimestamp.getTime() - (metricTimestamp.getTime() % (60 * 1000))); + StatisticSet ss = StatisticSet.builder() + .maximum(4.0) + .minimum(1.0) + .sampleCount(4.0) + .sum(10.0) + .build(); + MetricDatum metricDatum = MetricDatum.builder() + .metricName(metricName + "_1") + .statisticSet(ss) + .dimension(new Dimension("BaseMetricName", metricName)) + .dimension(new Dimension("TestDimension2", "TEST2")) + .unit(Unit.COUNT) + .timestamp(metricTimestamp) + .build(); + MetricDatum metricDatum2 = MetricDatum.builder() + .metricName(metricName + "_2") + .dimension(new Dimension("BaseMetricName", metricName)) + .unit(Unit.COUNT) + .timestamp(metricTimestamp) + .value(10.0) + .build(); + PutMetricData pmd = PutMetricData.builder() + .namespace(namespace) + .metricDatum(metricDatum) + .metricDatum(metricDatum2) + .build(); + + client().putMetricData(pmd); + + ListMetricsOptions lmo = ListMetricsOptions.builder().namespace(namespace) + .dimension(new Dimension("BaseMetricName", metricName)) + .build(); + boolean success = new RetryablePredicate(new Predicate() { + @Override + public boolean apply(ListMetricsOptions options) { + return Iterables.size(client().listMetrics(options)) == 2; + } + }, 20, 1, TimeUnit.MINUTES).apply(lmo); + + if (!success) { + Assert.fail("Unable to gather the created CloudWatch data within the time (20m) allotted."); + } + + ListMetricsResponse lmr = client().listMetrics(lmo); + Date endTime = new Date(metricTimestampInCloudWatch.getTime() + (60 * 1000)); // Pad a minute just in case + Date startTime = new Date(metricTimestampInCloudWatch.getTime() - (60 * 1000)); // Pad a minute just in case + + for (Metric m : lmr) { + GetMetricStatistics gms = GetMetricStatistics.builder() + .dimensions(m.getDimensions()) + .namespace(namespace) + .metricName(m.getMetricName()) + .endTime(endTime) + .statistic(Statistics.MAXIMUM) + .statistic(Statistics.MINIMUM) + .statistic(Statistics.SAMPLE_COUNT) + .statistic(Statistics.SUM) + .period(60) + .startTime(startTime) + .unit(Unit.COUNT) + .build(); + GetMetricStatisticsResponse gmr = client().getMetricStatistics(gms); + + Assert.assertEquals(1, Iterables.size(gmr)); + + Datapoint datapoint = gmr.iterator().next(); + + Assert.assertEquals(datapoint.getTimestamp(), metricTimestampInCloudWatch); + Assert.assertNull(datapoint.getCustomUnit()); + Assert.assertEquals(Unit.COUNT, datapoint.getUnit()); + Assert.assertNull(datapoint.getAverage()); + + if (m.getDimensions().size() == 1) { + Assert.assertEquals(10.0, datapoint.getMaximum()); + Assert.assertEquals(10.0, datapoint.getMinimum()); + Assert.assertEquals(10.0, datapoint.getSum()); + Assert.assertEquals(1.0, datapoint.getSamples()); + } else { + Assert.assertEquals(4.0, datapoint.getMaximum()); + Assert.assertEquals(1.0, datapoint.getMinimum()); + Assert.assertEquals(10.0, datapoint.getSum()); + Assert.assertEquals(4.0, datapoint.getSamples()); + } + } + } + // TODO: change this test to retrieve pre-seeded custom metrics @Test protected void testGetMetricStatistics() { diff --git a/apis/cloudwatch/src/test/resources/get_metric_statistics.xml b/apis/cloudwatch/src/test/resources/get_metric_statistics.xml index 72ed824700..c72f51899a 100644 --- a/apis/cloudwatch/src/test/resources/get_metric_statistics.xml +++ b/apis/cloudwatch/src/test/resources/get_metric_statistics.xml @@ -4,13 +4,13 @@ 2009-01-16T00:00:00Z Percent - 9.0 + 9.0 0.17777777777777778 2009-01-16T00:01:00Z Percent - 8.0 + 8.0 0.1 From 93381f47a4a226348f72cbd4498e1e1966abfd1d Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Fri, 25 May 2012 22:26:53 -0700 Subject: [PATCH 02/73] Issue 945:Port number is missing in service-managemant-url while invoking the Nova API of openstack --- .../java/org/jclouds/openstack/OpenStackAuthAsyncClient.java | 2 ++ .../org/jclouds/openstack/OpenStackAuthAsyncClientTest.java | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/common/openstack/src/main/java/org/jclouds/openstack/OpenStackAuthAsyncClient.java b/common/openstack/src/main/java/org/jclouds/openstack/OpenStackAuthAsyncClient.java index cd5030cc28..9292bb0946 100644 --- a/common/openstack/src/main/java/org/jclouds/openstack/OpenStackAuthAsyncClient.java +++ b/common/openstack/src/main/java/org/jclouds/openstack/OpenStackAuthAsyncClient.java @@ -28,6 +28,7 @@ import org.jclouds.openstack.domain.AuthenticationResponse; import org.jclouds.openstack.functions.ParseAuthenticationResponseFromHeaders; import org.jclouds.openstack.reference.AuthHeaders; import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.annotations.VirtualHost; import com.google.common.util.concurrent.ListenableFuture; @@ -39,6 +40,7 @@ import com.google.common.util.concurrent.ListenableFuture; * @author Adrian Cole */ @Path("/v{" + Constants.PROPERTY_API_VERSION + "}") +@VirtualHost public interface OpenStackAuthAsyncClient { public static final String VERSION = "1.0"; diff --git a/common/openstack/src/test/java/org/jclouds/openstack/OpenStackAuthAsyncClientTest.java b/common/openstack/src/test/java/org/jclouds/openstack/OpenStackAuthAsyncClientTest.java index 7acee18f31..1779fd979f 100644 --- a/common/openstack/src/test/java/org/jclouds/openstack/OpenStackAuthAsyncClientTest.java +++ b/common/openstack/src/test/java/org/jclouds/openstack/OpenStackAuthAsyncClientTest.java @@ -48,7 +48,7 @@ public class OpenStackAuthAsyncClientTest extends BaseAsyncClientTest Date: Sat, 26 May 2012 00:37:41 -0600 Subject: [PATCH 03/73] Follow up to 9f1ca865e81 that addresses Pull Request 651 feedback. * Removed all validation from the builders * All objects build with builders have @Nullable for getters * Removed PutMetricData object * CloudWatch.putMetricData added as a helper to allow publishing more than 10 metrics at a time --- .../org/jclouds/cloudwatch/CloudWatch.java | 37 +++- .../binders/GetMetricStatisticsBinder.java | 28 ++- ...cDataBinder.java => MetricDataBinder.java} | 29 ++- .../domain/GetMetricStatistics.java | 106 +++-------- .../cloudwatch/domain/MetricDatum.java | 80 +++----- .../cloudwatch/domain/PutMetricData.java | 154 ---------------- .../cloudwatch/domain/StatisticSet.java | 38 +--- .../features/MetricAsyncClient.java | 10 +- .../cloudwatch/features/MetricClient.java | 7 +- .../options/GetMetricStatisticsOptions.java | 44 ++--- .../options/ListMetricsOptions.java | 50 ++--- .../cloudwatch/CloudWatchLiveTest.java | 46 +++++ .../jclouds/cloudwatch/CloudWatchTest.java | 50 ++++- .../binders/MetricDataBinderTest.java | 142 ++++++++++++++ .../binders/PutMetricDataBinderTest.java | 168 ----------------- .../features/MetricClientExpectTest.java | 174 +++++++++--------- .../features/MetricClientLiveTest.java | 8 +- 17 files changed, 499 insertions(+), 672 deletions(-) rename apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/{PutMetricDataBinder.java => MetricDataBinder.java} (80%) delete mode 100644 apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java create mode 100644 apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java delete mode 100644 apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java index f5f2a01830..58f6109d00 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java @@ -19,12 +19,15 @@ package org.jclouds.cloudwatch; import com.google.common.collect.AbstractIterator; +import com.google.common.collect.Sets; import org.jclouds.cloudwatch.domain.ListMetricsResponse; import org.jclouds.cloudwatch.domain.Metric; +import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.features.MetricClient; import org.jclouds.cloudwatch.options.ListMetricsOptions; import java.util.Iterator; +import java.util.Set; /** * Utilities for using CloudWatch. @@ -58,10 +61,10 @@ public class CloudWatch { while (true) { if (iterator == null) { lastOptions = ListMetricsOptions.builder() - .dimensions(lastOptions.getDimensions()) - .metricName(lastOptions.getMetricName()) .namespace(lastOptions.getNamespace()) - .nextToken(response.getNextToken()) + .metricName(lastOptions.getMetricName()) + .dimensions(lastOptions.getDimensions()) + .nextToken(lastOptions.getNextToken()) .build(); response = metricClient.listMetrics(lastOptions); iterator = response.iterator(); @@ -95,4 +98,32 @@ public class CloudWatch { return listMetrics(cloudWatchClient.getMetricClientForRegion(region), options); } + /** + * Pushes metrics to CloudWatch. + * + * @param cloudWatchClient the {@link CloudWatchClient} to use for the request + * @param region the region to put the metrics in + * @param metrics the metrics to publish + * @param namespace the namespace to publish the metrics in + */ + public static void putMetricData(CloudWatchClient cloudWatchClient, String region, Iterable metrics, + String namespace) { + MetricClient metricClient = cloudWatchClient.getMetricClientForRegion(region); + Iterator mIterator = metrics.iterator(); + Set metricsData = Sets.newLinkedHashSet(); + + while (mIterator.hasNext()) { + metricsData.add(mIterator.next()); + if (metricsData.size() == 10 || !mIterator.hasNext()) { + // Make the call + metricClient.putMetricData(metrics, namespace); + + // Reset the list for subsequent call if necessary + if (mIterator.hasNext()) { + metricsData = Sets.newLinkedHashSet(); + } + } + } + } + } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java index bbb69ee3a0..e27aa85627 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java @@ -28,6 +28,8 @@ import org.jclouds.http.HttpRequest; import org.jclouds.http.utils.ModifyRequest; import javax.inject.Inject; +import java.util.HashSet; +import java.util.Set; /** * Binds the metrics request to the http request @@ -50,29 +52,41 @@ public class GetMetricStatisticsBinder implements org.jclouds.rest.Binder { @Override public R bindToRequest(R request, Object payload) { GetMetricStatistics getRequest = GetMetricStatistics.class.cast(payload); + Set dimensions = getRequest.getDimensions() != null ? + getRequest.getDimensions() : + new HashSet(); + Set statistics = getRequest.getStatistics() != null ? + getRequest.getStatistics() : + new HashSet(); int dimensionIndex = 1; int statisticIndex = 1; - ImmutableMultimap.Builder formParameters = ImmutableMultimap.builder(); - for (Dimension dimension : getRequest.getDimensions()) { + + for (Dimension dimension : dimensions) { formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue()); dimensionIndex++; } - formParameters.put("EndTime", dateService.iso8601SecondsDateFormat(getRequest.getEndTime())); + if (getRequest.getEndTime() != null) { + formParameters.put("EndTime", dateService.iso8601SecondsDateFormat(getRequest.getEndTime())); + } formParameters.put("MetricName", getRequest.getMetricName()); formParameters.put("Namespace", getRequest.getNamespace()); formParameters.put("Period", Integer.toString(getRequest.getPeriod())); - formParameters.put("StartTime", dateService.iso8601SecondsDateFormat(getRequest - .getStartTime())); + if (getRequest.getStartTime() != null) { + formParameters.put("StartTime", dateService.iso8601SecondsDateFormat(getRequest + .getStartTime())); + } - for (Statistics statistic : getRequest.getStatistics()) { + for (Statistics statistic : statistics) { formParameters.put("Statistics.member." + statisticIndex, statistic.toString()); statisticIndex++; } - formParameters.put("Unit", getRequest.getUnit().toString()); + if (getRequest.getUnit() != null) { + formParameters.put("Unit", getRequest.getUnit().toString()); + } return ModifyRequest.putFormParams(request, formParameters.build()); } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/PutMetricDataBinder.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java similarity index 80% rename from apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/PutMetricDataBinder.java rename to apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java index 3a13a2bee5..1ddffd48cf 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/PutMetricDataBinder.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java @@ -23,12 +23,14 @@ import com.google.common.collect.ImmutableMultimap; import com.google.inject.Inject; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.MetricDatum; -import org.jclouds.cloudwatch.domain.PutMetricData; import org.jclouds.cloudwatch.domain.StatisticSet; import org.jclouds.date.DateService; import org.jclouds.http.HttpRequest; import org.jclouds.http.utils.ModifyRequest; +import java.util.HashSet; +import java.util.Set; + /** * Binds the metrics request to the http request * @@ -37,12 +39,12 @@ import org.jclouds.http.utils.ModifyRequest; * @author Jeremy Whitlock */ @Beta -public class PutMetricDataBinder implements org.jclouds.rest.Binder { +public class MetricDataBinder implements org.jclouds.rest.Binder { private final DateService dateService; @Inject - protected PutMetricDataBinder(DateService dateService) { + protected MetricDataBinder(DateService dateService) { this.dateService = dateService; } @@ -51,17 +53,20 @@ public class PutMetricDataBinder implements org.jclouds.rest.Binder { */ @Override public R bindToRequest(R request, Object input) { - PutMetricData pmdRequest = PutMetricData.class.cast(input); + Iterable metrics = input != null ? + (Iterable)input : + new HashSet(); ImmutableMultimap.Builder formParameters = ImmutableMultimap.builder(); int metricDatumIndex = 1; - formParameters.put("Namespace", pmdRequest.getNamespace()); - - for (MetricDatum metricDatum : pmdRequest.getMetricData()) { + for (MetricDatum metricDatum : metrics) { int dimensionIndex = 1; StatisticSet statisticSet = metricDatum.getStatisticSet(); + Set dimensions = metricDatum.getDimensions() != null ? + metricDatum.getDimensions() : + new HashSet(); - for (Dimension dimension : metricDatum.getDimensions()) { + for (Dimension dimension : dimensions) { formParameters.put("MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); formParameters.put("MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + @@ -86,10 +91,14 @@ public class PutMetricDataBinder implements org.jclouds.rest.Binder { dateService.iso8601SecondsDateFormat(metricDatum.getTimestamp())); } - formParameters.put("MetricData.member." + metricDatumIndex + ".Unit", String.valueOf(metricDatum.getUnit())); + if (metricDatum.getUnit() != null) { + formParameters.put("MetricData.member." + metricDatumIndex + ".Unit", + String.valueOf(metricDatum.getUnit())); + } if (metricDatum.getValue() != null) { - formParameters.put("MetricData.member." + metricDatumIndex + ".Value", String.valueOf(metricDatum.getValue())); + formParameters.put("MetricData.member." + metricDatumIndex + ".Value", + String.valueOf(metricDatum.getValue())); } metricDatumIndex++; diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java index 9a03ecd59f..17f961dbf0 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java @@ -19,7 +19,6 @@ package org.jclouds.cloudwatch.domain; import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.jclouds.javax.annotation.Nullable; @@ -49,9 +48,8 @@ public class GetMetricStatistics { /** * Private constructor to enforce using {@link Builder}. */ - private GetMetricStatistics(@Nullable Set dimensions, Date endTime, String metricName, - String namespace, int period, Date startTime, Set statistics, - Unit unit) { + private GetMetricStatistics(Set dimensions, Date endTime, String metricName, String namespace, int period, + Date startTime, Set statistics, Unit unit) { this.dimensions = dimensions; this.endTime = endTime; this.metricName = metricName; @@ -73,6 +71,7 @@ public class GetMetricStatistics { /** * return the end time for this request */ + @Nullable public Date getEndTime() { return endTime; } @@ -80,6 +79,7 @@ public class GetMetricStatistics { /** * return the metric name for this request */ + @Nullable public String getMetricName() { return metricName; } @@ -87,6 +87,7 @@ public class GetMetricStatistics { /** * return the namespace for this request */ + @Nullable public String getNamespace() { return namespace; } @@ -94,6 +95,7 @@ public class GetMetricStatistics { /** * return the period for this request */ + @Nullable public int getPeriod() { return period; } @@ -101,6 +103,7 @@ public class GetMetricStatistics { /** * return the start time for this request */ + @Nullable public Date getStartTime() { return startTime; } @@ -108,6 +111,7 @@ public class GetMetricStatistics { /** * return the statistics for this request */ + @Nullable public Set getStatistics() { return statistics; } @@ -115,6 +119,7 @@ public class GetMetricStatistics { /** * return the unit for this request */ + @Nullable public Unit getUnit() { return unit; } @@ -129,13 +134,13 @@ public class GetMetricStatistics { public static class Builder { - private Set dimensions = Sets.newLinkedHashSet(); + private Set dimensions; private Date endTime; private String metricName; private String namespace; private int period; private Date startTime; - private Set statistics = Sets.newLinkedHashSet(); + private Set statistics; private Unit unit; /** @@ -145,142 +150,102 @@ public class GetMetricStatistics { public Builder() {} /** - * A list of dimensions describing qualities of the metric. (Set can be 10 or less items.) + * A list of dimensions describing qualities of the metric. * * @param dimensions the dimensions describing the qualities of the metric * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the passed in dimensions has more than 10 members */ public Builder dimensions(Set dimensions) { - if (dimensions != null) { - Preconditions.checkArgument(dimensions.size() <= 10, "dimensions can have 10 or fewer members."); - this.dimensions = dimensions; - } + this.dimensions = dimensions; return this; } /** - * A dimension describing qualities of the metric. (Can be called multiple times up to a maximum of 10 times.) + * A dimension describing qualities of the metric. * * @param dimension the dimension describing the qualities of the metric * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the number of dimensions would be greater than 10 after adding */ public Builder dimension(Dimension dimension) { - if (dimension != null) { - Preconditions.checkArgument(dimensions.size() < 10, "dimension member maximum count of 10 exceeded."); - this.dimensions.add(dimension); + if (dimensions == null) { + dimensions = Sets.newLinkedHashSet(); } + this.dimensions.add(dimension); return this; } /** * The time stamp to use for determining the last datapoint to return. The value specified is exclusive so - * results will include datapoints up to the time stamp specified. (Should be called once. Subsequent calls - * will overwrite the previous value.) + * results will include datapoints up to the time stamp specified. * * @param endTime the timestamp to use for determining the last datapoint to return * * @return this {@code Builder} object - * - * @throws NullPointerException if endTime is null */ public Builder endTime(Date endTime) { - Preconditions.checkNotNull(endTime, "endTime cannot be null."); this.endTime = endTime; return this; } /** - * The name of the metric. (Should be called once. Subsequent calls will overwrite the previous value.) + * The name of the metric. * * @param metricName the metric name to filter against * * @return this {@code Builder} object - * - * @throws NullPointerException if metricName is null - * @throws IllegalArgumentException if metricName is empty */ public Builder metricName(String metricName) { - Preconditions.checkNotNull(metricName, "metricName cannot be null."); - Preconditions.checkArgument(metricName.length() > 1, "metricName must not be empty."); this.metricName = metricName; return this; } /** - * The namespace of the metric. (Should be called once. Subsequent calls will overwrite the previous value. - * See {@link org.jclouds.cloudwatch.domain.Namespaces} for the known list of namespaces.) + * The namespace of the metric. * * @param namespace the namespace to filter against * * @return this {@code Builder} object - * - * @throws NullPointerException if namespace is null - * @throws IllegalArgumentException if namespace is empty */ public Builder namespace(String namespace) { - Preconditions.checkNotNull(namespace, "namespace cannot be null."); - Preconditions.checkArgument(namespace.length() > 1, "namespace must not be empty."); this.namespace = namespace; return this; } /** - * The granularity, in seconds, of the returned datapoints. Period must be at least 60 seconds and must be a - * multiple of 60. The default value is 60. (Should be called once. Subsequent calls will overwrite the - * previous value.) + * The granularity, in seconds, of the returned datapoints. * * @param period the granularity, in seconds, of the returned datapoints * * @return this {@code Builder} object - * - * @throws NullPointerException if period is null - * @throws IllegalArgumentException if period is less than 60 or not a multiple of 60 */ public Builder period(int period) { - Preconditions.checkNotNull(period, "period cannot be null."); - Preconditions.checkArgument(period >= 60 && period % 60 == 0, "period must be greater than 60 and as a " + - "multiple of 60."); this.period = period; return this; } /** * The time stamp to use for determining the first datapoint to return. The value specified is inclusive so - * results include datapoints with the time stamp specified. (Should be called once. Subsequent calls will - * overwrite the previous value.) + * results include datapoints with the time stamp specified. * * @param startTime The time stamp to use for determining the first datapoint to return * * @return this {@code Builder} object - * - * @throws NullPointerException if startTime is null */ public Builder startTime(Date startTime) { - Preconditions.checkNotNull(startTime, "startTime cannot be null."); this.startTime = startTime; return this; } /** - * The metric statistics to return. (Should be called once. Subsequent calls will overwrite the previous - * value.) + * The metric statistics to return. * * @param statistics the metric statistics to return. * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the number of statistics is greater than 5 - * @throws NullPointerException if statistics is null */ public Builder statistics(Set statistics) { - Preconditions.checkNotNull(statistics, "statistics cannot be null."); - Preconditions.checkArgument(statistics.size() <= 5, "statistics can have 5 or fewer members."); this.statistics = statistics; return this; } @@ -291,28 +256,23 @@ public class GetMetricStatistics { * @param statistic the metric statistic to return * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the number of statistics would be greater than 5 after adding - * @throws NullPointerException if statistic is null */ public Builder statistic(Statistics statistic) { - Preconditions.checkNotNull(statistic, "statistic cannot be null."); - Preconditions.checkArgument(statistics.size() < 5, "statistics member maximum count of 5 exceeded."); + if (statistics == null) { + statistics = Sets.newLinkedHashSet(); + } this.statistics.add(statistic); return this; } /** - * The unit for the metric. (Should be called once. Subsequent calls will overwrite the previous value.) + * The unit for the metric. * * @param unit the unit for the metric * * @return this {@code Builder} object - * - * @throws NullPointerException if unit is null */ public Builder unit(Unit unit) { - Preconditions.checkNotNull(unit, "unit cannot be null."); this.unit = unit; return this; } @@ -320,20 +280,8 @@ public class GetMetricStatistics { /** * Returns a newly-created {@code GetMetricStatisticsOptionsV2} based on the contents of * the {@code Builder}. - * - * @throws NullPointerException if any of the required fields are null - * @throws IllegalArgumentException if any of the provided fields don't meet required criteria */ public GetMetricStatistics build() { - Preconditions.checkNotNull(endTime, "endTime cannot be null."); - Preconditions.checkNotNull(metricName, "metricName cannot be null."); - Preconditions.checkNotNull(namespace, "namespace cannot be null."); - Preconditions.checkNotNull(period, "period cannot be null."); - Preconditions.checkNotNull(startTime, "startTime cannot be null."); - Preconditions.checkNotNull(statistics, "statistics cannot be null."); - Preconditions.checkNotNull(unit, "unit cannot be null."); - Preconditions.checkArgument(statistics.size() >= 1, "statistics must have at least one member"); - return new GetMetricStatistics(dimensions, endTime, metricName,namespace, period, startTime, statistics, unit); } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java index 89d92eb30f..6f0e36cc30 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java @@ -18,7 +18,6 @@ */ package org.jclouds.cloudwatch.domain; -import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.jclouds.javax.annotation.Nullable; @@ -42,14 +41,9 @@ public class MetricDatum { /** * Private constructor to enforce using {@link Builder}. */ - private MetricDatum(@Nullable Set dimensions, String metricName, StatisticSet statisticSet, - @Nullable Date timestamp, Unit unit, Double value) { - // Default to an empty set - if (dimensions == null) { - this.dimensions = Sets.newLinkedHashSet(); - } else { - this.dimensions = dimensions; - } + private MetricDatum(Set dimensions, String metricName, StatisticSet statisticSet, Date timestamp, + Unit unit, Double value) { + this.dimensions = dimensions; this.metricName = metricName; this.statisticSet = statisticSet; this.timestamp = timestamp; @@ -68,14 +62,15 @@ public class MetricDatum { /** * return the metric name for the metric. */ + @Nullable public String getMetricName() { return metricName; } /** - * return the object describing the set of statistical values for the metric (This and value are mutually - * exclusive.) + * return the object describing the set of statistical values for the metric */ + @Nullable public StatisticSet getStatisticSet() { return statisticSet; } @@ -91,14 +86,15 @@ public class MetricDatum { /** * return Standard unit used for the metric. */ + @Nullable public Unit getUnit() { return unit; } /** - * return the actual value of the metric (This and statisticSet are mutually exclusive.) - * + * return the actual value of the metric */ + @Nullable public Double getValue() { return value; } @@ -113,7 +109,7 @@ public class MetricDatum { public static class Builder { - private Set dimensions = Sets.newLinkedHashSet(); + private Set dimensions; private String metricName; private StatisticSet statisticSet; private Date timestamp; @@ -127,76 +123,59 @@ public class MetricDatum { public Builder() {} /** - * A list of dimensions describing qualities of the metric. (Set can be 10 or less items.) + * A list of dimensions describing qualities of the metric. * * @param dimensions the dimensions describing the qualities of the metric * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the passed in dimensions has more than 10 members */ public Builder dimensions(Set dimensions) { - if (dimensions != null) { - Preconditions.checkArgument(dimensions.size() <= 10, "dimensions can have 10 or fewer members."); - this.dimensions = dimensions; - } + this.dimensions = dimensions; return this; } /** - * A dimension describing qualities of the metric. (Can be called multiple times up to a maximum of 10 times.) + * A dimension describing qualities of the metric. * * @param dimension the dimension describing the qualities of the metric * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the number of dimensions would be greater than 10 after adding */ public Builder dimension(Dimension dimension) { - if (dimension != null) { - Preconditions.checkArgument(dimensions.size() < 10, "dimension member maximum count of 10 exceeded."); - this.dimensions.add(dimension); + if (dimensions == null) { + dimensions = Sets.newLinkedHashSet(); } + this.dimensions.add(dimension); return this; } /** - * The name of the metric. (Should be called once. Subsequent calls will overwrite the previous value.) + * The name of the metric. * * @param metricName the metric name * * @return this {@code Builder} object - * - * @throws NullPointerException if metricName is null - * @throws IllegalArgumentException if metricName is empty */ public Builder metricName(String metricName) { - Preconditions.checkNotNull(metricName, "metricName cannot be null."); - Preconditions.checkArgument(metricName.length() > 1, "metricName must not be empty."); this.metricName = metricName; return this; } /** - * The object describing the set of statistical values describing the metric. (Should be called once. Subsequent - * calls will overwrite the previous value. Also, this cannot be set once you've set the value.) + * The object describing the set of statistical values describing the metric. * * @param statisticSet the object describing the set of statistical values for the metric * * @return this {@code Builder} object - * - * @throws NullPointerException if statisticSet is null - * @throws IllegalArgumentException if value has already been set */ public Builder statisticSet(StatisticSet statisticSet) { - Preconditions.checkArgument(value == null, "value and statisticSet are mutually exclusive"); this.statisticSet = statisticSet; return this; } /** * The time stamp used for the metric. If not specified, the default value is set to the time the metric data was - * received. (Should be called once. Subsequent calls will overwrite the previous value.) + * received. * * @param timestamp the time stamp used for the metric * @@ -208,50 +187,33 @@ public class MetricDatum { } /** - * The unit for the metric. (Should be called once. Subsequent calls will overwrite the previous value.) + * The unit for the metric. * * @param unit the unit for the metric * * @return this {@code Builder} object - * - * @throws NullPointerException if unit is null */ public Builder unit(Unit unit) { - Preconditions.checkNotNull(unit, "unit cannot be null."); this.unit = unit; return this; } /** - * The value for the metric. (Should be called once. Subsequent calls will overwrite the previous value. Also, - * this cannot be set once you've set the statisticValue.) + * The value for the metric. * * @param value the value for the metric * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if statisticSet has already been set */ public Builder value(Double value) { - Preconditions.checkArgument(statisticSet == null, "statisticSet and value are mutually exclusive"); this.value = value; return this; } /** * Returns a newly-created {@code MetricDatum} based on the contents of the {@code Builder}. - * - * @throws NullPointerException if any of the required fields are null - * @throws IllegalArgumentException if any of the provided fields don't meet required criteria */ public MetricDatum build() { - Preconditions.checkNotNull(metricName, "metricName cannot be null."); - Preconditions.checkNotNull(unit, "unit cannot be null."); - Preconditions.checkArgument(metricName.length() > 1 && metricName.length() <= 255, - "metricName cannot be empty and must be 255 characters or less."); - Preconditions.checkArgument(statisticSet != null || value != null, - "statisticSet or value must be set"); - return new MetricDatum(dimensions, metricName, statisticSet, timestamp, unit, value); } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java deleted file mode 100644 index 8529fdee19..0000000000 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/PutMetricData.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.cloudwatch.domain; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.Sets; - -import java.util.Set; - -/** - * Options use to get statistics for the specified metric. - * - * @see - * - * @author Jeremy Whitlock - */ -@Beta -public class PutMetricData { - - private final String namespace; - private final Set metricData; - - /** - * Private constructor to enforce using {@link Builder}. - */ - private PutMetricData(String namespace, Set metricData) { - this.namespace = namespace; - this.metricData = metricData; - } - - /** - * return the namespace for this request - */ - public String getNamespace() { - return namespace; - } - - /** - * return the metric data for this request - */ - public Set getMetricData() { - return metricData; - } - - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - - private String namespace; - private Set metricData = Sets.newLinkedHashSet(); - - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link org.jclouds.cloudwatch.domain.PutMetricData#builder}. - */ - public Builder() {} - - /** - * The namespace for the metric data. (Should be called once. Subsequent calls will overwrite the previous - * value.) This value cannot start with "AWS/" as that namespace prefix is reserved for AWS CloudWatch - * metrics. - * - * @param namespace the namespace for the metric data - * - * @return this {@code Builder} object - * - * @throws NullPointerException if namespace is null - * @throws IllegalArgumentException if namespace is empty or starts with "AWS/" - */ - public Builder namespace(String namespace) { - Preconditions.checkNotNull(namespace, "namespace cannot be null."); - Preconditions.checkArgument(namespace.length() > 1, "namespace must not be empty."); - Preconditions.checkArgument(!namespace.startsWith("AWS/"), "namespace cannot start with 'AWS/' as it's " + - "reserved for AWS CloudWatch metrics."); - this.namespace = namespace; - return this; - } - - /** - * A metric to either create or aggregate to an existing metric. (Can be called multiple times up to a maximum of - * 10 times.) - * - * @param metricDatum the representation of a metric to either create a new metric or add new values to be - * aggregated into an existing metric - * - * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the number of dimensions would be greater than 10 after adding - */ - public Builder metricDatum(MetricDatum metricDatum) { - if (metricDatum != null) { - Preconditions.checkArgument(metricData.size() < 10, "metric data member maximum count of 10 exceeded."); - this.metricData.add(metricDatum); - } - return this; - } - - /** - * A list of data describing the metric. (Set can be 10 or less items.) - * - * @param metricData the list of data describing the data - * - * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the passed in data has more than 10 members - */ - public Builder metricData(Set metricData) { - if (metricData != null) { - Preconditions.checkArgument(metricData.size() <= 10, "metric data can have 10 or fewer members."); - this.metricData = metricData; - } - return this; - } - - /** - * Returns a newly-created {@code PutMetricData} based on the contents of the {@code Builder}. - * - * @throws NullPointerException if any of the required fields are null - * @throws IllegalArgumentException if any of the provided fields don't meet required criteria - */ - public PutMetricData build() { - Preconditions.checkNotNull(namespace, "namespace cannot be null."); - Preconditions.checkNotNull(metricData, "metricData cannot be null."); - Preconditions.checkArgument(metricData.size() > 0, "metricData must have at least one member."); - - return new PutMetricData(namespace, metricData); - } - - } - -} diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java index 28830f5d4e..82674dbf87 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java @@ -18,7 +18,6 @@ */ package org.jclouds.cloudwatch.domain; -import com.google.common.base.Preconditions; import org.jclouds.javax.annotation.Nullable; /** @@ -33,8 +32,7 @@ public class StatisticSet { private final Double sampleCount; private final Double sum; - public StatisticSet(@Nullable Double maximum, @Nullable Double minimum, @Nullable Double sampleCount, - @Nullable Double sum) { + public StatisticSet(Double maximum, Double minimum, Double sampleCount, Double sum) { this.maximum = maximum; this.minimum = minimum; this.sampleCount = sampleCount; @@ -44,6 +42,7 @@ public class StatisticSet { /** * return the maximum value of the sample set */ + @Nullable public Double getMaximum() { return maximum; } @@ -51,6 +50,7 @@ public class StatisticSet { /** * return the minimum value of the sample set */ + @Nullable public Double getMinimum() { return minimum; } @@ -58,6 +58,7 @@ public class StatisticSet { /** * return the number of samples used for the statistic set */ + @Nullable public Double getSampleCount() { return sampleCount; } @@ -65,6 +66,7 @@ public class StatisticSet { /** * return the sum of values for the sample set */ + @Nullable public Double getSum() { return sum; } @@ -91,79 +93,57 @@ public class StatisticSet { public Builder() {} /** - * The maximum value of the sample set. (Should be called once. Subsequent calls will overwrite the previous - * value.) + * The maximum value of the sample set. * * @param maximum the maximum value of the sample set * * @return this {@code Builder} object - * - * @throws NullPointerException if maximum is null */ public Builder maximum(Double maximum) { - Preconditions.checkNotNull(maximum, "maximum cannot be null."); this.maximum = maximum; return this; } /** - * The minimum value of the sample set. (Should be called once. Subsequent calls will overwrite the previous - * value.) + * The minimum value of the sample set. * * @param minimum the minimum value of the sample set * * @return this {@code Builder} object - * - * @throws NullPointerException if minimum is null */ public Builder minimum(Double minimum) { - Preconditions.checkNotNull(minimum, "minimum cannot be null."); this.minimum = minimum; return this; } /** - * The the number of samples used for the statistic set. (Should be called once. Subsequent calls will overwrite - * the previous value.) + * The the number of samples used for the statistic set. * * @param sampleCount the number of samples used for the statistic set * * @return this {@code Builder} object - * - * @throws NullPointerException if sampleCount is null */ public Builder sampleCount(Double sampleCount) { - Preconditions.checkNotNull(sampleCount, "sampleCount cannot be null."); this.sampleCount = sampleCount; return this; } /** - * The sum of values for the sample set. (Should be called once. Subsequent calls will overwrite the previous - * value.) + * The sum of values for the sample set. * * @param sum the sum of values for the sample set * * @return this {@code Builder} object - * - * @throws NullPointerException if sum is null */ public Builder sum(Double sum) { - Preconditions.checkNotNull(sum, "sum cannot be null."); this.sum = sum; return this; } /** * Returns a newly-created {@code StatisticSet} based on the contents of the {@code Builder}. - * - * @throws NullPointerException if any of the required fields are null */ public StatisticSet build() { - Preconditions.checkNotNull(maximum, "maximum cannot be null."); - Preconditions.checkNotNull(minimum, "minimum cannot be null."); - Preconditions.checkNotNull(sampleCount, "sampleCount cannot be null."); - Preconditions.checkNotNull(sum, "sum cannot be null."); return new StatisticSet(maximum, minimum, sampleCount, sum); } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java index 32f3858bf6..951d731c1b 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncClient.java @@ -21,11 +21,11 @@ package org.jclouds.cloudwatch.features; import com.google.common.util.concurrent.ListenableFuture; import org.jclouds.aws.filters.FormSigner; import org.jclouds.cloudwatch.binders.GetMetricStatisticsBinder; -import org.jclouds.cloudwatch.binders.PutMetricDataBinder; +import org.jclouds.cloudwatch.binders.MetricDataBinder; import org.jclouds.cloudwatch.domain.GetMetricStatistics; import org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse; import org.jclouds.cloudwatch.domain.ListMetricsResponse; -import org.jclouds.cloudwatch.domain.PutMetricData; +import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.options.GetMetricStatisticsOptions; import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.jclouds.cloudwatch.xml.GetMetricStatisticsResponseHandlerV2; @@ -36,6 +36,7 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; +import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; @@ -90,11 +91,12 @@ public interface MetricAsyncClient { GetMetricStatisticsOptions options); /** - * @see MetricClient#putMetricData(org.jclouds.cloudwatch.domain.PutMetricData) + * @see MetricClient#putMetricData(Iterable, String) */ @POST @Path("/") @FormParams(keys = "Action", values = "PutMetricData") - ListenableFuture putMetricData(@BinderParam(PutMetricDataBinder.class) PutMetricData putMetricData); + ListenableFuture putMetricData(@BinderParam(MetricDataBinder.class) Iterable metrics, + @FormParam("Namespace") String namespace); } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java index f70eaa746d..fe3477deec 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricClient.java @@ -21,7 +21,7 @@ package org.jclouds.cloudwatch.features; import org.jclouds.cloudwatch.domain.GetMetricStatistics; import org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse; import org.jclouds.cloudwatch.domain.ListMetricsResponse; -import org.jclouds.cloudwatch.domain.PutMetricData; +import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.options.GetMetricStatisticsOptions; import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.jclouds.concurrent.Timeout; @@ -72,8 +72,9 @@ public interface MetricClient { /** * Publishes metric data points to Amazon CloudWatch. * - * @param putMetricData object describing the metric data + * @param metrics the metrics to publish + * @param namespace the namespace to publish the metrics to */ - void putMetricData(PutMetricData putMetricData); + void putMetricData(Iterable metrics, String namespace); } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/GetMetricStatisticsOptions.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/GetMetricStatisticsOptions.java index b100f6e240..a4fbf27c95 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/GetMetricStatisticsOptions.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/GetMetricStatisticsOptions.java @@ -18,19 +18,16 @@ */ package org.jclouds.cloudwatch.options; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Set; - +import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; import org.jclouds.aws.util.AWSUtils; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.http.options.BaseHttpRequestOptions; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; +import java.util.Set; + +import static com.google.common.base.Preconditions.checkNotNull; /** * Options used to control metric statistics are returned @@ -42,39 +39,32 @@ import com.google.common.collect.Sets; */ public class GetMetricStatisticsOptions extends BaseHttpRequestOptions { - private Set dimensions = Sets.newLinkedHashSet(); + private Set dimensions; /** - * A dimension describing qualities of the metric. (Can be called multiple times up to a maximum of 10 times.) + * A dimension describing qualities of the metric. * * @param dimension the dimension describing the qualities of the metric * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the number of dimensions would be greater than 10 after adding */ public GetMetricStatisticsOptions dimension(Dimension dimension) { - if (dimension != null) { - Preconditions.checkArgument(dimensions.size() < 10, "dimension member maximum count of 10 exceeded."); - this.dimensions.add(dimension); + if (dimensions == null) { + dimensions = Sets.newLinkedHashSet(); } + this.dimensions.add(dimension); return this; } /** - * A list of dimensions describing qualities of the metric. (Set can be 10 or less items.) + * A list of dimensions describing qualities of the metric. * * @param dimensions the dimensions describing the qualities of the metric * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if this is invoked more than 10 times */ public GetMetricStatisticsOptions dimensions(Set dimensions) { - if (dimensions != null) { - Preconditions.checkArgument(dimensions.size() <= 10, "dimensions can have 10 or fewer members."); - this.dimensions = ImmutableSet.copyOf(dimensions); - } + this.dimensions = dimensions; return this; } @@ -137,10 +127,12 @@ public class GetMetricStatisticsOptions extends BaseHttpRequestOptions { public Multimap buildFormParameters() { Multimap formParameters = super.buildFormParameters(); int dimensionIndex = 1; - for (Dimension dimension : dimensions) { - formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); - formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue()); - dimensionIndex++; + if (dimensions != null) { + for (Dimension dimension : dimensions) { + formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); + formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue()); + dimensionIndex++; + } } return formParameters; } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListMetricsOptions.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListMetricsOptions.java index ee4b024410..a86f64dc88 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListMetricsOptions.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListMetricsOptions.java @@ -18,7 +18,6 @@ */ package org.jclouds.cloudwatch.options; -import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.http.options.BaseHttpRequestOptions; @@ -105,72 +104,50 @@ public class ListMetricsOptions extends BaseHttpRequestOptions { public Builder() {} /** - * The namespace to filter against. (Should be called once. Subsequent calls will overwrite the previous value. - * See {@link org.jclouds.cloudwatch.domain.Namespaces} for the known list of namespaces.) + * The namespace to filter against. * * @param namespace the namespace to filter against * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if namespace is empty */ public Builder namespace(String namespace) { - if (namespace != null) { - Preconditions.checkArgument(namespace.length() > 1, "namespace must not be empty."); - } this.namespace = namespace; return this; } /** - * The name of the metric to filter against. (Should be called once. Subsequent calls will overwrite the - * previous value.) + * The name of the metric to filter against. * * @param metricName the metric name to filter against * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if metricName is empty */ public Builder metricName(String metricName) { - if (metricName != null) { - Preconditions.checkArgument(metricName.length() > 1, "metricName must not be empty."); - } this.metricName = metricName; return this; } /** - * A list of dimensions to filter against. (Set can be 10 or less items.) + * A list of dimensions to filter against. * * @param dimensions the dimensions to filter against * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if the number of dimensions would be greater than 10 after adding */ public Builder dimensions(Set dimensions) { - if (dimensions != null) { - Preconditions.checkArgument(dimensions.size() <= 10, "dimensions can have 10 or fewer members."); - this.dimensions = dimensions; - } + this.dimensions = dimensions; return this; } /** - * A dimension to filter the available metrics by. (Can be called multiple times up to a maximum of 10 times.) + * A dimension to filter the available metrics by. * * @param dimension a dimension to filter the returned metrics by * * @return this {@code Builder} object - * - * @throws IllegalArgumentException if this is invoked more than 10 times */ public Builder dimension(Dimension dimension) { - if (dimension != null) { - Preconditions.checkArgument(dimensions.size() < 10, "dimension member maximum count of 10 exceeded."); - this.dimensions.add(dimension); - } + this.dimensions.add(dimension); return this; } @@ -194,20 +171,25 @@ public class ListMetricsOptions extends BaseHttpRequestOptions { ListMetricsOptions lmo = new ListMetricsOptions(namespace, metricName, dimensions, nextToken); int dimensionIndex = 1; + // If namespace isn't specified, don't include it if (namespace != null) { lmo.formParameters.put("Namespace", namespace); } - + // If metricName isn't specified, don't include it if (metricName != null) { lmo.formParameters.put("MetricName", metricName); } - for (Dimension dimension : dimensions) { - lmo.formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); - lmo.formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue()); - dimensionIndex++; + // If dimensions isn't specified, don't include it + if (dimensions != null) { + for (Dimension dimension : dimensions) { + lmo.formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); + lmo.formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue()); + dimensionIndex++; + } } + // If nextToken isn't specified, don't include it if (nextToken != null) { lmo.formParameters.put("NextToken", nextToken); } diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchLiveTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchLiveTest.java index f8115fc45d..cd635759cc 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchLiveTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchLiveTest.java @@ -18,13 +18,25 @@ */ package org.jclouds.cloudwatch; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; import com.google.common.reflect.TypeToken; +import junit.framework.Assert; import org.jclouds.apis.BaseContextLiveTest; +import org.jclouds.cloudwatch.domain.Dimension; +import org.jclouds.cloudwatch.domain.MetricDatum; +import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.cloudwatch.options.ListMetricsOptions; +import org.jclouds.predicates.RetryablePredicate; import org.jclouds.rest.RestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.Date; +import java.util.Set; +import java.util.concurrent.TimeUnit; + import static com.google.common.base.Preconditions.checkArgument; /** @@ -58,4 +70,38 @@ public class CloudWatchLiveTest extends BaseContextLiveTest metrics = Sets.newLinkedHashSet(); + + for (int i = 0; i < 11; i++) { + metrics.add(MetricDatum.builder() + .metricName(metricName + "_" + i) + .dimension(new Dimension("BaseMetricName", metricName)) + .unit(Unit.COUNT) + .timestamp(metricTimestamp) + .value((double) i) + .build()); + } + + CloudWatch.putMetricData(client, null, metrics, namespace); + + ListMetricsOptions lmo = ListMetricsOptions.builder().namespace(namespace) + .dimension(new Dimension("BaseMetricName", metricName)) + .build(); + boolean success = new RetryablePredicate(new Predicate() { + @Override + public boolean apply(ListMetricsOptions options) { + return Iterables.size(CloudWatch.listMetrics(client, null, options)) == 11; + } + }, 20, 1, TimeUnit.MINUTES).apply(lmo); + + if (!success) { + Assert.fail("Unable to gather the created CloudWatch data within the time (20m) allotted."); + } + } + } diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java index ac34d5e09f..19102f982d 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java @@ -18,20 +18,24 @@ */ package org.jclouds.cloudwatch; -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; - +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; import org.easymock.EasyMock; import org.jclouds.cloudwatch.domain.ListMetricsResponse; import org.jclouds.cloudwatch.domain.Metric; +import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.features.MetricClient; import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.testng.Assert; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; +import java.util.Set; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; /** * Tests behavior of {@code CloudWatch}. @@ -97,4 +101,38 @@ public class CloudWatchTest { Assert.assertEquals(2, Iterables.size(CloudWatch.listMetrics(client, "", options))); } + /** + * Tests {@link CloudWatch#putMetricData(CloudWatchClient, String, Iterable, String)} where the set of metrics is + * greater than 10. + * + * @throws Exception if anything goes wrong + */ + @Test + public void testPutMetricData() throws Exception { + CloudWatchClient client = createMock(CloudWatchClient.class); + MetricClient metricClient = createMock(MetricClient.class); + Set metrics = Sets.newLinkedHashSet(); + String namespace = "JCLOUDS/Test"; + + for (int i = 0; i < 11; i++) { + metrics.add(MetricDatum.builder().build()); + } + + // Using EasyMock.eq("") because EasyMock makes it impossible to pass null as a String value here + expect(client.getMetricClientForRegion(EasyMock.eq(""))) + .andReturn(metricClient) + .atLeastOnce(); + + + metricClient.putMetricData(metrics, namespace); + + expectLastCall().times(2); + + EasyMock.replay(client, metricClient); + + CloudWatch.putMetricData(client, "", metrics, namespace); + + EasyMock.verify(metricClient); + } + } diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java new file mode 100644 index 0000000000..0b79702422 --- /dev/null +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java @@ -0,0 +1,142 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudwatch.binders; + +import com.google.common.collect.ImmutableSet; +import com.google.inject.Guice; +import com.google.inject.Injector; +import junit.framework.Assert; +import org.jclouds.cloudwatch.domain.Dimension; +import org.jclouds.cloudwatch.domain.MetricDatum; +import org.jclouds.cloudwatch.domain.StatisticSet; +import org.jclouds.cloudwatch.domain.Unit; +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import java.net.URI; +import java.util.Date; + +/** + * Tests behavior of {@link MetricDataBinder}. + * + * @author Jeremy Whitlock + */ +@Test(groups = "unit") +public class MetricDataBinderTest { + + Injector injector = Guice.createInjector(); + MetricDataBinder binder = injector.getInstance(MetricDataBinder.class); + HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + + public void testMetricWithoutTimestamp() throws Exception { + StatisticSet ss = StatisticSet.builder() + .maximum(4.0) + .minimum(1.0) + .sampleCount(4.0) + .sum(10.0) + .build(); + MetricDatum metricDatum = MetricDatum.builder() + .metricName("TestMetricName") + .statisticSet(ss) + .dimension(new Dimension("TestDimension", "FAKE")) + .unit(Unit.COUNT) + .build(); + + request = binder.bindToRequest(request, ImmutableSet.of(metricDatum)); + + Assert.assertEquals(request.getPayload().getRawContent(), + "MetricData.member.1.Dimensions.member.1.Name=TestDimension" + + "&MetricData.member.1.Dimensions.member.1.Value=FAKE" + + "&MetricData.member.1.MetricName=TestMetricName" + + "&MetricData.member.1.StatisticValues.Maximum=4.0" + + "&MetricData.member.1.StatisticValues.Minimum=1.0" + + "&MetricData.member.1.StatisticValues.SampleCount=4.0" + + "&MetricData.member.1.StatisticValues.Sum=10.0" + + "&MetricData.member.1.Unit=" + Unit.COUNT.toString()); + } + + public void testMetricWithMultipleDimensions() throws Exception { + MetricDatum metricDatum = MetricDatum.builder() + .metricName("TestMetricName") + .dimension(new Dimension("TestDimension", "FAKE")) + .dimension(new Dimension("TestDimension2", "FAKE2")) + .unit(Unit.COUNT) + .timestamp(new Date(10000000l)) + .value(5.0) + .build(); + + request = binder.bindToRequest(request, ImmutableSet.of(metricDatum)); + + Assert.assertEquals(request.getPayload().getRawContent(), + "MetricData.member.1.Dimensions.member.1.Name=TestDimension" + + "&MetricData.member.1.Dimensions.member.1.Value=FAKE" + + "&MetricData.member.1.Dimensions.member.2.Name=TestDimension2" + + "&MetricData.member.1.Dimensions.member.2.Value=FAKE2" + + "&MetricData.member.1.MetricName=TestMetricName" + + "&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z" + + "&MetricData.member.1.Unit=" + Unit.COUNT.toString() + + "&MetricData.member.1.Value=5.0"); + } + + public void testMetricWithMultipleDatum() throws Exception { + StatisticSet ss = StatisticSet.builder() + .maximum(4.0) + .minimum(1.0) + .sampleCount(4.0) + .sum(10.0) + .build(); + MetricDatum metricDatum = MetricDatum.builder() + .metricName("TestMetricName") + .statisticSet(ss) + .dimension(new Dimension("TestDimension", "FAKE")) + .dimension(new Dimension("TestDimension2", "FAKE2")) + .unit(Unit.COUNT) + .timestamp(new Date(10000000l)) + .build(); + MetricDatum metricDatum2 = MetricDatum.builder() + .metricName("TestMetricName") + .dimension(new Dimension("TestDimension", "FAKE")) + .unit(Unit.COUNT) + .timestamp(new Date(10000000l)) + .value(5.0) + .build(); + + request = binder.bindToRequest(request, ImmutableSet.of(metricDatum, metricDatum2)); + + Assert.assertEquals(request.getPayload().getRawContent(), + "MetricData.member.1.Dimensions.member.1.Name=TestDimension" + + "&MetricData.member.1.Dimensions.member.1.Value=FAKE" + + "&MetricData.member.1.Dimensions.member.2.Name=TestDimension2" + + "&MetricData.member.1.Dimensions.member.2.Value=FAKE2" + + "&MetricData.member.1.MetricName=TestMetricName" + + "&MetricData.member.1.StatisticValues.Maximum=4.0" + + "&MetricData.member.1.StatisticValues.Minimum=1.0" + + "&MetricData.member.1.StatisticValues.SampleCount=4.0" + + "&MetricData.member.1.StatisticValues.Sum=10.0" + + "&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z" + + "&MetricData.member.1.Unit=" + Unit.COUNT.toString() + + "&MetricData.member.2.Dimensions.member.1.Name=TestDimension" + + "&MetricData.member.2.Dimensions.member.1.Value=FAKE" + + "&MetricData.member.2.MetricName=TestMetricName" + + "&MetricData.member.2.Timestamp=1970-01-01T02%3A46%3A40Z" + + "&MetricData.member.2.Unit=" + Unit.COUNT.toString() + + "&MetricData.member.2.Value=5.0"); + } + +} diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java deleted file mode 100644 index a8395b55eb..0000000000 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/PutMetricDataBinderTest.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.cloudwatch.binders; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; -import junit.framework.Assert; -import org.jclouds.cloudwatch.domain.Dimension; -import org.jclouds.cloudwatch.domain.MetricDatum; -import org.jclouds.cloudwatch.domain.PutMetricData; -import org.jclouds.cloudwatch.domain.StatisticSet; -import org.jclouds.cloudwatch.domain.Unit; -import org.jclouds.http.HttpRequest; -import org.testng.annotations.Test; - -import java.net.URI; -import java.util.Date; - -/** - * Tests behavior of {@link PutMetricDataBinder}. - * - * @author Jeremy Whitlock - */ -@Test(groups = "unit") -public class PutMetricDataBinderTest { - - Injector injector = Guice.createInjector(); - PutMetricDataBinder binder = injector.getInstance(PutMetricDataBinder.class); - HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); - - public void testMetricWithoutTimestamp() throws Exception { - StatisticSet ss = StatisticSet.builder() - .maximum(4.0) - .minimum(1.0) - .sampleCount(4.0) - .sum(10.0) - .build(); - MetricDatum metricDatum = MetricDatum.builder() - .metricName("TestMetricName") - .statisticSet(ss) - .dimension(new Dimension("TestDimension", "FAKE")) - .unit(Unit.COUNT) - .build(); - PutMetricData pmd = PutMetricData.builder() - .metricDatum(metricDatum) - .namespace("JCLOUDS/Test") - .build(); - - request = binder.bindToRequest(request, pmd); - - Assert.assertEquals(request.getPayload().getRawContent(), - new StringBuilder() - .append("Namespace=JCLOUDS%2FTest") - .append("&MetricData.member.1.Dimensions.member.1.Name=TestDimension") - .append("&MetricData.member.1.Dimensions.member.1.Value=FAKE") - .append("&MetricData.member.1.MetricName=TestMetricName") - .append("&MetricData.member.1.StatisticValues.Maximum=4.0") - .append("&MetricData.member.1.StatisticValues.Minimum=1.0") - .append("&MetricData.member.1.StatisticValues.SampleCount=4.0") - .append("&MetricData.member.1.StatisticValues.Sum=10.0") - .append("&MetricData.member.1.Unit=") - .append(Unit.COUNT.toString()) - .toString()); - } - - public void testMetricWithMultipleDimensions() throws Exception { - MetricDatum metricDatum = MetricDatum.builder() - .metricName("TestMetricName") - .dimension(new Dimension("TestDimension", "FAKE")) - .dimension(new Dimension("TestDimension2", "FAKE2")) - .unit(Unit.COUNT) - .timestamp(new Date(10000000l)) - .value(5.0) - .build(); - PutMetricData pmd = PutMetricData.builder() - .metricDatum(metricDatum) - .namespace("JCLOUDS/Test") - .build(); - - request = binder.bindToRequest(request, pmd); - - Assert.assertEquals(request.getPayload().getRawContent(), - new StringBuilder() - .append("Namespace=JCLOUDS%2FTest") - .append("&MetricData.member.1.Dimensions.member.1.Name=TestDimension") - .append("&MetricData.member.1.Dimensions.member.1.Value=FAKE") - .append("&MetricData.member.1.Dimensions.member.2.Name=TestDimension2") - .append("&MetricData.member.1.Dimensions.member.2.Value=FAKE2") - .append("&MetricData.member.1.MetricName=TestMetricName") - .append("&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z") - .append("&MetricData.member.1.Unit=") - .append(Unit.COUNT.toString()) - .append("&MetricData.member.1.Value=5.0") - .toString()); - } - - public void testMetricWithMultipleDatum() throws Exception { - StatisticSet ss = StatisticSet.builder() - .maximum(4.0) - .minimum(1.0) - .sampleCount(4.0) - .sum(10.0) - .build(); - MetricDatum metricDatum = MetricDatum.builder() - .metricName("TestMetricName") - .statisticSet(ss) - .dimension(new Dimension("TestDimension", "FAKE")) - .dimension(new Dimension("TestDimension2", "FAKE2")) - .unit(Unit.COUNT) - .timestamp(new Date(10000000l)) - .build(); - MetricDatum metricDatum2 = MetricDatum.builder() - .metricName("TestMetricName") - .dimension(new Dimension("TestDimension", "FAKE")) - .unit(Unit.COUNT) - .timestamp(new Date(10000000l)) - .value(5.0) - .build(); - PutMetricData pmd = PutMetricData.builder() - .metricData(ImmutableSet.of(metricDatum, metricDatum2)) - .namespace("JCLOUDS/Test") - .build(); - - request = binder.bindToRequest(request, pmd); - - Assert.assertEquals(request.getPayload().getRawContent(), - new StringBuilder() - .append("Namespace=JCLOUDS%2FTest") - .append("&MetricData.member.1.Dimensions.member.1.Name=TestDimension") - .append("&MetricData.member.1.Dimensions.member.1.Value=FAKE") - .append("&MetricData.member.1.Dimensions.member.2.Name=TestDimension2") - .append("&MetricData.member.1.Dimensions.member.2.Value=FAKE2") - .append("&MetricData.member.1.MetricName=TestMetricName") - .append("&MetricData.member.1.StatisticValues.Maximum=4.0") - .append("&MetricData.member.1.StatisticValues.Minimum=1.0") - .append("&MetricData.member.1.StatisticValues.SampleCount=4.0") - .append("&MetricData.member.1.StatisticValues.Sum=10.0") - .append("&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z") - .append("&MetricData.member.1.Unit=") - .append(Unit.COUNT.toString()) - .append("&MetricData.member.2.Dimensions.member.1.Name=TestDimension") - .append("&MetricData.member.2.Dimensions.member.1.Value=FAKE") - .append("&MetricData.member.2.MetricName=TestMetricName") - .append("&MetricData.member.2.Timestamp=1970-01-01T02%3A46%3A40Z") - .append("&MetricData.member.2.Unit=") - .append(Unit.COUNT.toString()) - .append("&MetricData.member.2.Value=5.0") - .toString()); - } - -} diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java index 81e1159e81..a25271c58f 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientExpectTest.java @@ -58,14 +58,14 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { .build()) .payload( payloadFromStringWithContentType( - new StringBuilder() - .append("Action=ListMetrics").append('&') - .append("Signature=KSh9oQydCR0HMAV6QPYwDzqwQIpxs8I%2Fig7brYgHVZU%3D").append('&') - .append("SignatureMethod=HmacSHA256").append('&') - .append("SignatureVersion=2").append('&') - .append("Timestamp=2009-11-08T15%3A54%3A08.897Z").append('&') - .append("Version=2010-08-01").append('&') - .append("AWSAccessKeyId=identity").toString(), "application/x-www-form-urlencoded")) + "Action=ListMetrics" + + "&Signature=KSh9oQydCR0HMAV6QPYwDzqwQIpxs8I%2Fig7brYgHVZU%3D" + + "&SignatureMethod=HmacSHA256" + + "&SignatureVersion=2" + + "&Timestamp=2009-11-08T15%3A54%3A08.897Z" + + "&Version=2010-08-01" + + "&AWSAccessKeyId=identity", + "application/x-www-form-urlencoded")) .build(); public void testListMetricsWhenResponseIs2xx() throws Exception { @@ -77,7 +77,8 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { listMetrics, listMetricsResponse); assertEquals(clientWhenMetricsExist.getMetricClientForRegion(null).listMetrics().toString(), - "ListMetricsResponse{metrics=[Metric{namespace=AWS/EC2, metricName=CPUUtilization, dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}], nextToken=null}"); + "ListMetricsResponse{metrics=[Metric{namespace=AWS/EC2, metricName=CPUUtilization, " + + "dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}], nextToken=null}"); } // TODO: this should really be an empty set @@ -93,28 +94,28 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { } public void testListMetricsWithOptionsWhenResponseIs2xx() throws Exception { - HttpRequest listMetricsWithOptions = HttpRequest.builder() - .method("POST") - .endpoint(URI.create("https://monitoring.us-east-1.amazonaws.com/")) - .headers(ImmutableMultimap. builder() - .put("Host", "monitoring.us-east-1.amazonaws.com") - .build()) - .payload( - payloadFromStringWithContentType( - new StringBuilder() - .append("Action=ListMetrics").append('&') - .append("Dimensions.member.1.Name=InstanceId").append('&') - .append("Dimensions.member.1.Value=SOMEINSTANCEID").append('&') - .append("MetricName=CPUUtilization").append('&') - .append("Namespace=SOMENEXTTOKEN").append('&') - .append("NextToken=AWS%2FEC2").append('&') - .append("Signature=G05HKEx9FJpGZBk02OVYwt3u4g%2FilAY9nU5hJI9LDXA%3D").append('&') - .append("SignatureMethod=HmacSHA256").append('&') - .append("SignatureVersion=2").append('&') - .append("Timestamp=2009-11-08T15%3A54%3A08.897Z").append('&') - .append("Version=2010-08-01").append('&') - .append("AWSAccessKeyId=identity").toString(), "application/x-www-form-urlencoded")) - .build(); + HttpRequest listMetricsWithOptions = + HttpRequest.builder() + .method("POST") + .endpoint(URI.create("https://monitoring.us-east-1.amazonaws.com/")) + .headers(ImmutableMultimap.builder() + .put("Host", "monitoring.us-east-1.amazonaws.com") + .build()) + .payload(payloadFromStringWithContentType( + "Action=ListMetrics" + + "&Dimensions.member.1.Name=InstanceId" + + "&Dimensions.member.1.Value=SOMEINSTANCEID" + + "&MetricName=CPUUtilization" + + "&Namespace=SOMENEXTTOKEN" + + "&NextToken=AWS%2FEC2" + + "&Signature=G05HKEx9FJpGZBk02OVYwt3u4g%2FilAY9nU5hJI9LDXA%3D" + + "&SignatureMethod=HmacSHA256" + + "&SignatureVersion=2" + + "&Timestamp=2009-11-08T15%3A54%3A08.897Z" + + "&Version=2010-08-01" + + "&AWSAccessKeyId=identity", + "application/x-www-form-urlencoded")) + .build(); HttpResponse listMetricsWithOptionsResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResourceWithContentType("/list_metrics.xml", "text/xml")).build(); @@ -125,12 +126,14 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { assertEquals( clientWhenMetricsWithOptionsExist.getMetricClientForRegion(null).listMetrics( ListMetricsOptions.builder() - .dimension(new Dimension(EC2Constants.Dimension.INSTANCE_ID, "SOMEINSTANCEID")) + .dimension(new Dimension(EC2Constants.Dimension.INSTANCE_ID, + "SOMEINSTANCEID")) .metricName(EC2Constants.MetricName.CPU_UTILIZATION) .namespace("SOMENEXTTOKEN") .nextToken( Namespaces.EC2) .build()).toString(), - "ListMetricsResponse{metrics=[Metric{namespace=AWS/EC2, metricName=CPUUtilization, dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}], nextToken=null}"); + "ListMetricsResponse{metrics=[Metric{namespace=AWS/EC2, metricName=CPUUtilization, " + + "dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}], nextToken=null}"); } GetMetricStatistics stats = GetMetricStatistics.builder() @@ -151,21 +154,22 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { .build()) .payload( payloadFromStringWithContentType( - new StringBuilder() - .append("Action=GetMetricStatistics").append('&') - .append("EndTime=1970-01-01T02%3A46%3A40Z").append('&') - .append("MetricName=CPUUtilization").append('&') - .append("Namespace=AWS%2FEC2").append('&') - .append("Period=60").append('&') - .append("Signature=rmg8%2Ba7w4ycy%2FKfO8rnuj6rDL0jNE96m8GKfjh3SWcw%3D").append('&') - .append("SignatureMethod=HmacSHA256").append('&') - .append("SignatureVersion=2").append('&') - .append("StartTime=1970-01-01T02%3A46%3A40Z").append('&') - .append("Statistics.member.1=Maximum").append('&') - .append("Statistics.member.2=Minimum").append('&') - .append("Timestamp=2009-11-08T15%3A54%3A08.897Z").append('&') - .append("Unit=Percent").append('&').append("Version=2010-08-01").append('&') - .append("AWSAccessKeyId=identity").toString(), "application/x-www-form-urlencoded")) + "Action=GetMetricStatistics" + + "&EndTime=1970-01-01T02%3A46%3A40Z" + + "&MetricName=CPUUtilization" + + "&Namespace=AWS%2FEC2" + + "&Period=60" + + "&Signature=rmg8%2Ba7w4ycy%2FKfO8rnuj6rDL0jNE96m8GKfjh3SWcw%3D" + + "&SignatureMethod=HmacSHA256" + + "&SignatureVersion=2" + + "&StartTime=1970-01-01T02%3A46%3A40Z" + + "&Statistics.member.1=Maximum" + + "&Statistics.member.2=Minimum" + + "&Timestamp=2009-11-08T15%3A54%3A08.897Z" + + "&Unit=Percent" + + "&Version=2010-08-01" + + "&AWSAccessKeyId=identity", + "application/x-www-form-urlencoded")) .build(); public void testGetMetricStatisticsWhenResponseIs2xx() throws Exception { @@ -178,7 +182,11 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { assertEquals( clientWhenMetricsExist.getMetricClientForRegion(null).getMetricStatistics(stats).toString(), // TODO: make an object for this - "GetMetricStatisticsResponse{label=CPUUtilization, datapoints=[Datapoint{timestamp=Thu Jan 15 16:00:00 PST 2009, customUnit=null, maximum=null, minimum=null, average=0.17777777777777778, sum=null, samples=9.0, unit=Percent}, Datapoint{timestamp=Thu Jan 15 16:01:00 PST 2009, customUnit=null, maximum=null, minimum=null, average=0.1, sum=null, samples=8.0, unit=Percent}]}"); + "GetMetricStatisticsResponse{label=CPUUtilization, " + + "datapoints=[Datapoint{timestamp=Thu Jan 15 16:00:00 PST 2009, customUnit=null, maximum=null, " + + "minimum=null, average=0.17777777777777778, sum=null, samples=9.0, unit=Percent}, " + + "Datapoint{timestamp=Thu Jan 15 16:01:00 PST 2009, customUnit=null, maximum=null, minimum=null, " + + "average=0.1, sum=null, samples=8.0, unit=Percent}]}"); } // TODO: this should really be an empty set @@ -193,35 +201,35 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { } public void testGetMetricStatisticsWithOptionsWhenResponseIs2xx() throws Exception { - HttpRequest getMetricStatistics = HttpRequest.builder() - .method("POST") - .endpoint(URI.create("https://monitoring.us-east-1.amazonaws.com/")) - .headers(ImmutableMultimap. builder() - .put("Host", "monitoring.us-east-1.amazonaws.com") - .build()) - .payload( - payloadFromStringWithContentType( - new StringBuilder() - .append("Action=GetMetricStatistics").append('&') - .append("Dimensions.member.1.Name=InstanceId").append('&') - .append("Dimensions.member.1.Value=SOMEINSTANCEID").append('&') - .append("Dimensions.member.2.Name=InstanceType").append('&') - .append("Dimensions.member.2.Value=t1.micro").append('&') - .append("EndTime=1970-01-01T02%3A46%3A40Z").append('&') - .append("MetricName=CPUUtilization").append('&') - .append("Namespace=AWS%2FEC2").append('&') - .append("Period=60").append('&') - .append("Signature=e0WyI%2FNm4hN2%2BMEm1mjRUzsvgvMCdFXbVJWi4ORpwic%3D").append('&') - .append("SignatureMethod=HmacSHA256").append('&') - .append("SignatureVersion=2").append('&') - .append("StartTime=1970-01-01T02%3A46%3A40Z").append('&') - .append("Statistics.member.1=Maximum").append('&') - .append("Statistics.member.2=Minimum").append('&') - .append("Timestamp=2009-11-08T15%3A54%3A08.897Z").append('&') - .append("Unit=Percent").append('&') - .append("Version=2010-08-01").append('&') - .append("AWSAccessKeyId=identity").toString(), "application/x-www-form-urlencoded")) - .build(); + HttpRequest getMetricStatistics = + HttpRequest.builder() + .method("POST") + .endpoint(URI.create("https://monitoring.us-east-1.amazonaws.com/")) + .headers(ImmutableMultimap. builder() + .put("Host", "monitoring.us-east-1.amazonaws.com") + .build()) + .payload(payloadFromStringWithContentType( + "Action=GetMetricStatistics" + + "&Dimensions.member.1.Name=InstanceId" + + "&Dimensions.member.1.Value=SOMEINSTANCEID" + + "&Dimensions.member.2.Name=InstanceType" + + "&Dimensions.member.2.Value=t1.micro" + + "&EndTime=1970-01-01T02%3A46%3A40Z" + + "&MetricName=CPUUtilization" + + "&Namespace=AWS%2FEC2" + + "&Period=60" + + "&Signature=e0WyI%2FNm4hN2%2BMEm1mjRUzsvgvMCdFXbVJWi4ORpwic%3D" + + "&SignatureMethod=HmacSHA256" + + "&SignatureVersion=2" + + "&StartTime=1970-01-01T02%3A46%3A40Z" + + "&Statistics.member.1=Maximum" + + "&Statistics.member.2=Minimum" + + "&Timestamp=2009-11-08T15%3A54%3A08.897Z" + + "&Unit=Percent" + + "&Version=2010-08-01" + + "&AWSAccessKeyId=identity", + "application/x-www-form-urlencoded")) + .build(); HttpResponse getMetricStatisticsResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResourceWithContentType("/get_metric_statistics.xml", "text/xml")).build(); @@ -235,11 +243,11 @@ public class MetricClientExpectTest extends BaseCloudWatchClientExpectTest { clientWhenMetricsExist.getMetricClientForRegion(null).getMetricStatistics(stats, GetMetricStatisticsOptions.Builder.dimension(dimension1).dimension(dimension2)).toString(), // TODO: make an object for this - "GetMetricStatisticsResponse{label=CPUUtilization, datapoints=[Datapoint{timestamp=Thu Jan 15 16:00:00 PST 2009, customUnit=null, maximum=null, minimum=null, average=0.17777777777777778, sum=null, samples=9.0, unit=Percent}, Datapoint{timestamp=Thu Jan 15 16:01:00 PST 2009, customUnit=null, maximum=null, minimum=null, average=0.1, sum=null, samples=8.0, unit=Percent}]}"); - } - - public void testPutMetricData() throws Exception { - + "GetMetricStatisticsResponse{label=CPUUtilization, " + + "datapoints=[Datapoint{timestamp=Thu Jan 15 16:00:00 PST 2009, customUnit=null, maximum=null, " + + "minimum=null, average=0.17777777777777778, sum=null, samples=9.0, unit=Percent}, " + + "Datapoint{timestamp=Thu Jan 15 16:01:00 PST 2009, customUnit=null, maximum=null, minimum=null, " + + "average=0.1, sum=null, samples=8.0, unit=Percent}]}"); } } diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java index de4e4b2f34..4d340598dd 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java @@ -31,7 +31,6 @@ import org.jclouds.cloudwatch.domain.ListMetricsResponse; import org.jclouds.cloudwatch.domain.Metric; import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.domain.Namespaces; -import org.jclouds.cloudwatch.domain.PutMetricData; import org.jclouds.cloudwatch.domain.StatisticSet; import org.jclouds.cloudwatch.domain.Statistics; import org.jclouds.cloudwatch.domain.Unit; @@ -83,13 +82,8 @@ public class MetricClientLiveTest extends BaseCloudWatchClientLiveTest { .timestamp(metricTimestamp) .value(10.0) .build(); - PutMetricData pmd = PutMetricData.builder() - .namespace(namespace) - .metricDatum(metricDatum) - .metricDatum(metricDatum2) - .build(); - client().putMetricData(pmd); + client().putMetricData(ImmutableSet.of(metricDatum, metricDatum2), namespace); ListMetricsOptions lmo = ListMetricsOptions.builder().namespace(namespace) .dimension(new Dimension("BaseMetricName", metricName)) From 84de4b30db55ab33c76592506a2de7f10b7e8757 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 26 May 2012 09:31:22 -0700 Subject: [PATCH 04/73] fixed CloudWatch.putMetricData --- .../org/jclouds/cloudwatch/CloudWatch.java | 26 +++++----------- .../jclouds/cloudwatch/CloudWatchTest.java | 31 ++++++++++--------- 2 files changed, 24 insertions(+), 33 deletions(-) diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java index 58f6109d00..8fdae90e02 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java @@ -18,16 +18,17 @@ */ package org.jclouds.cloudwatch; -import com.google.common.collect.AbstractIterator; -import com.google.common.collect.Sets; +import java.util.Iterator; +import java.util.List; + import org.jclouds.cloudwatch.domain.ListMetricsResponse; import org.jclouds.cloudwatch.domain.Metric; import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.features.MetricClient; import org.jclouds.cloudwatch.options.ListMetricsOptions; -import java.util.Iterator; -import java.util.Set; +import com.google.common.collect.AbstractIterator; +import com.google.common.collect.Iterables; /** * Utilities for using CloudWatch. @@ -107,22 +108,11 @@ public class CloudWatch { * @param namespace the namespace to publish the metrics in */ public static void putMetricData(CloudWatchClient cloudWatchClient, String region, Iterable metrics, - String namespace) { + String namespace) { MetricClient metricClient = cloudWatchClient.getMetricClientForRegion(region); - Iterator mIterator = metrics.iterator(); - Set metricsData = Sets.newLinkedHashSet(); - while (mIterator.hasNext()) { - metricsData.add(mIterator.next()); - if (metricsData.size() == 10 || !mIterator.hasNext()) { - // Make the call - metricClient.putMetricData(metrics, namespace); - - // Reset the list for subsequent call if necessary - if (mIterator.hasNext()) { - metricsData = Sets.newLinkedHashSet(); - } - } + for (List slice : Iterables.partition(metrics, 10)) { + metricClient.putMetricData(slice, namespace); } } diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java index 19102f982d..d3bffb1d11 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java @@ -18,9 +18,13 @@ */ package org.jclouds.cloudwatch; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; + +import java.util.List; +import java.util.Set; + import org.easymock.EasyMock; import org.jclouds.cloudwatch.domain.ListMetricsResponse; import org.jclouds.cloudwatch.domain.Metric; @@ -30,18 +34,16 @@ import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.testng.Assert; import org.testng.annotations.Test; -import java.util.Set; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; /** * Tests behavior of {@code CloudWatch}. * * @author Jeremy Whitlock */ +@Test(testName = "CloudWatchTest") public class CloudWatchTest { /** @@ -115,18 +117,17 @@ public class CloudWatchTest { String namespace = "JCLOUDS/Test"; for (int i = 0; i < 11; i++) { - metrics.add(MetricDatum.builder().build()); + metrics.add(MetricDatum.builder().metricName("foo").build()); } // Using EasyMock.eq("") because EasyMock makes it impossible to pass null as a String value here expect(client.getMetricClientForRegion(EasyMock.eq(""))) .andReturn(metricClient) .atLeastOnce(); - - - metricClient.putMetricData(metrics, namespace); - - expectLastCall().times(2); + + for (List slice : Iterables.partition(metrics, 10)) { + metricClient.putMetricData(slice, namespace); + } EasyMock.replay(client, metricClient); From cd08ce98cc93cf5d88e6c228c6cdd9ca355135b3 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 26 May 2012 09:31:41 -0700 Subject: [PATCH 05/73] addressed nullables --- .../binders/GetMetricStatisticsBinder.java | 38 ++++--- .../cloudwatch/binders/MetricDataBinder.java | 54 +++++----- .../domain/GetMetricStatistics.java | 70 ++++++------- .../cloudwatch/domain/MetricDatum.java | 98 ++++++++++++------- ...StatisticSet.java => StatisticValues.java} | 42 ++++---- .../binders/MetricDataBinderTest.java | 30 +++--- .../features/MetricClientLiveTest.java | 6 +- 7 files changed, 177 insertions(+), 161 deletions(-) rename apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/{StatisticSet.java => StatisticValues.java} (79%) diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java index e27aa85627..1fb4dafe98 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java @@ -18,8 +18,10 @@ */ package org.jclouds.cloudwatch.binders; -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMultimap; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; + import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.GetMetricStatistics; import org.jclouds.cloudwatch.domain.Statistics; @@ -27,9 +29,8 @@ import org.jclouds.date.DateService; import org.jclouds.http.HttpRequest; import org.jclouds.http.utils.ModifyRequest; -import javax.inject.Inject; -import java.util.HashSet; -import java.util.Set; +import com.google.common.annotations.Beta; +import com.google.common.collect.ImmutableMultimap; /** * Binds the metrics request to the http request @@ -51,41 +52,36 @@ public class GetMetricStatisticsBinder implements org.jclouds.rest.Binder { @Override public R bindToRequest(R request, Object payload) { - GetMetricStatistics getRequest = GetMetricStatistics.class.cast(payload); - Set dimensions = getRequest.getDimensions() != null ? - getRequest.getDimensions() : - new HashSet(); - Set statistics = getRequest.getStatistics() != null ? - getRequest.getStatistics() : - new HashSet(); + GetMetricStatistics getRequest = GetMetricStatistics.class.cast(checkNotNull(payload, + "GetMetricStatistics must be set!")); int dimensionIndex = 1; int statisticIndex = 1; ImmutableMultimap.Builder formParameters = ImmutableMultimap.builder(); - for (Dimension dimension : dimensions) { + for (Dimension dimension : getRequest.getDimensions()) { formParameters.put("Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); formParameters.put("Dimensions.member." + dimensionIndex + ".Value", dimension.getValue()); dimensionIndex++; } - if (getRequest.getEndTime() != null) { - formParameters.put("EndTime", dateService.iso8601SecondsDateFormat(getRequest.getEndTime())); + if (getRequest.getEndTime().isPresent()) { + formParameters.put("EndTime", dateService.iso8601SecondsDateFormat(getRequest.getEndTime().get())); } formParameters.put("MetricName", getRequest.getMetricName()); formParameters.put("Namespace", getRequest.getNamespace()); formParameters.put("Period", Integer.toString(getRequest.getPeriod())); - if (getRequest.getStartTime() != null) { + if (getRequest.getStartTime().isPresent()) { formParameters.put("StartTime", dateService.iso8601SecondsDateFormat(getRequest - .getStartTime())); + .getStartTime().get())); } - - for (Statistics statistic : statistics) { + + for (Statistics statistic : getRequest.getStatistics()) { formParameters.put("Statistics.member." + statisticIndex, statistic.toString()); statisticIndex++; } - if (getRequest.getUnit() != null) { - formParameters.put("Unit", getRequest.getUnit().toString()); + if (getRequest.getUnit().isPresent()) { + formParameters.put("Unit", getRequest.getUnit().get().toString()); } return ModifyRequest.putFormParams(request, formParameters.build()); diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java index 1ddffd48cf..15f28503c6 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java @@ -18,18 +18,18 @@ */ package org.jclouds.cloudwatch.binders; -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMultimap; -import com.google.inject.Inject; +import static com.google.common.base.Preconditions.checkNotNull; + import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.MetricDatum; -import org.jclouds.cloudwatch.domain.StatisticSet; +import org.jclouds.cloudwatch.domain.StatisticValues; import org.jclouds.date.DateService; import org.jclouds.http.HttpRequest; import org.jclouds.http.utils.ModifyRequest; -import java.util.HashSet; -import java.util.Set; +import com.google.common.annotations.Beta; +import com.google.common.collect.ImmutableMultimap; +import com.google.inject.Inject; /** * Binds the metrics request to the http request @@ -51,22 +51,18 @@ public class MetricDataBinder implements org.jclouds.rest.Binder { /** * {@inheritDoc} */ + @SuppressWarnings("unchecked") @Override public R bindToRequest(R request, Object input) { - Iterable metrics = input != null ? - (Iterable)input : - new HashSet(); + Iterable metrics = (Iterable) checkNotNull(input, "metrics must be set!"); + ImmutableMultimap.Builder formParameters = ImmutableMultimap.builder(); int metricDatumIndex = 1; for (MetricDatum metricDatum : metrics) { int dimensionIndex = 1; - StatisticSet statisticSet = metricDatum.getStatisticSet(); - Set dimensions = metricDatum.getDimensions() != null ? - metricDatum.getDimensions() : - new HashSet(); - for (Dimension dimension : dimensions) { + for (Dimension dimension : metricDatum.getDimensions()) { formParameters.put("MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + ".Name", dimension.getName()); formParameters.put("MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + @@ -76,30 +72,30 @@ public class MetricDataBinder implements org.jclouds.rest.Binder { formParameters.put("MetricData.member." + metricDatumIndex + ".MetricName", metricDatum.getMetricName()); - if (statisticSet != null) { + + if (metricDatum.getStatisticValues().isPresent()) { + StatisticValues statisticValues = metricDatum.getStatisticValues().get(); + formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Maximum", - String.valueOf(statisticSet.getMaximum())); + String.valueOf(statisticValues.getMaximum())); formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Minimum", - String.valueOf(statisticSet.getMinimum())); + String.valueOf(statisticValues.getMinimum())); formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.SampleCount", - String.valueOf(statisticSet.getSampleCount())); + String.valueOf(statisticValues.getSampleCount())); formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Sum", - String.valueOf(statisticSet.getSum())); + String.valueOf(statisticValues.getSum())); } - if (metricDatum.getTimestamp() != null) { + + if (metricDatum.getTimestamp().isPresent()) { formParameters.put("MetricData.member." + metricDatumIndex + ".Timestamp", - dateService.iso8601SecondsDateFormat(metricDatum.getTimestamp())); + dateService.iso8601SecondsDateFormat(metricDatum.getTimestamp().get())); } - if (metricDatum.getUnit() != null) { - formParameters.put("MetricData.member." + metricDatumIndex + ".Unit", - String.valueOf(metricDatum.getUnit())); - } + formParameters.put("MetricData.member." + metricDatumIndex + ".Unit", + String.valueOf(metricDatum.getUnit())); - if (metricDatum.getValue() != null) { - formParameters.put("MetricData.member." + metricDatumIndex + ".Value", - String.valueOf(metricDatum.getValue())); - } + formParameters.put("MetricData.member." + metricDatumIndex + ".Value", + String.valueOf(metricDatum.getValue())); metricDatumIndex++; } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java index 17f961dbf0..a386602bae 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java @@ -18,14 +18,18 @@ */ package org.jclouds.cloudwatch.domain; -import com.google.common.annotations.Beta; -import com.google.common.collect.Sets; -import org.jclouds.cloudwatch.options.ListMetricsOptions; -import org.jclouds.javax.annotation.Nullable; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.Date; import java.util.Set; +import org.jclouds.cloudwatch.options.ListMetricsOptions; + +import com.google.common.annotations.Beta; +import com.google.common.base.Optional; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + /** * Options use to get statistics for the specified metric. * @@ -37,33 +41,32 @@ import java.util.Set; public class GetMetricStatistics { private final Set dimensions; - private final Date endTime; + private final Optional endTime; private final String metricName; private final String namespace; private final int period; - private final Date startTime; + private final Optional startTime; private final Set statistics; - private final Unit unit; + private final Optional unit; /** * Private constructor to enforce using {@link Builder}. */ - private GetMetricStatistics(Set dimensions, Date endTime, String metricName, String namespace, int period, + protected GetMetricStatistics(Set dimensions, Date endTime, String metricName, String namespace, int period, Date startTime, Set statistics, Unit unit) { - this.dimensions = dimensions; - this.endTime = endTime; - this.metricName = metricName; - this.namespace = namespace; + this.dimensions = ImmutableSet.copyOf(checkNotNull(dimensions, "dimensions")); + this.endTime = Optional.fromNullable(endTime); + this.metricName = checkNotNull(metricName, "metricName"); + this.namespace = checkNotNull(namespace, "namespace"); this.period = period; - this.startTime = startTime; - this.statistics = statistics; - this.unit = unit; + this.startTime = Optional.fromNullable(startTime); + this.statistics = ImmutableSet.copyOf(checkNotNull(statistics, "statistics")); + this.unit = Optional.fromNullable(unit); } /** * return the set of dimensions for this request */ - @Nullable public Set getDimensions() { return dimensions; } @@ -71,15 +74,13 @@ public class GetMetricStatistics { /** * return the end time for this request */ - @Nullable - public Date getEndTime() { + public Optional getEndTime() { return endTime; } /** * return the metric name for this request */ - @Nullable public String getMetricName() { return metricName; } @@ -87,7 +88,6 @@ public class GetMetricStatistics { /** * return the namespace for this request */ - @Nullable public String getNamespace() { return namespace; } @@ -95,7 +95,6 @@ public class GetMetricStatistics { /** * return the period for this request */ - @Nullable public int getPeriod() { return period; } @@ -103,15 +102,13 @@ public class GetMetricStatistics { /** * return the start time for this request */ - @Nullable - public Date getStartTime() { + public Optional getStartTime() { return startTime; } /** * return the statistics for this request */ - @Nullable public Set getStatistics() { return statistics; } @@ -119,8 +116,7 @@ public class GetMetricStatistics { /** * return the unit for this request */ - @Nullable - public Unit getUnit() { + public Optional getUnit() { return unit; } @@ -134,13 +130,15 @@ public class GetMetricStatistics { public static class Builder { - private Set dimensions; + // this builder is set to be additive on dimension calls, so make this mutable + private Set dimensions = Sets.newLinkedHashSet(); private Date endTime; private String metricName; private String namespace; - private int period; + private int period = 60; private Date startTime; - private Set statistics; + // this builder is set to be additive on dimension calls, so make this mutable + private Set statistics = Sets.newLinkedHashSet(); private Unit unit; /** @@ -157,7 +155,7 @@ public class GetMetricStatistics { * @return this {@code Builder} object */ public Builder dimensions(Set dimensions) { - this.dimensions = dimensions; + this.dimensions.addAll(checkNotNull(dimensions, "dimensions")); return this; } @@ -169,10 +167,7 @@ public class GetMetricStatistics { * @return this {@code Builder} object */ public Builder dimension(Dimension dimension) { - if (dimensions == null) { - dimensions = Sets.newLinkedHashSet(); - } - this.dimensions.add(dimension); + this.dimensions.add(checkNotNull(dimension, "dimension")); return this; } @@ -246,7 +241,7 @@ public class GetMetricStatistics { * @return this {@code Builder} object */ public Builder statistics(Set statistics) { - this.statistics = statistics; + this.statistics.addAll(checkNotNull(statistics, "statistics")); return this; } @@ -258,10 +253,7 @@ public class GetMetricStatistics { * @return this {@code Builder} object */ public Builder statistic(Statistics statistic) { - if (statistics == null) { - statistics = Sets.newLinkedHashSet(); - } - this.statistics.add(statistic); + this.statistics.add(checkNotNull(statistic, "statistic")); return this; } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java index 6f0e36cc30..2bd2d1385e 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java @@ -18,12 +18,18 @@ */ package org.jclouds.cloudwatch.domain; -import com.google.common.collect.Sets; -import org.jclouds.javax.annotation.Nullable; +import static com.google.common.base.Objects.equal; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.Date; import java.util.Set; +import com.google.common.base.Objects; +import com.google.common.base.Optional; +import com.google.common.base.Objects.ToStringHelper; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + /** * @see * @@ -33,28 +39,27 @@ public class MetricDatum { private final Set dimensions; private final String metricName; - private final StatisticSet statisticSet; - private final Date timestamp; + private final Optional statisticValues; + private final Optional timestamp; private final Unit unit; - private final Double value; + private final double value; /** * Private constructor to enforce using {@link Builder}. */ - private MetricDatum(Set dimensions, String metricName, StatisticSet statisticSet, Date timestamp, - Unit unit, Double value) { - this.dimensions = dimensions; - this.metricName = metricName; - this.statisticSet = statisticSet; - this.timestamp = timestamp; - this.unit = unit; - this.value = value; + protected MetricDatum(Set dimensions, String metricName, StatisticValues statisticValues, Date timestamp, + Unit unit, double value) { + this.dimensions = ImmutableSet.copyOf(checkNotNull(dimensions, "dimensions")); + this.metricName = checkNotNull(metricName, "metricName"); + this.statisticValues = Optional.fromNullable(statisticValues); + this.timestamp = Optional.fromNullable(timestamp); + this.unit = checkNotNull(unit, "unit"); + this.value = checkNotNull(value, "value"); } /** * return the list of dimensions describing the the metric. */ - @Nullable public Set getDimensions() { return dimensions; } @@ -62,7 +67,6 @@ public class MetricDatum { /** * return the metric name for the metric. */ - @Nullable public String getMetricName() { return metricName; } @@ -70,23 +74,20 @@ public class MetricDatum { /** * return the object describing the set of statistical values for the metric */ - @Nullable - public StatisticSet getStatisticSet() { - return statisticSet; + public Optional getStatisticValues() { + return statisticValues; } /** * return the time stamp used for the metric */ - @Nullable - public Date getTimestamp() { + public Optional getTimestamp() { return timestamp; } /** * return Standard unit used for the metric. */ - @Nullable public Unit getUnit() { return unit; } @@ -94,8 +95,7 @@ public class MetricDatum { /** * return the actual value of the metric */ - @Nullable - public Double getValue() { + public double getValue() { return value; } @@ -109,12 +109,13 @@ public class MetricDatum { public static class Builder { - private Set dimensions; + // this builder is set to be additive on dimension calls, so make this mutable + private Set dimensions = Sets.newLinkedHashSet(); private String metricName; - private StatisticSet statisticSet; + private StatisticValues statisticValues; private Date timestamp; - private Unit unit; - private Double value; + private Unit unit = Unit.NONE; + private double value; /** * Creates a new builder. The returned builder is equivalent to the builder @@ -130,7 +131,7 @@ public class MetricDatum { * @return this {@code Builder} object */ public Builder dimensions(Set dimensions) { - this.dimensions = dimensions; + this.dimensions.addAll(checkNotNull(dimensions, "dimensions")); return this; } @@ -142,10 +143,7 @@ public class MetricDatum { * @return this {@code Builder} object */ public Builder dimension(Dimension dimension) { - if (dimensions == null) { - dimensions = Sets.newLinkedHashSet(); - } - this.dimensions.add(dimension); + this.dimensions.add(checkNotNull(dimension, "dimension")); return this; } @@ -164,12 +162,12 @@ public class MetricDatum { /** * The object describing the set of statistical values describing the metric. * - * @param statisticSet the object describing the set of statistical values for the metric + * @param statisticValues the object describing the set of statistical values for the metric * * @return this {@code Builder} object */ - public Builder statisticSet(StatisticSet statisticSet) { - this.statisticSet = statisticSet; + public Builder statisticValues(StatisticValues statisticValues) { + this.statisticValues = statisticValues; return this; } @@ -205,7 +203,7 @@ public class MetricDatum { * * @return this {@code Builder} object */ - public Builder value(Double value) { + public Builder value(double value) { this.value = value; return this; } @@ -214,9 +212,35 @@ public class MetricDatum { * Returns a newly-created {@code MetricDatum} based on the contents of the {@code Builder}. */ public MetricDatum build() { - return new MetricDatum(dimensions, metricName, statisticSet, timestamp, unit, value); + return new MetricDatum(dimensions, metricName, statisticValues, timestamp, unit, value); } } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + MetricDatum that = MetricDatum.class.cast(o); + return equal(this.dimensions, that.dimensions) && equal(this.metricName, that.metricName) + && equal(this.statisticValues, that.statisticValues) && equal(this.timestamp, that.timestamp) + && equal(this.unit, that.unit) && equal(this.value, that.value); + } + + @Override + public int hashCode() { + return Objects.hashCode(dimensions, metricName, statisticValues, timestamp, unit, value); + } + + @Override + public String toString() { + return string().toString(); + } + + protected ToStringHelper string() { + return Objects.toStringHelper("").add("dimensions", dimensions).add("metricName", metricName).add( + "statisticValues", statisticValues).add("timestamp", timestamp).add("unit", unit).add("value", value); + } } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticValues.java similarity index 79% rename from apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java rename to apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticValues.java index 82674dbf87..d0e235f9b5 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticSet.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticValues.java @@ -25,14 +25,14 @@ import org.jclouds.javax.annotation.Nullable; * * @author Jeremy Whitlock */ -public class StatisticSet { +public class StatisticValues { - private final Double maximum; - private final Double minimum; - private final Double sampleCount; - private final Double sum; + private final double maximum; + private final double minimum; + private final double sampleCount; + private final double sum; - public StatisticSet(Double maximum, Double minimum, Double sampleCount, Double sum) { + public StatisticValues(double maximum, double minimum, double sampleCount, double sum) { this.maximum = maximum; this.minimum = minimum; this.sampleCount = sampleCount; @@ -43,7 +43,7 @@ public class StatisticSet { * return the maximum value of the sample set */ @Nullable - public Double getMaximum() { + public double getMaximum() { return maximum; } @@ -51,7 +51,7 @@ public class StatisticSet { * return the minimum value of the sample set */ @Nullable - public Double getMinimum() { + public double getMinimum() { return minimum; } @@ -59,7 +59,7 @@ public class StatisticSet { * return the number of samples used for the statistic set */ @Nullable - public Double getSampleCount() { + public double getSampleCount() { return sampleCount; } @@ -67,7 +67,7 @@ public class StatisticSet { * return the sum of values for the sample set */ @Nullable - public Double getSum() { + public double getSum() { return sum; } @@ -81,14 +81,14 @@ public class StatisticSet { public static class Builder { - private Double maximum; - private Double minimum; - private Double sampleCount; - private Double sum; + private double maximum; + private double minimum; + private double sampleCount; + private double sum; /** * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link org.jclouds.cloudwatch.domain.StatisticSet#builder}. + * generated by {@link org.jclouds.cloudwatch.domain.StatisticValues#builder}. */ public Builder() {} @@ -99,7 +99,7 @@ public class StatisticSet { * * @return this {@code Builder} object */ - public Builder maximum(Double maximum) { + public Builder maximum(double maximum) { this.maximum = maximum; return this; } @@ -111,7 +111,7 @@ public class StatisticSet { * * @return this {@code Builder} object */ - public Builder minimum(Double minimum) { + public Builder minimum(double minimum) { this.minimum = minimum; return this; } @@ -123,7 +123,7 @@ public class StatisticSet { * * @return this {@code Builder} object */ - public Builder sampleCount(Double sampleCount) { + public Builder sampleCount(double sampleCount) { this.sampleCount = sampleCount; return this; } @@ -135,7 +135,7 @@ public class StatisticSet { * * @return this {@code Builder} object */ - public Builder sum(Double sum) { + public Builder sum(double sum) { this.sum = sum; return this; } @@ -143,8 +143,8 @@ public class StatisticSet { /** * Returns a newly-created {@code StatisticSet} based on the contents of the {@code Builder}. */ - public StatisticSet build() { - return new StatisticSet(maximum, minimum, sampleCount, sum); + public StatisticValues build() { + return new StatisticValues(maximum, minimum, sampleCount, sum); } } diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java index 0b79702422..554deab5ca 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java @@ -24,7 +24,7 @@ import com.google.inject.Injector; import junit.framework.Assert; import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.MetricDatum; -import org.jclouds.cloudwatch.domain.StatisticSet; +import org.jclouds.cloudwatch.domain.StatisticValues; import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.http.HttpRequest; import org.testng.annotations.Test; @@ -37,28 +37,33 @@ import java.util.Date; * * @author Jeremy Whitlock */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "MetricDataBinderTest") public class MetricDataBinderTest { Injector injector = Guice.createInjector(); MetricDataBinder binder = injector.getInstance(MetricDataBinder.class); - HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + + HttpRequest request() { + return HttpRequest.builder().method("POST").endpoint(URI.create("http://localhost")).build(); + } public void testMetricWithoutTimestamp() throws Exception { - StatisticSet ss = StatisticSet.builder() + StatisticValues ss = StatisticValues.builder() .maximum(4.0) .minimum(1.0) .sampleCount(4.0) .sum(10.0) .build(); + MetricDatum metricDatum = MetricDatum.builder() .metricName("TestMetricName") - .statisticSet(ss) + .statisticValues(ss) .dimension(new Dimension("TestDimension", "FAKE")) .unit(Unit.COUNT) + .value(2) .build(); - request = binder.bindToRequest(request, ImmutableSet.of(metricDatum)); + HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(metricDatum)); Assert.assertEquals(request.getPayload().getRawContent(), "MetricData.member.1.Dimensions.member.1.Name=TestDimension" + @@ -68,7 +73,8 @@ public class MetricDataBinderTest { "&MetricData.member.1.StatisticValues.Minimum=1.0" + "&MetricData.member.1.StatisticValues.SampleCount=4.0" + "&MetricData.member.1.StatisticValues.Sum=10.0" + - "&MetricData.member.1.Unit=" + Unit.COUNT.toString()); + "&MetricData.member.1.Unit=" + Unit.COUNT.toString() + + "&MetricData.member.1.Value=2.0"); } public void testMetricWithMultipleDimensions() throws Exception { @@ -81,7 +87,7 @@ public class MetricDataBinderTest { .value(5.0) .build(); - request = binder.bindToRequest(request, ImmutableSet.of(metricDatum)); + HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(metricDatum)); Assert.assertEquals(request.getPayload().getRawContent(), "MetricData.member.1.Dimensions.member.1.Name=TestDimension" + @@ -95,7 +101,7 @@ public class MetricDataBinderTest { } public void testMetricWithMultipleDatum() throws Exception { - StatisticSet ss = StatisticSet.builder() + StatisticValues ss = StatisticValues.builder() .maximum(4.0) .minimum(1.0) .sampleCount(4.0) @@ -103,11 +109,12 @@ public class MetricDataBinderTest { .build(); MetricDatum metricDatum = MetricDatum.builder() .metricName("TestMetricName") - .statisticSet(ss) + .statisticValues(ss) .dimension(new Dimension("TestDimension", "FAKE")) .dimension(new Dimension("TestDimension2", "FAKE2")) .unit(Unit.COUNT) .timestamp(new Date(10000000l)) + .value(2.0) .build(); MetricDatum metricDatum2 = MetricDatum.builder() .metricName("TestMetricName") @@ -117,7 +124,7 @@ public class MetricDataBinderTest { .value(5.0) .build(); - request = binder.bindToRequest(request, ImmutableSet.of(metricDatum, metricDatum2)); + HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(metricDatum, metricDatum2)); Assert.assertEquals(request.getPayload().getRawContent(), "MetricData.member.1.Dimensions.member.1.Name=TestDimension" + @@ -131,6 +138,7 @@ public class MetricDataBinderTest { "&MetricData.member.1.StatisticValues.Sum=10.0" + "&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z" + "&MetricData.member.1.Unit=" + Unit.COUNT.toString() + + "&MetricData.member.1.Value=2.0" + "&MetricData.member.2.Dimensions.member.1.Name=TestDimension" + "&MetricData.member.2.Dimensions.member.1.Value=FAKE" + "&MetricData.member.2.MetricName=TestMetricName" + diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java index 4d340598dd..e582f8ff49 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricClientLiveTest.java @@ -31,7 +31,7 @@ import org.jclouds.cloudwatch.domain.ListMetricsResponse; import org.jclouds.cloudwatch.domain.Metric; import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.domain.Namespaces; -import org.jclouds.cloudwatch.domain.StatisticSet; +import org.jclouds.cloudwatch.domain.StatisticValues; import org.jclouds.cloudwatch.domain.Statistics; import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.cloudwatch.internal.BaseCloudWatchClientLiveTest; @@ -61,7 +61,7 @@ public class MetricClientLiveTest extends BaseCloudWatchClientLiveTest { // CloudWatch rounds metric timestamps down to the closest minute Date metricTimestampInCloudWatch = new Date(metricTimestamp.getTime() - (metricTimestamp.getTime() % (60 * 1000))); - StatisticSet ss = StatisticSet.builder() + StatisticValues ss = StatisticValues.builder() .maximum(4.0) .minimum(1.0) .sampleCount(4.0) @@ -69,7 +69,7 @@ public class MetricClientLiveTest extends BaseCloudWatchClientLiveTest { .build(); MetricDatum metricDatum = MetricDatum.builder() .metricName(metricName + "_1") - .statisticSet(ss) + .statisticValues(ss) .dimension(new Dimension("BaseMetricName", metricName)) .dimension(new Dimension("TestDimension2", "TEST2")) .unit(Unit.COUNT) From 07c2c2472124c0c4d5747438b353665c124a5c51 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 29 May 2012 20:41:10 -0700 Subject: [PATCH 06/73] Issue 949:Introduce: ComputeMetadataIncludingStatus; Deprecate NodeState -> NodeMetadata.Status --- .../byon/functions/NodeToNodeMetadata.java | 4 +- .../functions/NodeToNodeMetadataTest.java | 4 +- ...oudServersComputeServiceContextModule.java | 56 ++++++------ .../functions/ServerToNodeMetadata.java | 10 +-- ...erversComputeServiceContextModuleTest.java | 2 +- .../functions/ServerToNodeMetadataTest.java | 20 ++--- .../functions/ServerInfoToNodeMetadata.java | 18 ++-- .../VirtualMachineToNodeMetadata.java | 24 ++--- .../VirtualMachineToNodeMetadataTest.java | 8 +- .../functions/InstanceToNodeMetadata.java | 14 +-- .../EC2ComputeServiceDependenciesModule.java | 16 ++-- .../RunningInstanceToNodeMetadata.java | 14 +-- .../AddElasticIpsToNodemetadataTest.java | 4 +- .../RunningInstanceToNodeMetadataTest.java | 32 +++---- ...EC2CreateNodesInGroupThenAddToSetTest.java | 6 +- .../functions/ServerInfoToNodeMetadata.java | 18 ++-- .../NovaComputeServiceContextModule.java | 40 ++++----- .../functions/ServerToNodeMetadata.java | 10 +-- .../NovaComputeServiceContextModuleTest.java | 2 +- .../functions/ServerToNodeMetadataTest.java | 16 ++-- .../functions/ServerInZoneToNodeMetadata.java | 2 +- .../openstack/nova/v1_1/domain/Server.java | 22 ++--- ...ocateAndAddFloatingIpToNodeExpectTest.java | 4 +- .../functions/OrphanedGroupsByZoneIdTest.java | 1 - .../ServerInZoneToNodeMetadataTest.java | 3 +- .../v1_1/parse/ParseCreatedServerTest.java | 4 - ...CloudComputeServiceDependenciesModule.java | 17 ++-- .../compute/functions/VAppToNodeMetadata.java | 9 +- .../functions/VAppToNodeMetadataTest.java | 3 +- .../compute/TerremarkVCloudComputeClient.java | 10 +-- ...markVCloudComputeServiceContextModule.java | 14 +-- .../compute/functions/VAppToNodeMetadata.java | 9 +- .../TerremarkVCloudComputeClientTest.java | 10 +-- .../strategy/CleanupOrphanKeysTest.java | 6 +- .../src/main/clojure/org/jclouds/compute2.clj | 28 +++--- .../config/ComputeServiceTimeoutsModule.java | 4 +- .../ComputeMetadataIncludingStatus.java | 32 +++++++ .../jclouds/compute/domain/NodeMetadata.java | 37 +++++++- .../compute/domain/NodeMetadataBuilder.java | 52 ++++------- .../org/jclouds/compute/domain/NodeState.java | 51 ++++++++++- .../compute/domain/TemplateBuilderSpec.java | 8 +- .../domain/internal/NodeMetadataImpl.java | 51 ++++------- .../compute/internal/BaseComputeService.java | 10 +-- .../compute/options/TemplateOptions.java | 4 +- .../compute/predicates/AtomicNodeRunning.java | 9 +- .../predicates/AtomicNodeSuspended.java | 9 +- ...OnFalse.java => AtomicNodeTerminated.java} | 44 +++------ .../compute/predicates/NodePredicates.java | 8 +- ...ndDoubleCheckOnFailUnlessStateInvalid.java | 90 ------------------- ...dDoubleCheckOnFailUnlessStatusInvalid.java | 77 ++++++++++++++++ ...dDoubleCheckOnFailUnlessStatusInvalid.java | 65 ++++++++++++++ ...OrDeletedRefreshAndDoubleCheckOnFalse.java | 67 ++++++++++++++ ...dAddToGoodMapOrPutExceptionIntoBadMap.java | 12 +-- .../AdaptingComputeServiceStrategies.java | 4 +- ...sWithGroupEncodedIntoNameThenAddToSet.java | 8 +- .../config/StubComputeServiceAdapter.java | 44 ++++----- .../StubComputeServiceDependenciesModule.java | 4 +- ...riptUsingSshAndBlockUntilCompleteTest.java | 12 +-- ...nScriptOnNodeAsInitScriptUsingSshTest.java | 10 +-- .../config/PersistNodeCredentialsTest.java | 10 +-- .../internal/BaseComputeServiceLiveTest.java | 18 ++-- .../predicates/AtomicNodePredicatesTest.java | 20 ++--- ...ToGoodMapOrPutExceptionIntoBadMapTest.java | 16 ++-- .../ServerDetailsToNodeMetadata.java | 14 +-- .../ServerDetailsToNodeMetadataTest.java | 4 +- .../java/org/jclouds/nodepool/AppTest.java | 4 +- .../keystone/v2_0/AdminClientExpectTest.java | 1 + .../compute/functions/VMToNodeMetadata.java | 14 +-- .../compute/functions/VmToNodeMetadata.java | 11 ++- ...rdcodeLocalhostAsNodeMetadataSupplier.java | 5 +- ...VirtualBoxComputeServiceContextModule.java | 36 ++++---- .../functions/IMachineToNodeMetadata.java | 10 +-- .../virtualbox/functions/NodeCreator.java | 2 +- .../StartVBoxIfNotAlreadyRunningLiveTest.java | 6 +- .../AWSRunningInstanceToNodeMetadata.java | 6 +- .../AWSRunningInstanceToNodeMetadataTest.java | 14 +-- .../GoGridComputeServiceContextModule.java | 26 +++--- .../functions/ServerToNodeMetadata.java | 10 +-- ...GoGridComputeServiceContextModuleTest.java | 2 +- .../functions/ServerToNodeMetadataTest.java | 12 +-- .../miro/binder/RimuHostingJsonBinder.java | 1 - ...stingComputeServiceDependenciesModule.java | 18 ++-- .../functions/ServerToNodeMetadata.java | 14 +-- ...ostingComputeServiceContextModuleTest.java | 2 +- .../SlicehostComputeServiceContextModule.java | 20 ++--- .../functions/SliceToNodeMetadata.java | 10 +-- ...cehostComputeServiceContextModuleTest.java | 2 +- .../functions/SliceToNodeMetadataTest.java | 20 ++--- .../functions/VirtualGuestToNodeMetadata.java | 12 +-- .../VirtualGuestToNodeMetadataTest.java | 12 +-- .../functions/ServerToNodeMetadata.java | 14 +-- 91 files changed, 857 insertions(+), 681 deletions(-) create mode 100644 compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataIncludingStatus.java rename compute/src/main/java/org/jclouds/compute/predicates/{TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse.java => AtomicNodeTerminated.java} (51%) delete mode 100644 compute/src/main/java/org/jclouds/compute/predicates/RefreshAndDoubleCheckOnFailUnlessStateInvalid.java create mode 100644 compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshAndDoubleCheckOnFailUnlessStatusInvalid.java create mode 100644 compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid.java create mode 100644 compute/src/main/java/org/jclouds/compute/predicates/internal/TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse.java diff --git a/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java b/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java index 878da381b3..8b9655fe5d 100644 --- a/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java +++ b/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java @@ -36,9 +36,9 @@ import org.jclouds.byon.Node; import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; @@ -90,7 +90,7 @@ public class NodeToNodeMetadata implements Function { builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); - builder.state(NodeState.RUNNING); + builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet. of(from.getHostname())); if (from.getUsername() != null) { diff --git a/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java b/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java index f3bb421920..8a5034fa24 100644 --- a/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java +++ b/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java @@ -27,9 +27,9 @@ import java.util.Set; import org.jclouds.byon.suppliers.SupplyFromProviderURIOrNodesProperty; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -88,7 +88,7 @@ public class NodeToNodeMetadataTest { .location(location) .userMetadata(ImmutableMap.of("Name", "foo")) .tags(ImmutableSet.of("vanilla")) - .state(NodeState.RUNNING) + .status(Status.RUNNING) .operatingSystem( OperatingSystem.builder().description("redhat").family(OsFamily.RHEL).arch("x86").version("5.3") .build()) diff --git a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java index 2810f6012a..8ab0b09680 100644 --- a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java +++ b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java @@ -37,8 +37,8 @@ import org.jclouds.compute.config.ComputeServiceAdapterContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.internal.BaseComputeService; import org.jclouds.domain.Location; @@ -93,36 +93,36 @@ public class CloudServersComputeServiceContextModule extends } @VisibleForTesting - public static final Map serverToNodeState = ImmutableMap - . builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)// - .put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)// - .put(ServerStatus.DELETED, NodeState.TERMINATED)// - .put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)// - .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// - .put(ServerStatus.RESIZE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// - .put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)// - .put(ServerStatus.PREP_MOVE, NodeState.PENDING)// - .put(ServerStatus.MOVE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)// - .put(ServerStatus.RESCUE, NodeState.PENDING)// - .put(ServerStatus.ERROR, NodeState.ERROR)// - .put(ServerStatus.BUILD, NodeState.PENDING)// - .put(ServerStatus.RESTORING, NodeState.PENDING)// - .put(ServerStatus.PASSWORD, NodeState.PENDING)// - .put(ServerStatus.REBUILD, NodeState.PENDING)// - .put(ServerStatus.DELETE_IP, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP, NodeState.PENDING)// - .put(ServerStatus.REBOOT, NodeState.PENDING)// - .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// - .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// - .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + public static final Map serverToNodeStatus = ImmutableMap + . builder().put(ServerStatus.ACTIVE, Status.RUNNING)// + .put(ServerStatus.SUSPENDED, Status.SUSPENDED)// + .put(ServerStatus.DELETED, Status.TERMINATED)// + .put(ServerStatus.QUEUE_RESIZE, Status.PENDING)// + .put(ServerStatus.PREP_RESIZE, Status.PENDING)// + .put(ServerStatus.RESIZE, Status.PENDING)// + .put(ServerStatus.VERIFY_RESIZE, Status.PENDING)// + .put(ServerStatus.QUEUE_MOVE, Status.PENDING)// + .put(ServerStatus.PREP_MOVE, Status.PENDING)// + .put(ServerStatus.MOVE, Status.PENDING)// + .put(ServerStatus.VERIFY_MOVE, Status.PENDING)// + .put(ServerStatus.RESCUE, Status.PENDING)// + .put(ServerStatus.ERROR, Status.ERROR)// + .put(ServerStatus.BUILD, Status.PENDING)// + .put(ServerStatus.RESTORING, Status.PENDING)// + .put(ServerStatus.PASSWORD, Status.PENDING)// + .put(ServerStatus.REBUILD, Status.PENDING)// + .put(ServerStatus.DELETE_IP, Status.PENDING)// + .put(ServerStatus.SHARE_IP_NO_CONFIG, Status.PENDING)// + .put(ServerStatus.SHARE_IP, Status.PENDING)// + .put(ServerStatus.REBOOT, Status.PENDING)// + .put(ServerStatus.HARD_REBOOT, Status.PENDING)// + .put(ServerStatus.UNKNOWN, Status.UNRECOGNIZED)// + .put(ServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED).build(); @Singleton @Provides - Map provideServerToNodeState() { - return serverToNodeState; + Map provideServerToNodeStatus() { + return serverToNodeStatus; } @Override diff --git a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadata.java b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadata.java index a161ad4aa3..f28cb4e71e 100644 --- a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadata.java +++ b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadata.java @@ -37,8 +37,8 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Location; @@ -61,7 +61,7 @@ public class ServerToNodeMetadata implements Function { protected Logger logger = Logger.NULL; protected final Supplier location; - protected final Map serverToNodeState; + protected final Map serverToNodeStatus; protected final Supplier> images; protected final Supplier> hardwares; protected final GroupNamingConvention nodeNamingConvention; @@ -93,12 +93,12 @@ public class ServerToNodeMetadata implements Function { } @Inject - ServerToNodeMetadata(Map serverStateToNodeState, + ServerToNodeMetadata(Map serverStateToNodeStatus, @Memoized Supplier> images, Supplier location, @Memoized Supplier> hardwares, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); - this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); + this.serverToNodeStatus = checkNotNull(serverStateToNodeStatus, "serverStateToNodeStatus"); this.images = checkNotNull(images, "images"); this.location = checkNotNull(location, "location"); this.hardwares = checkNotNull(hardwares, "hardwares"); @@ -117,7 +117,7 @@ public class ServerToNodeMetadata implements Function { builder.imageId(from.getImageId() + ""); builder.operatingSystem(parseOperatingSystem(from)); builder.hardware(parseHardware(from)); - builder.state(serverToNodeState.get(from.getStatus())); + builder.status(serverToNodeStatus.get(from.getStatus())); builder.publicAddresses(from.getAddresses().getPublicAddresses()); builder.privateAddresses(from.getAddresses().getPrivateAddresses()); return builder.build(); diff --git a/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java b/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java index b39995a26b..74c69d381d 100644 --- a/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java +++ b/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java @@ -30,7 +30,7 @@ public class CloudServersComputeServiceContextModuleTest { public void testAllStatusCovered() { for (ServerStatus state : ServerStatus.values()) { - assert CloudServersComputeServiceContextModule.serverToNodeState.containsKey(state) : state; + assert CloudServersComputeServiceContextModule.serverToNodeStatus.containsKey(state) : state; } } diff --git a/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadataTest.java b/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadataTest.java index 855603afb8..e2665c1647 100644 --- a/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadataTest.java +++ b/apis/cloudservers/src/test/java/org/jclouds/cloudservers/compute/functions/ServerToNodeMetadataTest.java @@ -32,12 +32,12 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.VolumeBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -60,12 +60,12 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareNotFound() { - Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.serverToNodeStatus; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, Suppliers.> ofInstance(images), Suppliers + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.> ofInstance(images), Suppliers .ofInstance(provider), Suppliers.> ofInstance(hardwares), namingConvention); NodeMetadata metadata = parser.apply(server); @@ -73,7 +73,7 @@ public class ServerToNodeMetadataTest { assertEquals( metadata, new NodeMetadataBuilder() - .state(NodeState.PENDING) + .status(Status.PENDING) .publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131")) .privateAddresses(ImmutableSet.of("10.176.42.16")) .imageId("2") @@ -91,13 +91,13 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageFoundAndHardwareNotFound() { - Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.serverToNodeStatus; org.jclouds.compute.domain.Image jcImage = CloudServersImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, Suppliers.> ofInstance(images), Suppliers + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.> ofInstance(images), Suppliers .ofInstance(provider), Suppliers.> ofInstance(hardwares), namingConvention); NodeMetadata metadata = parser.apply(server); @@ -105,7 +105,7 @@ public class ServerToNodeMetadataTest { assertEquals( metadata, new NodeMetadataBuilder() - .state(NodeState.PENDING) + .status(Status.PENDING) .publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131")) .privateAddresses(ImmutableSet.of("10.176.42.16")) .imageId("2") @@ -126,12 +126,12 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareFound() { - Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.serverToNodeStatus; Set images = ImmutableSet.of(CloudServersImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, Suppliers.> ofInstance(images), Suppliers + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.> ofInstance(images), Suppliers .ofInstance(provider), Suppliers.> ofInstance(hardwares), namingConvention); NodeMetadata metadata = parser.apply(server); @@ -139,7 +139,7 @@ public class ServerToNodeMetadataTest { assertEquals( metadata, new NodeMetadataBuilder() - .state(NodeState.PENDING) + .status(Status.PENDING) .publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131")) .privateAddresses(ImmutableSet.of("10.176.42.16")) .imageId("2") diff --git a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java index d4f5dbd84f..5e131e6f30 100644 --- a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java +++ b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java @@ -38,10 +38,10 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.VolumeBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -60,13 +60,13 @@ import com.google.common.util.concurrent.UncheckedExecutionException; */ @Singleton public class ServerInfoToNodeMetadata implements Function { - public static final Map serverStatusToNodeState = ImmutableMap - . builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)// - .put(ServerStatus.STOPPED, NodeState.SUSPENDED)// - .put(ServerStatus.PAUSED, NodeState.SUSPENDED)// - .put(ServerStatus.DUMPED, NodeState.PENDING)// - .put(ServerStatus.DEAD, NodeState.TERMINATED)// - .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + public static final Map serverStatusToNodeStatus = ImmutableMap + . builder().put(ServerStatus.ACTIVE, Status.RUNNING)// + .put(ServerStatus.STOPPED, Status.SUSPENDED)// + .put(ServerStatus.PAUSED, Status.SUSPENDED)// + .put(ServerStatus.DUMPED, Status.PENDING)// + .put(ServerStatus.DEAD, Status.TERMINATED)// + .put(ServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED)// .build(); private final Function getImageIdFromServer; @@ -104,7 +104,7 @@ public class ServerInfoToNodeMetadata implements Function of(from.getVnc().getIp())); builder.privateAddresses(ImmutableSet. of()); return builder.build(); diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java index 8c551f66f7..193f3812bd 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java @@ -41,8 +41,8 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Processor; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.rest.ResourceNotFoundException; @@ -64,17 +64,17 @@ import com.google.common.util.concurrent.UncheckedExecutionException; @Singleton public class VirtualMachineToNodeMetadata implements Function { - public static final Map vmStateToNodeState = ImmutableMap - . builder().put(VirtualMachine.State.STARTING, NodeState.PENDING) - .put(VirtualMachine.State.RUNNING, NodeState.RUNNING).put(VirtualMachine.State.STOPPING, NodeState.PENDING) - .put(VirtualMachine.State.STOPPED, NodeState.SUSPENDED) - .put(VirtualMachine.State.DESTROYED, NodeState.TERMINATED) - .put(VirtualMachine.State.EXPUNGING, NodeState.TERMINATED) - .put(VirtualMachine.State.MIGRATING, NodeState.PENDING).put(VirtualMachine.State.ERROR, NodeState.ERROR) - .put(VirtualMachine.State.UNKNOWN, NodeState.UNRECOGNIZED) + public static final Map vmStateToNodeStatus = ImmutableMap + . builder().put(VirtualMachine.State.STARTING, Status.PENDING) + .put(VirtualMachine.State.RUNNING, Status.RUNNING).put(VirtualMachine.State.STOPPING, Status.PENDING) + .put(VirtualMachine.State.STOPPED, Status.SUSPENDED) + .put(VirtualMachine.State.DESTROYED, Status.TERMINATED) + .put(VirtualMachine.State.EXPUNGING, Status.TERMINATED) + .put(VirtualMachine.State.MIGRATING, Status.PENDING).put(VirtualMachine.State.ERROR, Status.ERROR) + .put(VirtualMachine.State.UNKNOWN, Status.UNRECOGNIZED) // TODO: is this really a state? - .put(VirtualMachine.State.SHUTDOWNED, NodeState.PENDING) - .put(VirtualMachine.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + .put(VirtualMachine.State.SHUTDOWNED, Status.PENDING) + .put(VirtualMachine.State.UNRECOGNIZED, Status.UNRECOGNIZED).build(); private final FindLocationForVirtualMachine findLocationForVirtualMachine; private final FindImageForVirtualMachine findImageForVirtualMachine; @@ -123,7 +123,7 @@ public class VirtualMachineToNodeMetadata implements Function publicAddresses = newHashSet(), privateAddresses = newHashSet(); if (from.getIPAddress() != null) { diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadataTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadataTest.java index d6597a3a83..ca89526200 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadataTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadataTest.java @@ -36,7 +36,7 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.domain.Location; @@ -87,7 +87,7 @@ public class VirtualMachineToNodeMetadataTest { assertEquals( node.toString(), new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3-54") - .location(ZoneToLocationTest.one).state(NodeState.PENDING).hostname("i-3-54-VM") + .location(ZoneToLocationTest.one).status(Status.PENDING).hostname("i-3-54-VM") .privateAddresses(ImmutableSet.of("10.1.1.18")).publicAddresses(ImmutableSet.of("1.1.1.1")) .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, "XenServer")) .imageId(TemplateToImageTest.one.getId()) @@ -150,7 +150,7 @@ public class VirtualMachineToNodeMetadataTest { assertEquals( node.toString(), new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3-54") - .location(ZoneToLocationTest.one).state(NodeState.PENDING).hostname("i-3-54-VM") + .location(ZoneToLocationTest.one).status(Status.PENDING).hostname("i-3-54-VM") .privateAddresses(ImmutableSet.of()) .publicAddresses(ImmutableSet.of("1.1.1.5")) .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, "XenServer")) @@ -186,7 +186,7 @@ public class VirtualMachineToNodeMetadataTest { assertEquals( node.toString(), new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3-54") - .location(ZoneToLocationTest.one).state(NodeState.PENDING).hostname("i-3-54-VM") + .location(ZoneToLocationTest.one).status(Status.PENDING).hostname("i-3-54-VM") .privateAddresses(ImmutableSet.of("10.1.1.18")) .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, "XenServer")) .imageId(TemplateToImageTest.one.getId()) diff --git a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java index 175d8e27bb..188ce1d2a2 100644 --- a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java +++ b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java @@ -34,8 +34,8 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.deltacloud.domain.Instance; @@ -54,11 +54,11 @@ import com.google.common.collect.Iterables; @Singleton public class InstanceToNodeMetadata implements Function { - public static final Map instanceToNodeState = ImmutableMap - . builder().put(Instance.State.STOPPED, NodeState.SUSPENDED) - .put(Instance.State.RUNNING, NodeState.RUNNING).put(Instance.State.PENDING, NodeState.PENDING) - .put(Instance.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(Instance.State.SHUTTING_DOWN, NodeState.PENDING) - .put(Instance.State.START, NodeState.PENDING).build(); + public static final Map instanceToNodeStatus = ImmutableMap + . builder().put(Instance.State.STOPPED, Status.SUSPENDED) + .put(Instance.State.RUNNING, Status.RUNNING).put(Instance.State.PENDING, Status.PENDING) + .put(Instance.State.UNRECOGNIZED, Status.UNRECOGNIZED).put(Instance.State.SHUTTING_DOWN, Status.PENDING) + .put(Instance.State.START, Status.PENDING).build(); @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) @@ -155,7 +155,7 @@ public class InstanceToNodeMetadata implements Function builder.imageId(from.getImage().toASCIIString()); builder.operatingSystem(parseOperatingSystem(from)); builder.hardware(parseHardware(from)); - builder.state(instanceToNodeState.get(from.getState())); + builder.status(instanceToNodeStatus.get(from.getState())); builder.publicAddresses(from.getPublicAddresses()); builder.privateAddresses(from.getPrivateAddresses()); return builder.build(); diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2ComputeServiceDependenciesModule.java b/apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2ComputeServiceDependenciesModule.java index b236189627..d1ed6b4835 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2ComputeServiceDependenciesModule.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2ComputeServiceDependenciesModule.java @@ -31,8 +31,8 @@ import javax.inject.Singleton; import org.jclouds.compute.ComputeService; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; @@ -79,17 +79,17 @@ import com.google.inject.name.Names; */ public class EC2ComputeServiceDependenciesModule extends AbstractModule { - public static final Map instanceToNodeState = ImmutableMap - . builder().put(InstanceState.PENDING, NodeState.PENDING).put( - InstanceState.RUNNING, NodeState.RUNNING).put(InstanceState.SHUTTING_DOWN, NodeState.PENDING).put( - InstanceState.TERMINATED, NodeState.TERMINATED).put(InstanceState.STOPPING, NodeState.PENDING) - .put(InstanceState.STOPPED, NodeState.SUSPENDED).put(InstanceState.UNRECOGNIZED, NodeState.UNRECOGNIZED) + public static final Map instanceToNodeStatus = ImmutableMap + . builder().put(InstanceState.PENDING, Status.PENDING).put( + InstanceState.RUNNING, Status.RUNNING).put(InstanceState.SHUTTING_DOWN, Status.PENDING).put( + InstanceState.TERMINATED, Status.TERMINATED).put(InstanceState.STOPPING, Status.PENDING) + .put(InstanceState.STOPPED, Status.SUSPENDED).put(InstanceState.UNRECOGNIZED, Status.UNRECOGNIZED) .build(); @Singleton @Provides - Map provideServerToNodeState() { - return instanceToNodeState; + Map provideServerToNodeStatus() { + return instanceToNodeStatus; } @Override diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java index fa66954a23..a037f31b98 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java @@ -24,9 +24,9 @@ import static com.google.common.collect.Iterables.filter; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; +import java.util.Map.Entry; import javax.annotation.Resource; import javax.inject.Singleton; @@ -37,8 +37,8 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Credentials; @@ -60,10 +60,10 @@ import com.google.common.base.Supplier; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSet.Builder; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableSet.Builder; import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.inject.Inject; @@ -80,18 +80,18 @@ public class RunningInstanceToNodeMetadata implements Function> hardware; protected final Supplier> imageMap; protected final Map credentialStore; - protected final Map instanceToNodeState; + protected final Map instanceToNodeStatus; protected final GroupNamingConvention.Factory namingConvention; @Inject - protected RunningInstanceToNodeMetadata(Map instanceToNodeState, + protected RunningInstanceToNodeMetadata(Map instanceToNodeStatus, Map credentialStore, Supplier> imageMap, @Memoized Supplier> locations, @Memoized Supplier> hardware, GroupNamingConvention.Factory namingConvention) { this.locations = checkNotNull(locations, "locations"); this.hardware = checkNotNull(hardware, "hardware"); this.imageMap = checkNotNull(imageMap, "imageMap"); - this.instanceToNodeState = checkNotNull(instanceToNodeState, "instanceToNodeState"); + this.instanceToNodeStatus = checkNotNull(instanceToNodeStatus, "instanceToNodeStatus"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.namingConvention = checkNotNull(namingConvention, "namingConvention"); } @@ -114,7 +114,7 @@ public class RunningInstanceToNodeMetadata implements Function of(), ImmutableSet . of(), ImmutableSet. of(), ImmutableMap. of()); - assertEquals(parser.apply(instance), new NodeMetadataBuilder().state(NodeState.RUNNING).publicAddresses( + assertEquals(parser.apply(instance), new NodeMetadataBuilder().status(Status.RUNNING).publicAddresses( ImmutableSet. of()).privateAddresses(ImmutableSet.of("10.1.1.1")).id("us-east-1/id").imageId( "us-east-1/image").providerId("id").build()); } @@ -94,7 +94,7 @@ public class RunningInstanceToNodeMetadataTest { RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet . of(), ImmutableSet. of(), ImmutableMap. of()); - assertEquals(parser.apply(instance), new NodeMetadataBuilder().state(NodeState.RUNNING).privateAddresses( + assertEquals(parser.apply(instance), new NodeMetadataBuilder().status(Status.RUNNING).privateAddresses( ImmutableSet. of()).publicAddresses(ImmutableSet.of("1.1.1.1")).id("us-east-1/id").imageId( "us-east-1/image").providerId("id").build()); } @@ -115,7 +115,7 @@ public class RunningInstanceToNodeMetadataTest { assertEquals( parser.apply(server), - new NodeMetadataBuilder().state(NodeState.RUNNING).hostname("ip-10-243-42-70") + new NodeMetadataBuilder().status(Status.RUNNING).hostname("ip-10-243-42-70") .publicAddresses(ImmutableSet. of()).privateAddresses(ImmutableSet.of("10.243.42.70")) .publicAddresses(ImmutableSet.of("174.129.81.68")).credentials(creds) .imageId("us-east-1/ami-82e4b5c7").id("us-east-1/i-0799056f").providerId("i-0799056f").build()); @@ -129,7 +129,7 @@ public class RunningInstanceToNodeMetadataTest { RunningInstance server = firstInstanceFromResource("/describe_instances_running.xml"); assertEquals(parser.apply(server), - new NodeMetadataBuilder().hostname("ip-10-243-42-70").state(NodeState.RUNNING) + new NodeMetadataBuilder().hostname("ip-10-243-42-70").status(Status.RUNNING) .publicAddresses(ImmutableSet. of()).privateAddresses(ImmutableSet.of("10.243.42.70")) .publicAddresses(ImmutableSet.of("174.129.81.68")).imageId("us-east-1/ami-82e4b5c7") .id("us-east-1/i-0799056f").providerId("i-0799056f").build()); @@ -141,7 +141,7 @@ public class RunningInstanceToNodeMetadataTest { ImmutableSet. of(), ImmutableMap. of()); RunningInstance server = firstInstanceFromResource("/describe_instances_running.xml"); - NodeMetadata expected = new NodeMetadataBuilder().hostname("ip-10-243-42-70").state(NodeState.RUNNING) + NodeMetadata expected = new NodeMetadataBuilder().hostname("ip-10-243-42-70").status(Status.RUNNING) .privateAddresses(ImmutableSet.of("10.243.42.70")).publicAddresses(ImmutableSet.of("174.129.81.68")) .imageId("us-east-1/ami-82e4b5c7").id("us-east-1/i-0799056f").providerId("i-0799056f") .location(provider).build(); @@ -159,7 +159,7 @@ public class RunningInstanceToNodeMetadataTest { assertEquals( parser.apply(server), new NodeMetadataBuilder() - .state(NodeState.RUNNING) + .status(Status.RUNNING) .hostname("ip-10-243-42-70") .privateAddresses(ImmutableSet.of("10.243.42.70")) .publicAddresses(ImmutableSet.of("174.129.81.68")) @@ -182,7 +182,7 @@ public class RunningInstanceToNodeMetadataTest { parser.apply(server), new NodeMetadataBuilder() .hostname("ip-10-243-42-70") - .state(NodeState.RUNNING) + .status(Status.RUNNING) .privateAddresses(ImmutableSet.of("10.243.42.70")) .publicAddresses(ImmutableSet.of("174.129.81.68")) .imageId("us-east-1/ami-82e4b5c7") @@ -210,13 +210,13 @@ public class RunningInstanceToNodeMetadataTest { RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), ImmutableSet .of(provider), ImmutableMap. of(), - EC2ComputeServiceDependenciesModule.instanceToNodeState, instanceToImage); + EC2ComputeServiceDependenciesModule.instanceToNodeStatus, instanceToImage); RunningInstance server = firstInstanceFromResource("/describe_instances_running.xml"); assertEquals( parser.apply(server), - new NodeMetadataBuilder().hostname("ip-10-243-42-70").state(NodeState.RUNNING) + new NodeMetadataBuilder().hostname("ip-10-243-42-70").status(Status.RUNNING) .privateAddresses(ImmutableSet.of("10.243.42.70")).publicAddresses(ImmutableSet.of("174.129.81.68")) .imageId("us-east-1/ami-82e4b5c7").id("us-east-1/i-0799056f").providerId("i-0799056f") .hardware(m1_small().build()).location(provider).build()); @@ -245,7 +245,7 @@ public class RunningInstanceToNodeMetadataTest { protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, final ImmutableSet locations, final Set images, Map credentialStore) { - Map instanceToNodeState = EC2ComputeServiceDependenciesModule.instanceToNodeState; + Map instanceToNodeStatus = EC2ComputeServiceDependenciesModule.instanceToNodeStatus; CacheLoader getRealImage = new CacheLoader() { @@ -255,7 +255,7 @@ public class RunningInstanceToNodeMetadataTest { } }; LoadingCache instanceToImage = CacheBuilder.newBuilder().build(getRealImage); - return createNodeParser(hardware, locations, credentialStore, instanceToNodeState, instanceToImage); + return createNodeParser(hardware, locations, credentialStore, instanceToNodeStatus, instanceToImage); } private void checkGroupName(RunningInstance instance) { @@ -266,7 +266,7 @@ public class RunningInstanceToNodeMetadataTest { private RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, final ImmutableSet locations, Map credentialStore, - Map instanceToNodeState, LoadingCache instanceToImage) { + Map instanceToNodeStatus, LoadingCache instanceToImage) { Supplier> locationSupplier = new Supplier>() { @Override @@ -293,7 +293,7 @@ public class RunningInstanceToNodeMetadataTest { }).getInstance(GroupNamingConvention.Factory.class); - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(instanceToNodeState, credentialStore, + RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(instanceToNodeStatus, credentialStore, Suppliers.> ofInstance(instanceToImage), locationSupplier, hardwareSupplier, namingConvention); return parser; diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/EC2CreateNodesInGroupThenAddToSetTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/EC2CreateNodesInGroupThenAddToSetTest.java index 400c954a57..0bf4fe3802 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/EC2CreateNodesInGroupThenAddToSetTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/EC2CreateNodesInGroupThenAddToSetTest.java @@ -34,9 +34,9 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.predicates.AtomicNodeRunning; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.util.ComputeUtils; @@ -78,7 +78,7 @@ public class EC2CreateNodesInGroupThenAddToSetTest { String imageId = "ami1"; String instanceCreatedId = "instance1"; NodeMetadata nodeMetadata = new NodeMetadataBuilder().id(region + "/" + instanceCreatedId) - .providerId(instanceCreatedId).state(NodeState.RUNNING).build(); + .providerId(instanceCreatedId).status(Status.RUNNING).build(); // setup mocks TemplateBuilder templateBuilder = createMock(TemplateBuilder.class); EC2CreateNodesInGroupThenAddToSet strategy = setupStrategy(templateBuilder, nodeMetadata); @@ -190,7 +190,7 @@ public class EC2CreateNodesInGroupThenAddToSetTest { String imageId = "ami1"; String instanceCreatedId = "instance1"; NodeMetadata nodeMetadata = new NodeMetadataBuilder().id(region + "/" + instanceCreatedId) - .providerId(instanceCreatedId).state(NodeState.RUNNING).build(); + .providerId(instanceCreatedId).status(Status.RUNNING).build(); // setup mocks TemplateBuilder templateBuilder = createMock(TemplateBuilder.class); diff --git a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java index ceac0e90a9..59d2658660 100644 --- a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java +++ b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java @@ -34,10 +34,10 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.VolumeBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.elasticstack.domain.Device; @@ -61,13 +61,13 @@ import com.google.common.util.concurrent.UncheckedExecutionException; */ @Singleton public class ServerInfoToNodeMetadata implements Function { - public static final Map serverStatusToNodeState = ImmutableMap - . builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)// - .put(ServerStatus.STOPPED, NodeState.SUSPENDED)// - .put(ServerStatus.PAUSED, NodeState.SUSPENDED)// - .put(ServerStatus.DUMPED, NodeState.PENDING)// - .put(ServerStatus.DEAD, NodeState.TERMINATED)// - .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + public static final Map serverStatusToNodeStatus = ImmutableMap + . builder().put(ServerStatus.ACTIVE, Status.RUNNING)// + .put(ServerStatus.STOPPED, Status.SUSPENDED)// + .put(ServerStatus.PAUSED, Status.SUSPENDED)// + .put(ServerStatus.DUMPED, Status.PENDING)// + .put(ServerStatus.DEAD, Status.TERMINATED)// + .put(ServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED)// .build(); private final Function getImageIdFromServer; @@ -106,7 +106,7 @@ public class ServerInfoToNodeMetadata implements Function of(from.getNics().get(0).getDhcp())); builder.privateAddresses(ImmutableSet. of()); return builder.build(); diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java index 6ac995e84e..8d2d1c720d 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java @@ -27,8 +27,8 @@ import org.jclouds.compute.config.ComputeServiceAdapterContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.internal.BaseComputeService; import org.jclouds.domain.Location; import org.jclouds.functions.IdentityFunction; @@ -80,28 +80,28 @@ public class NovaComputeServiceContextModule extends } @VisibleForTesting - public static final Map serverToNodeState = ImmutableMap - . builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)// - .put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)// - .put(ServerStatus.DELETED, NodeState.TERMINATED)// - .put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)// - .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// - .put(ServerStatus.RESIZE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// - .put(ServerStatus.RESCUE, NodeState.PENDING)// - .put(ServerStatus.BUILD, NodeState.PENDING)// - .put(ServerStatus.PASSWORD, NodeState.PENDING)// - .put(ServerStatus.REBUILD, NodeState.PENDING)// - .put(ServerStatus.DELETE_IP, NodeState.PENDING)// - .put(ServerStatus.REBOOT, NodeState.PENDING)// - .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// - .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// - .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + public static final Map serverToNodeStatus = ImmutableMap + . builder().put(ServerStatus.ACTIVE, Status.RUNNING)// + .put(ServerStatus.SUSPENDED, Status.SUSPENDED)// + .put(ServerStatus.DELETED, Status.TERMINATED)// + .put(ServerStatus.QUEUE_RESIZE, Status.PENDING)// + .put(ServerStatus.PREP_RESIZE, Status.PENDING)// + .put(ServerStatus.RESIZE, Status.PENDING)// + .put(ServerStatus.VERIFY_RESIZE, Status.PENDING)// + .put(ServerStatus.RESCUE, Status.PENDING)// + .put(ServerStatus.BUILD, Status.PENDING)// + .put(ServerStatus.PASSWORD, Status.PENDING)// + .put(ServerStatus.REBUILD, Status.PENDING)// + .put(ServerStatus.DELETE_IP, Status.PENDING)// + .put(ServerStatus.REBOOT, Status.PENDING)// + .put(ServerStatus.HARD_REBOOT, Status.PENDING)// + .put(ServerStatus.UNKNOWN, Status.UNRECOGNIZED)// + .put(ServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED).build(); @Singleton @Provides - Map provideServerToNodeState() { - return serverToNodeState; + Map provideServerToNodeStatus() { + return serverToNodeStatus; } } diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java index bc6b567f08..983c39dcc6 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java @@ -34,7 +34,7 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Location; @@ -60,7 +60,7 @@ public class ServerToNodeMetadata implements Function { protected Logger logger = Logger.NULL; protected final Supplier location; - protected final Map serverToNodeState; + protected final Map serverToNodeStatus; protected final Supplier> images; protected final Supplier> hardwares; protected final GroupNamingConvention nodeNamingConvention; @@ -92,12 +92,12 @@ public class ServerToNodeMetadata implements Function { } @Inject - ServerToNodeMetadata(Map serverStateToNodeState, + ServerToNodeMetadata(Map serverStateToNodeStatus, @Memoized Supplier> images, Supplier location, @Memoized Supplier> hardwares, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); - this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); + this.serverToNodeStatus = checkNotNull(serverStateToNodeStatus, "serverStateToNodeStatus"); this.images = checkNotNull(images, "images"); this.location = checkNotNull(location, "location"); this.hardwares = checkNotNull(hardwares, "hardwares"); @@ -118,7 +118,7 @@ public class ServerToNodeMetadata implements Function { builder.operatingSystem(image.getOperatingSystem()); } builder.hardware(parseHardware(from)); - builder.state(serverToNodeState.get(from.getStatus())); + builder.status(serverToNodeStatus.get(from.getStatus())); builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction())); builder.privateAddresses(Iterables.transform(from.getAddresses().getPrivateAddresses(), Address.newAddress2StringFunction())); builder.uri(from.getURI()); diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModuleTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModuleTest.java index fe9a759e23..a826c20695 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModuleTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModuleTest.java @@ -30,7 +30,7 @@ public class NovaComputeServiceContextModuleTest { public void testAllStatusCovered() { for (ServerStatus state : ServerStatus.values()) { - assert NovaComputeServiceContextModule.serverToNodeState.containsKey(state) : state; + assert NovaComputeServiceContextModule.serverToNodeStatus.containsKey(state) : state; } } diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index c0d8909b7c..ffb57fa254 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -31,12 +31,12 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.VolumeBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -64,12 +64,12 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeState = NovaComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeStatus = NovaComputeServiceContextModule.serverToNodeStatus; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.> ofInstance(images), Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares), namingConvention); @@ -83,7 +83,7 @@ public class ServerToNodeMetadataTest { private NodeMetadataBuilder newNodeMetadataBuilder() throws URISyntaxException { return new NodeMetadataBuilder() - .state(NodeState.PENDING) + .status(Status.PENDING) .publicAddresses(ImmutableSet.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")) .privateAddresses(ImmutableSet.of("10.176.42.16", "::babe:10.176.42.16")) .id("1234") @@ -100,13 +100,13 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeState = NovaComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeStatus = NovaComputeServiceContextModule.serverToNodeStatus; org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.> ofInstance(images), Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares), namingConvention); @@ -125,12 +125,12 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeState = NovaComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeStatus = NovaComputeServiceContextModule.serverToNodeStatus; Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers.> ofInstance(images), Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares), namingConvention); diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java index 5cb74c3a09..0c8433be2b 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java @@ -103,7 +103,7 @@ public class ServerInZoneToNodeMetadata implements Function VAPPSTATUS_TO_NODESTATE = ImmutableMap. builder().put( - Status.OFF, NodeState.SUSPENDED).put(Status.ON, NodeState.RUNNING).put(Status.RESOLVED, NodeState.PENDING) - .put(Status.ERROR, NodeState.ERROR).put(Status.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(Status.DEPLOYED, - NodeState.PENDING).put(Status.INCONSISTENT, NodeState.PENDING).put(Status.UNKNOWN, - NodeState.UNRECOGNIZED).put(Status.MIXED, NodeState.PENDING).put(Status.WAITING_FOR_INPUT, - NodeState.PENDING).put(Status.SUSPENDED, NodeState.SUSPENDED).put(Status.UNRESOLVED, - NodeState.PENDING).build(); + public static final Map VAPPSTATUS_TO_NODESTATE = ImmutableMap. builder().put( + Status.OFF, NodeMetadata.Status.SUSPENDED).put(Status.ON, NodeMetadata.Status.RUNNING).put(Status.RESOLVED, NodeMetadata.Status.PENDING) + .put(Status.ERROR, NodeMetadata.Status.ERROR).put(Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).put(Status.DEPLOYED, + NodeMetadata.Status.PENDING).put(Status.INCONSISTENT, NodeMetadata.Status.PENDING).put(Status.UNKNOWN, + NodeMetadata.Status.UNRECOGNIZED).put(Status.MIXED, NodeMetadata.Status.PENDING).put(Status.WAITING_FOR_INPUT, + NodeMetadata.Status.PENDING).put(Status.SUSPENDED, NodeMetadata.Status.SUSPENDED).put(Status.UNRESOLVED, + NodeMetadata.Status.PENDING).build(); @Singleton @Provides - protected Map provideVAppStatusToNodeState() { + protected Map provideVAppStatusToNodeStatus() { return VAPPSTATUS_TO_NODESTATE; } diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java index 62bfc686d4..9e11ae4026 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java @@ -35,7 +35,6 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Credentials; import org.jclouds.logging.Logger; @@ -55,19 +54,19 @@ public class VAppToNodeMetadata implements Function { protected final FindLocationForResource findLocationForResourceInVDC; protected final Function hardwareForVApp; - protected final Map vAppStatusToNodeState; + protected final Map vAppStatusToNodeStatus; protected final Map credentialStore; protected final GroupNamingConvention nodeNamingConvention; @Inject - protected VAppToNodeMetadata(Map vAppStatusToNodeState, Map credentialStore, + protected VAppToNodeMetadata(Map vAppStatusToNodeStatus, Map credentialStore, FindLocationForResource findLocationForResourceInVDC, Function hardwareForVApp, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); this.hardwareForVApp = checkNotNull(hardwareForVApp, "hardwareForVApp"); this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); - this.vAppStatusToNodeState = checkNotNull(vAppStatusToNodeState, "vAppStatusToNodeState"); + this.vAppStatusToNodeStatus = checkNotNull(vAppStatusToNodeStatus, "vAppStatusToNodeStatus"); } public NodeMetadata apply(VApp from) { @@ -80,7 +79,7 @@ public class VAppToNodeMetadata implements Function { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName())); builder.operatingSystem(toComputeOs(from, null)); builder.hardware(hardwareForVApp.apply(from)); - builder.state(vAppStatusToNodeState.get(from.getStatus())); + builder.status(vAppStatusToNodeStatus.get(from.getStatus())); Set addresses = getIpsFromVApp(from); builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE))); builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE)); diff --git a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java index f3d5df5188..6b335b26c2 100644 --- a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java +++ b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java @@ -31,7 +31,6 @@ import org.jclouds.cim.xml.ResourceAllocationSettingDataHandler; import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -101,7 +100,7 @@ public class VAppToNodeMetadataTest { @SuppressWarnings("unused") @Singleton @Provides - protected Map provideVAppStatusToNodeState() { + protected Map provideVAppStatusToNodeStatus() { return VCloudComputeServiceDependenciesModule.VAPPSTATUS_TO_NODESTATE; } diff --git a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java index 77f49a0f30..45060ad8c4 100644 --- a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java +++ b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java @@ -25,9 +25,9 @@ import static org.jclouds.trmk.vcloud_0_8.options.AddInternetServiceOptions.Buil import java.net.URI; import java.util.Map; -import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; +import java.util.Map.Entry; import javax.annotation.Resource; import javax.inject.Inject; @@ -36,7 +36,7 @@ import javax.inject.Provider; import javax.inject.Singleton; import org.jclouds.compute.ComputeServiceAdapter; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials; @@ -72,18 +72,18 @@ public class TerremarkVCloudComputeClient { protected final TerremarkVCloudClient client; protected final Provider passwordGenerator; protected final InternetServiceAndPublicIpAddressSupplier internetServiceAndPublicIpAddressSupplier; - protected final Map vAppStatusToNodeState; + protected final Map vAppStatusToNodeStatus; protected final Predicate taskTester; @Inject protected TerremarkVCloudComputeClient(TerremarkVCloudClient client, @Named("PASSWORD") Provider passwordGenerator, Predicate successTester, - Map vAppStatusToNodeState, Map credentialStore, + Map vAppStatusToNodeStatus, Map credentialStore, InternetServiceAndPublicIpAddressSupplier internetServiceAndPublicIpAddressSupplier) { this.client = client; this.passwordGenerator = passwordGenerator; this.internetServiceAndPublicIpAddressSupplier = internetServiceAndPublicIpAddressSupplier; - this.vAppStatusToNodeState = vAppStatusToNodeState; + this.vAppStatusToNodeStatus = vAppStatusToNodeStatus; this.taskTester = successTester; } diff --git a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java index 4788da82b6..b448da1041 100644 --- a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java +++ b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java @@ -28,7 +28,6 @@ import org.jclouds.compute.ComputeService; import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; @@ -60,15 +59,16 @@ import com.google.inject.TypeLiteral; public class TerremarkVCloudComputeServiceContextModule extends BaseComputeServiceContextModule { @VisibleForTesting - public static final Map VAPPSTATUS_TO_NODESTATE = ImmutableMap. builder() - .put(Status.OFF, NodeState.SUSPENDED).put(Status.ON, NodeState.RUNNING) - .put(Status.RESOLVED, NodeState.PENDING).put(Status.UNRECOGNIZED, NodeState.UNRECOGNIZED) - .put(Status.DEPLOYED, NodeState.PENDING).put(Status.SUSPENDED, NodeState.SUSPENDED) - .put(Status.UNRESOLVED, NodeState.PENDING).build(); + public static final Map VAPPSTATUS_TO_NODESTATE = ImmutableMap + . builder().put(Status.OFF, NodeMetadata.Status.SUSPENDED).put(Status.ON, + NodeMetadata.Status.RUNNING).put(Status.RESOLVED, NodeMetadata.Status.PENDING).put( + Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).put(Status.DEPLOYED, + NodeMetadata.Status.PENDING).put(Status.SUSPENDED, NodeMetadata.Status.SUSPENDED).put( + Status.UNRESOLVED, NodeMetadata.Status.PENDING).build(); @Singleton @Provides - protected Map provideVAppStatusToNodeState() { + protected Map provideVAppStatusToNodeStatus() { return VAPPSTATUS_TO_NODESTATE; } diff --git a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/VAppToNodeMetadata.java b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/VAppToNodeMetadata.java index 966f9e6b66..95299cb588 100644 --- a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/VAppToNodeMetadata.java +++ b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/VAppToNodeMetadata.java @@ -32,7 +32,6 @@ import org.jclouds.compute.domain.CIMOperatingSystem; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.compute.util.ComputeServiceUtils; @@ -57,12 +56,12 @@ public class VAppToNodeMetadata implements Function { protected final Supplier> images; protected final FindLocationForResource findLocationForResourceInVDC; protected final HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp; - protected final Map vAppStatusToNodeState; + protected final Map vAppStatusToNodeStatus; protected final GroupNamingConvention nodeNamingConvention; @Inject protected VAppToNodeMetadata(TerremarkVCloudComputeClient computeClient, Map credentialStore, - Map vAppStatusToNodeState, HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, + Map vAppStatusToNodeStatus, HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, FindLocationForResource findLocationForResourceInVDC, @Memoized Supplier> images, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); @@ -71,7 +70,7 @@ public class VAppToNodeMetadata implements Function { this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.computeClient = checkNotNull(computeClient, "computeClient"); - this.vAppStatusToNodeState = checkNotNull(vAppStatusToNodeState, "vAppStatusToNodeState"); + this.vAppStatusToNodeStatus = checkNotNull(vAppStatusToNodeStatus, "vAppStatusToNodeStatus"); } @Override @@ -97,7 +96,7 @@ public class VAppToNodeMetadata implements Function { builder.operatingSystem(osBuilder.build()); } builder.hardware(hardwareForVCloudExpressVApp.apply(from)); - builder.state(vAppStatusToNodeState.get(from.getStatus())); + builder.status(vAppStatusToNodeStatus.get(from.getStatus())); builder.publicAddresses(computeClient.getPublicAddresses(from.getHref())); builder.privateAddresses(computeClient.getPrivateAddresses(from.getHref())); builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName())); diff --git a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClientTest.java b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClientTest.java index c8386fc85b..1ad5dc51f1 100644 --- a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClientTest.java +++ b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClientTest.java @@ -32,7 +32,7 @@ import java.util.Map; import javax.inject.Provider; import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials; import org.jclouds.trmk.vcloud_0_8.TerremarkVCloudClient; @@ -86,7 +86,7 @@ public class TerremarkVCloudComputeClientTest { expect(client.powerOnVApp(vappLocation)).andReturn(task); Predicate notFoundTester = createMock(Predicate.class); - Map vAppStatusToNodeState = createMock(Map.class); + Map vAppStatusToNodeStatus = createMock(Map.class); TerremarkVCloudComputeClient computeClient = new TerremarkVCloudComputeClient(client, new Provider() { @@ -96,7 +96,7 @@ public class TerremarkVCloudComputeClientTest { return "password"; } - }, successTester, vAppStatusToNodeState, credentialStore, supplier); + }, successTester, vAppStatusToNodeStatus, credentialStore, supplier); replay(vdc); replay(template); @@ -105,7 +105,7 @@ public class TerremarkVCloudComputeClientTest { replay(client); replay(successTester); replay(notFoundTester); - replay(vAppStatusToNodeState); + replay(vAppStatusToNodeStatus); NodeAndInitialCredentials response = computeClient.startAndReturnCredentials(vdcURI, templateURI, "name", new InstantiateVAppTemplateOptions()); @@ -120,6 +120,6 @@ public class TerremarkVCloudComputeClientTest { verify(client); verify(successTester); verify(notFoundTester); - verify(vAppStatusToNodeState); + verify(vAppStatusToNodeStatus); } } diff --git a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/CleanupOrphanKeysTest.java b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/CleanupOrphanKeysTest.java index 07d742ad45..13b56f8374 100644 --- a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/CleanupOrphanKeysTest.java +++ b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/CleanupOrphanKeysTest.java @@ -28,7 +28,7 @@ import java.net.URI; import java.util.Map; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.domain.Credentials; import org.jclouds.trmk.vcloud_0_8.compute.domain.OrgAndName; @@ -94,7 +94,7 @@ public class CleanupOrphanKeysTest { expect((Object) strategy.listNodes.listDetailsOnNodesMatching(parentLocationId(orgTag.getOrg().toASCIIString()))) .andReturn(ImmutableSet.of(nodeMetadata)); expect(nodeMetadata.getGroup()).andReturn(orgTag.getName()).atLeastOnce(); - expect(nodeMetadata.getState()).andReturn(NodeState.RUNNING).atLeastOnce(); + expect(nodeMetadata.getStatus()).andReturn(Status.RUNNING).atLeastOnce(); expectCleanupCredentialStore(strategy, nodeMetadata); // replay mocks @@ -121,7 +121,7 @@ public class CleanupOrphanKeysTest { expect((Object) strategy.listNodes.listDetailsOnNodesMatching(parentLocationId(orgTag.getOrg().toASCIIString()))) .andReturn(ImmutableSet.of(nodeMetadata)); expect(nodeMetadata.getGroup()).andReturn(orgTag.getName()).atLeastOnce(); - expect(nodeMetadata.getState()).andReturn(NodeState.TERMINATED).atLeastOnce(); + expect(nodeMetadata.getStatus()).andReturn(Status.TERMINATED).atLeastOnce(); strategy.deleteKeyPair.execute(orgTag); expectCleanupCredentialStore(strategy, nodeMetadata); diff --git a/compute/src/main/clojure/org/jclouds/compute2.clj b/compute/src/main/clojure/org/jclouds/compute2.clj index db3c4a6c89..8d9147ed8c 100644 --- a/compute/src/main/clojure/org/jclouds/compute2.clj +++ b/compute/src/main/clojure/org/jclouds/compute2.clj @@ -243,41 +243,41 @@ Here's an example of creating and running a small linux node in the group webser ([#^ComputeService compute pred command #^RunScriptOptions options] (.runScriptOnNodesMatching compute (to-predicate pred) command options))) -(defmacro state-predicate [node state] - `(= (.getState ~node) - (. org.jclouds.compute.domain.NodeState ~state))) +(defmacro status-predicate [node status] + `(= (.getStatus ~node) + (. org.jclouds.compute.domain.NodeMetadata$Status ~status))) (defn pending? "Predicate for the node being in transition" [#^NodeMetadata node] - (state-predicate node PENDING)) + (status-predicate node PENDING)) (defn running? "Predicate for the node being available for requests." [#^NodeMetadata node] - (state-predicate node RUNNING)) + (status-predicate node RUNNING)) (defn terminated? "Predicate for the node being halted." [#^NodeMetadata node] (or (= node nil) - (state-predicate node TERMINATED))) + (status-predicate node TERMINATED))) (defn suspended? "Predicate for the node being suspended." [#^NodeMetadata node] - (state-predicate node SUSPENDED)) + (status-predicate node SUSPENDED)) -(defn error-state? - "Predicate for the node being in an error state." +(defn error-status? + "Predicate for the node being in an error status." [#^NodeMetadata node] - (state-predicate node ERROR)) + (status-predicate node ERROR)) -(defn unrecognized-state? - "Predicate for the node being in an unrecognized state." +(defn unrecognized-status? + "Predicate for the node being in an unrecognized status." [#^NodeMetadata node] - (state-predicate node UNRECOGNIZED)) + (status-predicate node UNRECOGNIZED)) (defn in-group? "Returns a predicate fn which returns true if the node is in the given group, false otherwise" @@ -317,7 +317,7 @@ Here's an example of creating and running a small linux node in the group webser (define-accessors Template image hardware location options) (define-accessors Image version os-family os-description architecture) (define-accessors Hardware processors ram volumes) -(define-accessors NodeMetadata "node" credentials hardware state group) +(define-accessors NodeMetadata "node" credentials hardware status group) (def ^{:doc "TemplateBuilder functions" :private true} diff --git a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java index 311a651175..99dc468af4 100644 --- a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java @@ -29,7 +29,7 @@ import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.predicates.AtomicNodeRunning; import org.jclouds.compute.predicates.AtomicNodeSuspended; import org.jclouds.compute.predicates.ScriptStatusReturnsZero; -import org.jclouds.compute.predicates.TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse; +import org.jclouds.compute.predicates.AtomicNodeTerminated; import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.predicates.RetryablePredicate; @@ -56,7 +56,7 @@ public class ComputeServiceTimeoutsModule extends AbstractModule { @Provides @Singleton @Named("NODE_TERMINATED") - protected Predicate> serverTerminated(TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse stateTerminated, Timeouts timeouts) { + protected Predicate> serverTerminated(AtomicNodeTerminated stateTerminated, Timeouts timeouts) { return timeouts.nodeTerminated == 0 ? stateTerminated : new RetryablePredicate>(stateTerminated, timeouts.nodeTerminated); } diff --git a/compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataIncludingStatus.java b/compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataIncludingStatus.java new file mode 100644 index 0000000000..bce2067d90 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataIncludingStatus.java @@ -0,0 +1,32 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.compute.domain; + +/** + * @author Adrian Cole + */ +public interface ComputeMetadataIncludingStatus> extends ComputeMetadata { + + /** + * status of the resource + * @since 1.5 + */ + public S getStatus(); + +} diff --git a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java index 36343a7cbf..53f1dc1ab0 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java +++ b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java @@ -32,7 +32,36 @@ import com.google.inject.ImplementedBy; * @author Ivan Meredith */ @ImplementedBy(NodeMetadataImpl.class) -public interface NodeMetadata extends ComputeMetadata { +public interface NodeMetadata extends ComputeMetadataIncludingStatus { + + public static enum Status { + /** + * The node is in transition + */ + PENDING, + /** + * The node is visible, and in the process of being deleted. + */ + TERMINATED, + /** + * The node is deployed, but suspended or stopped. + */ + SUSPENDED, + /** + * The node is available for requests + */ + RUNNING, + /** + * There is an error on the node + */ + ERROR, + /** + * The state of the node is unrecognized. + */ + UNRECOGNIZED; + + } + /** *

note

hostname is something that is set in the operating system image, so this value, * if present, cannot be guaranteed on images not directly controlled by the cloud provider. @@ -75,8 +104,12 @@ public interface NodeMetadata extends ComputeMetadata { OperatingSystem getOperatingSystem(); /** - * Current State of the node + * Current State of the node; replaced by {@link #getStatus()} + *

Note

+ * will be removed in jclouds 1.6! + * @see #getStatus() */ + @Deprecated NodeState getState(); /** diff --git a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java index ff6ebf06b2..e33018c0e7 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java @@ -24,11 +24,10 @@ import java.net.URI; import java.util.Map; import java.util.Set; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.domain.internal.NodeMetadataImpl; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LoginCredentials; -import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.javax.annotation.Nullable; import com.google.common.collect.ImmutableSet; @@ -38,7 +37,7 @@ import com.google.common.collect.Sets; * @author Adrian Cole */ public class NodeMetadataBuilder extends ComputeMetadataBuilder { - private NodeState state; + private Status status; private Set publicAddresses = Sets.newLinkedHashSet(); private Set privateAddresses = Sets.newLinkedHashSet(); @Nullable @@ -63,9 +62,20 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder { this.loginPort = loginPort; return this; } - + + public NodeMetadataBuilder status(Status status) { + this.status = checkNotNull(status, "status"); + return this; + } + + /** + *

Note

+ * will be removed in jclouds 1.6! + * @see #status + */ + @Deprecated public NodeMetadataBuilder state(NodeState state) { - this.state = checkNotNull(state, "state"); + this.status = checkNotNull(state, "state").toStatus(); return this; } @@ -79,39 +89,11 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder { return this; } - /** - *

will be removed in jclouds 1.4.0

- * - * @see LoginCredentials#shouldAuthenticateSudo - */ - @Deprecated - public NodeMetadataBuilder adminPassword(@Nullable String adminPassword) { - if (adminPassword != null) { - Builder builder = credentials != null ? credentials.toBuilder() : LoginCredentials - .builder(); - builder.authenticateSudo(true); - builder.password(adminPassword); - this.credentials = builder.build(); - } - return this; - } - - /** - *

will be removed in jclouds 1.4.0

- * - * @see #credentials(LoginCredentials) - */ - @Deprecated - public NodeMetadataBuilder credentials(@Nullable Credentials credentials) { - return credentials(LoginCredentials.fromCredentials(credentials)); - } - public NodeMetadataBuilder credentials(@Nullable LoginCredentials credentials) { this.credentials = credentials; return this; } - public NodeMetadataBuilder group(@Nullable String group) { this.group = group; return this; @@ -180,14 +162,14 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder { @Override public NodeMetadata build() { return new NodeMetadataImpl(providerId, name, id, location, uri, userMetadata, tags, group, hardware, imageId, - os, state, loginPort, publicAddresses, privateAddresses, credentials, hostname); + os, status, loginPort, publicAddresses, privateAddresses, credentials, hostname); } public static NodeMetadataBuilder fromNodeMetadata(NodeMetadata node) { return new NodeMetadataBuilder().providerId(node.getProviderId()).name(node.getName()).id(node.getId()).location( node.getLocation()).uri(node.getUri()).userMetadata(node.getUserMetadata()).tags(node.getTags()).group( node.getGroup()).hardware(node.getHardware()).imageId(node.getImageId()).operatingSystem( - node.getOperatingSystem()).state(node.getState()).loginPort(node.getLoginPort()).publicAddresses( + node.getOperatingSystem()).status(node.getStatus()).loginPort(node.getLoginPort()).publicAddresses( node.getPublicAddresses()).privateAddresses(node.getPrivateAddresses()).credentials(node.getCredentials()).hostname(node.getHostname()); } diff --git a/compute/src/main/java/org/jclouds/compute/domain/NodeState.java b/compute/src/main/java/org/jclouds/compute/domain/NodeState.java index 07dddea847..e0bd5a698d 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/NodeState.java +++ b/compute/src/main/java/org/jclouds/compute/domain/NodeState.java @@ -18,35 +18,84 @@ */ package org.jclouds.compute.domain; +import org.jclouds.compute.domain.NodeMetadata.Status; + /** - * Indicates the status of a node + * Indicates the status of a node. Replaced by {@link Status} * * @author Adrian Cole + * @see NodeMetadata#getStatus() */ +@Deprecated public enum NodeState { /** * The node is in transition + * + * @see Status#PENDING */ PENDING, /** * The node is visible, and in the process of being deleted. + * + * @see Status#TERMINATED */ TERMINATED, /** * The node is deployed, but suspended or stopped. + * + * @see Status#SUSPENDED */ SUSPENDED, /** * The node is available for requests + * + * @see Status#RUNNING */ RUNNING, /** * There is an error on the node + * + * @see Status#ERROR */ ERROR, /** * The state of the node is unrecognized. + * + * @see Status#UNRECOGNIZED */ UNRECOGNIZED; + public static NodeState from(Status in) { + switch (in) { + case PENDING: + return PENDING; + case TERMINATED: + return TERMINATED; + case SUSPENDED: + return SUSPENDED; + case RUNNING: + return RUNNING; + case ERROR: + return ERROR; + default: + return UNRECOGNIZED; + } + } + + public Status toStatus() { + switch (this) { + case PENDING: + return Status.PENDING; + case TERMINATED: + return Status.TERMINATED; + case SUSPENDED: + return Status.SUSPENDED; + case RUNNING: + return Status.RUNNING; + case ERROR: + return Status.ERROR; + default: + return Status.UNRECOGNIZED; + } + } } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/TemplateBuilderSpec.java b/compute/src/main/java/org/jclouds/compute/domain/TemplateBuilderSpec.java index 9f0cec5ab7..1192374482 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/TemplateBuilderSpec.java +++ b/compute/src/main/java/org/jclouds/compute/domain/TemplateBuilderSpec.java @@ -184,7 +184,13 @@ public class TemplateBuilderSpec implements Serializable { /** Specification; used for toParseableString(). */ // transient in case people using serializers don't want this to show up - protected transient final String specification; + protected transient String specification; + + protected TemplateBuilderSpec() { + // we want serializers like Gson to work w/o using sun.misc.Unsafe, + // prohibited in GAE. This also implies fields are not final. + // see http://code.google.com/p/jclouds/issues/detail?spec=925 + } protected TemplateBuilderSpec(String specification) { this.specification = specification; diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java index 79a329cd6a..1502de8cac 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java @@ -27,12 +27,9 @@ import java.util.Set; import org.jclouds.compute.domain.ComputeType; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LoginCredentials; -import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.javax.annotation.Nullable; import com.google.common.collect.ImmutableSet; @@ -46,7 +43,7 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat /** The serialVersionUID */ private static final long serialVersionUID = 7924307572338157887L; - private final NodeState state; + private final Status status; private final int loginPort; private final Set publicAddresses; private final Set privateAddresses; @@ -63,36 +60,9 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat @Nullable private final String hostname; - /** - *

will be removed in jclouds 1.4.0

- */ - @Deprecated public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri, Map userMetadata, Set tags, @Nullable String group, @Nullable Hardware hardware, - @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort, - Iterable publicAddresses, Iterable privateAddresses, @Nullable String adminPassword, - @Nullable Credentials credentials, String hostname) { - super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata, tags); - this.group = group; - this.hardware = hardware; - this.imageId = imageId; - this.os = os; - this.state = checkNotNull(state, "state"); - this.loginPort = loginPort; - this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses")); - this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses")); - this.hostname = hostname; - Builder builder = LoginCredentials.builder(credentials); - if (adminPassword != null) { - builder.authenticateSudo(true); - builder.password(adminPassword); - } - this.credentials = builder.build(); - } - - public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri, - Map userMetadata, Set tags, @Nullable String group, @Nullable Hardware hardware, - @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort, + @Nullable String imageId, @Nullable OperatingSystem os, Status status, int loginPort, Iterable publicAddresses, Iterable privateAddresses, @Nullable LoginCredentials credentials, String hostname) { super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata, tags); @@ -100,7 +70,7 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat this.hardware = hardware; this.imageId = imageId; this.os = os; - this.state = checkNotNull(state, "state"); + this.status = checkNotNull(status, "status"); this.loginPort = loginPort; this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses")); this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses")); @@ -161,8 +131,17 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat * {@inheritDoc} */ @Override - public NodeState getState() { - return state; + @Deprecated + public org.jclouds.compute.domain.NodeState getState() { + return org.jclouds.compute.domain.NodeState.from(status); + } + + /** + * {@inheritDoc} + */ + @Override + public Status getStatus() { + return status; } /** @@ -201,7 +180,7 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat public String toString() { return "[id=" + getId() + ", providerId=" + getProviderId() + ", group=" + getGroup() + ", name=" + getName() + ", location=" + getLocation() + ", uri=" + getUri() + ", imageId=" + getImageId() + ", os=" - + getOperatingSystem() + ", state=" + getState() + ", loginPort=" + getLoginPort() + ", hostname=" + + getOperatingSystem() + ", status=" + getStatus() + ", loginPort=" + getLoginPort() + ", hostname=" + getHostname() + ", privateAddresses=" + privateAddresses + ", publicAddresses=" + publicAddresses + ", hardware=" + getHardware() + ", loginUser=" + ((credentials != null) ? credentials.identity : null) + ", userMetadata=" + getUserMetadata() + ", tags=" + tags + "]"; diff --git a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java index 8c56f43fa2..42106ad924 100644 --- a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java +++ b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java @@ -61,9 +61,9 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.options.TemplateOptions; @@ -576,9 +576,9 @@ public class BaseComputeService implements ComputeService { NodeMetadata node = this.getNodeMetadata(id); if (node == null) throw new NoSuchElementException(id); - if (node.getState() != NodeState.RUNNING) + if (node.getStatus() != Status.RUNNING) throw new IllegalStateException("node " + id - + " needs to be running before executing a script on it. current state: " + node.getState()); + + " needs to be running before executing a script on it. current state: " + node.getStatus()); initAdminAccess.visit(runScript); node = updateNodeWithCredentialsIfPresent(node, options); ExecResponse response = runScriptOnNodeFactory.create(node, runScript, options).init().call(); @@ -595,9 +595,9 @@ public class BaseComputeService implements ComputeService { NodeMetadata node = this.getNodeMetadata(id); if (node == null) throw new NoSuchElementException(id); - if (node.getState() != NodeState.RUNNING) + if (node.getStatus() != Status.RUNNING) throw new IllegalStateException("node " + id - + " needs to be running before executing a script on it. current state: " + node.getState()); + + " needs to be running before executing a script on it. current state: " + node.getStatus()); initAdminAccess.visit(runScript); final NodeMetadata node1 = updateNodeWithCredentialsIfPresent(node, options); ListenableFuture response = runScriptOnNodeFactory.submit(node1, runScript, options); diff --git a/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java b/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java index 2ff19be5ca..e9066f8ae8 100644 --- a/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java +++ b/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java @@ -26,7 +26,7 @@ import java.util.Arrays; import java.util.Map; import java.util.Set; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.domain.LoginCredentials; import org.jclouds.io.Payload; import org.jclouds.scriptbuilder.domain.Statement; @@ -588,7 +588,7 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { * * @param blockUntilRunning * (default true) whether to block until the nodes in this template - * are in {@link NodeState#RUNNING} state + * are in {@link Status#RUNNING} state */ public TemplateOptions blockUntilRunning(boolean blockUntilRunning) { this.blockUntilRunning = blockUntilRunning; diff --git a/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeRunning.java b/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeRunning.java index ab66cb91c1..cb13ddee74 100644 --- a/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeRunning.java +++ b/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeRunning.java @@ -18,13 +18,14 @@ */ package org.jclouds.compute.predicates; +import javax.inject.Inject; import javax.inject.Singleton; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; +import org.jclouds.compute.predicates.internal.RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import com.google.common.collect.ImmutableSet; -import com.google.inject.Inject; /** * @@ -33,10 +34,10 @@ import com.google.inject.Inject; * @author Adrian Cole */ @Singleton -public class AtomicNodeRunning extends RefreshAndDoubleCheckOnFailUnlessStateInvalid { +public class AtomicNodeRunning extends RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid { @Inject public AtomicNodeRunning(GetNodeMetadataStrategy client) { - super(NodeState.RUNNING, ImmutableSet.of(NodeState.ERROR, NodeState.TERMINATED), client); + super(Status.RUNNING, ImmutableSet.of(Status.ERROR, Status.TERMINATED), client); } } diff --git a/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeSuspended.java b/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeSuspended.java index 3e94459195..640488bc7e 100644 --- a/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeSuspended.java +++ b/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeSuspended.java @@ -18,13 +18,14 @@ */ package org.jclouds.compute.predicates; +import javax.inject.Inject; import javax.inject.Singleton; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; +import org.jclouds.compute.predicates.internal.RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import com.google.common.collect.ImmutableSet; -import com.google.inject.Inject; /** * @@ -33,10 +34,10 @@ import com.google.inject.Inject; * @author Adrian Cole */ @Singleton -public class AtomicNodeSuspended extends RefreshAndDoubleCheckOnFailUnlessStateInvalid { +public class AtomicNodeSuspended extends RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid { @Inject public AtomicNodeSuspended(GetNodeMetadataStrategy client) { - super(NodeState.SUSPENDED, ImmutableSet.of(NodeState.ERROR, NodeState.TERMINATED), client); + super(Status.SUSPENDED, ImmutableSet.of(Status.ERROR, Status.TERMINATED), client); } } diff --git a/compute/src/main/java/org/jclouds/compute/predicates/TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse.java b/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeTerminated.java similarity index 51% rename from compute/src/main/java/org/jclouds/compute/predicates/TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse.java rename to compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeTerminated.java index bf95727a30..fe12a99690 100644 --- a/compute/src/main/java/org/jclouds/compute/predicates/TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse.java +++ b/compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeTerminated.java @@ -18,16 +18,13 @@ */ package org.jclouds.compute.predicates; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Resource; +import static com.google.common.base.Preconditions.checkNotNull; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; +import org.jclouds.compute.predicates.internal.TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; -import org.jclouds.logging.Logger; -import com.google.common.base.Predicate; import com.google.inject.Inject; /** @@ -35,35 +32,20 @@ import com.google.inject.Inject; * * @author Adrian Cole */ -public class TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse implements Predicate> { +public class AtomicNodeTerminated extends TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse { private final GetNodeMetadataStrategy client; - @Resource - protected Logger logger = Logger.NULL; - @Inject - public TrueIfNullOrTerminatedRefreshAndDoubleCheckOnFalse(GetNodeMetadataStrategy client) { - this.client = client; + public AtomicNodeTerminated(GetNodeMetadataStrategy client) { + super(Status.TERMINATED); + this.client = checkNotNull(client, "client"); } - - public boolean apply(AtomicReference atomicNode) { - NodeMetadata node = atomicNode.get(); - if (checkState(node)) - return true; - node = refresh(node); - atomicNode.set(node); - return checkState(node); - } - - public boolean checkState(NodeMetadata node) { - if (node == null) - return true; - logger.trace("%s: looking for node state %s: currently: %s", node.getId(), NodeState.TERMINATED, node.getState()); - return node.getState() == NodeState.TERMINATED; - } - - private NodeMetadata refresh(NodeMetadata node) { - return client.getNode(node.getId()); + + @Override + protected NodeMetadata refreshOrNull(NodeMetadata resource) { + if (resource == null || resource.getId() == null) + return null; + return client.getNode(resource.getId()); } } diff --git a/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java b/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java index 32cd732d0f..e14210b8b6 100644 --- a/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java +++ b/compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java @@ -24,7 +24,7 @@ import java.util.Set; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.util.Preconditions2; import com.google.common.base.Predicate; @@ -235,7 +235,7 @@ public class NodePredicates { return new Predicate() { @Override public boolean apply(NodeMetadata nodeMetadata) { - return group.equals(nodeMetadata.getGroup()) && nodeMetadata.getState() == NodeState.RUNNING; + return group.equals(nodeMetadata.getGroup()) && nodeMetadata.getStatus() == Status.RUNNING; } @Override @@ -251,7 +251,7 @@ public class NodePredicates { public static final Predicate RUNNING = new Predicate() { @Override public boolean apply(NodeMetadata nodeMetadata) { - return nodeMetadata.getState() == NodeState.RUNNING; + return nodeMetadata.getStatus() == Status.RUNNING; } @Override @@ -266,7 +266,7 @@ public class NodePredicates { public static final Predicate TERMINATED = new Predicate() { @Override public boolean apply(NodeMetadata nodeMetadata) { - return nodeMetadata.getState() == NodeState.TERMINATED; + return nodeMetadata.getStatus() == Status.TERMINATED; } @Override diff --git a/compute/src/main/java/org/jclouds/compute/predicates/RefreshAndDoubleCheckOnFailUnlessStateInvalid.java b/compute/src/main/java/org/jclouds/compute/predicates/RefreshAndDoubleCheckOnFailUnlessStateInvalid.java deleted file mode 100644 index 32e9e2fea2..0000000000 --- a/compute/src/main/java/org/jclouds/compute/predicates/RefreshAndDoubleCheckOnFailUnlessStateInvalid.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.compute.predicates; - -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Resource; -import javax.inject.Singleton; - -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.strategy.GetNodeMetadataStrategy; -import org.jclouds.logging.Logger; - -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Inject; - -/** - * - * The point of RefreshAndDoubleCheckOnFailUnlessStateInvalid is to keep an atomic reference to a - * node, so as to eliminate a redundant {@link ComputeService#getNodeMetadata} call after the - * predicate passes. - * - * @author Adrian Cole - */ -@Singleton -public class RefreshAndDoubleCheckOnFailUnlessStateInvalid implements Predicate> { - - private final GetNodeMetadataStrategy client; - private final NodeState intended; - private final Set invalids; - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public RefreshAndDoubleCheckOnFailUnlessStateInvalid(NodeState intended, GetNodeMetadataStrategy client) { - this(intended, ImmutableSet.of(NodeState.ERROR), client); - } - - public RefreshAndDoubleCheckOnFailUnlessStateInvalid(NodeState intended, Set invalids, - GetNodeMetadataStrategy client) { - this.intended = intended; - this.client = client; - this.invalids = invalids; - } - - public boolean apply(AtomicReference atomicNode) { - NodeMetadata node = atomicNode.get(); - if (checkState(node)) - return true; - node = refresh(node); - atomicNode.set(node); - return checkState(node); - } - - public boolean checkState(NodeMetadata node) { - if (node == null) - return false; - logger.trace("%s: looking for node state %s: currently: %s", node.getId(), intended, node.getState()); - if (invalids.contains(node.getState())) - throw new IllegalStateException("node " + node.getId() + " in location " + node.getLocation() - + " is in invalid state " + node.getState()); - return node.getState() == intended; - } - - private NodeMetadata refresh(NodeMetadata node) { - if (node == null || node.getId() == null) - return null; - return client.getNode(node.getId()); - } -} diff --git a/compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshAndDoubleCheckOnFailUnlessStatusInvalid.java b/compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshAndDoubleCheckOnFailUnlessStatusInvalid.java new file mode 100644 index 0000000000..9ad4cca997 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshAndDoubleCheckOnFailUnlessStatusInvalid.java @@ -0,0 +1,77 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.compute.predicates.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +import javax.annotation.Resource; +import javax.inject.Singleton; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.domain.ComputeMetadataIncludingStatus; +import org.jclouds.logging.Logger; + +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableSet; + +/** + * + * Keep an atomic reference to a + * resource, so as to eliminate a redundant {@link ComputeService#getNodeMetadata} call after the + * predicate passes. + * + * @author Adrian Cole + */ +@Singleton +public abstract class RefreshAndDoubleCheckOnFailUnlessStatusInvalid, C extends ComputeMetadataIncludingStatus> implements Predicate> { + + private final S intended; + private final Set invalids; + @Resource + protected Logger logger = Logger.NULL; + + public RefreshAndDoubleCheckOnFailUnlessStatusInvalid(S intended, Set invalids) { + this.intended = checkNotNull(intended, "intended"); + this.invalids = ImmutableSet.copyOf(checkNotNull(invalids, "invalids")); + } + + public boolean apply(AtomicReference atomicResource) { + C resource = atomicResource.get(); + if (checkStatus(resource)) + return true; + resource = refreshOrNull(resource); + atomicResource.set(resource); + return checkStatus(resource); + } + + public boolean checkStatus(C resource) { + if (resource == null) + return false; + logger.trace("%s: looking for resource state %s: currently: %s", resource.getId(), intended, resource.getStatus()); + if (invalids.contains(resource.getStatus())) + throw new IllegalStateException("resource " + resource.getId() + " in location " + resource.getLocation() + + " is in invalid status " + resource.getStatus()); + return resource.getStatus() == intended; + } + + protected abstract C refreshOrNull(C resource); +} diff --git a/compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid.java b/compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid.java new file mode 100644 index 0000000000..89a4073923 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.compute.predicates.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Set; + +import javax.inject.Singleton; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadata.Status; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; + +import com.google.common.collect.ImmutableSet; +import com.google.inject.Inject; + +/** + * + * The point of RefreshAndDoubleCheckOnFailUnlessStateInvalid is to keep an atomic reference to a + * node, so as to eliminate a redundant {@link ComputeService#getNodeMetadata} call after the + * predicate passes. + * + * @author Adrian Cole + */ +@Singleton +public class RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid extends RefreshAndDoubleCheckOnFailUnlessStatusInvalid { + + private final GetNodeMetadataStrategy client; + + @Inject + public RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid(Status intended, GetNodeMetadataStrategy client) { + this(intended, ImmutableSet.of(Status.ERROR), client); + } + + public RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid(Status intended, Set invalids, + GetNodeMetadataStrategy client) { + super(intended, invalids); + this.client = checkNotNull(client, "client"); + } + + @Override + protected NodeMetadata refreshOrNull(NodeMetadata resource) { + if (resource == null || resource.getId() == null) + return null; + return client.getNode(resource.getId()); + } +} diff --git a/compute/src/main/java/org/jclouds/compute/predicates/internal/TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse.java b/compute/src/main/java/org/jclouds/compute/predicates/internal/TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse.java new file mode 100644 index 0000000000..78bec8a60e --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/predicates/internal/TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.compute.predicates.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.concurrent.atomic.AtomicReference; + +import javax.annotation.Resource; + +import org.jclouds.compute.domain.ComputeMetadataIncludingStatus; +import org.jclouds.logging.Logger; + +import com.google.common.base.Predicate; + +/** + * + * + * @author Adrian Cole + */ +public abstract class TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse, C extends ComputeMetadataIncludingStatus> + implements Predicate> { + protected final S deletedStatus; + + @Resource + protected Logger logger = Logger.NULL; + + protected TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse(S deletedStatus) { + this.deletedStatus = checkNotNull(deletedStatus, "deletedStatus"); + } + + public boolean apply(AtomicReference atomicResource) { + C resource = atomicResource.get(); + if (checkStatus(resource)) + return true; + resource = refreshOrNull(resource); + atomicResource.set(resource); + return checkStatus(resource); + } + + public boolean checkStatus(C resource) { + if (resource == null) + return true; + logger.trace("%s: looking for resource status %s: currently: %s", resource.getId(), deletedStatus, resource + .getStatus()); + return resource.getStatus() == deletedStatus; + } + + protected abstract C refreshOrNull(C resource); + +} diff --git a/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java b/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java index 67f48befe1..2eefd0e25f 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java @@ -36,7 +36,7 @@ import org.jclouds.compute.callables.RunScriptOnNode; import org.jclouds.compute.config.CustomizationResponse; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; @@ -140,17 +140,17 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Cal } else if (timeWaited < (timeouts.nodeRunning - earlyReturnGrace)) { throw new IllegalStateException( format( - "node(%s) didn't achieve the state running, so we couldn't customize; aborting prematurely after %d seconds with final state: %s", - originalId, timeWaited / 1000, node.get().getState())); + "node(%s) didn't achieve the status running, so we couldn't customize; aborting prematurely after %d seconds with final status: %s", + originalId, timeWaited / 1000, node.get().getStatus())); } else { throw new IllegalStateException( format( - "node(%s) didn't achieve the state running within %d seconds, so we couldn't customize; final state: %s", - originalId, timeouts.nodeRunning / 1000, node.get().getState())); + "node(%s) didn't achieve the status running within %d seconds, so we couldn't customize; final status: %s", + originalId, timeouts.nodeRunning / 1000, node.get().getStatus())); } } } catch (IllegalStateException e) { - if (node.get().getState() == NodeState.TERMINATED) { + if (node.get().getStatus() == Status.TERMINATED) { throw new IllegalStateException(format("node(%s) terminated before we could customize", originalId)); } else { throw e; diff --git a/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java b/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java index 2e232caf11..ccb52339c5 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java @@ -33,8 +33,8 @@ import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName; @@ -127,7 +127,7 @@ public class AdaptingComputeServiceStrategies implements CreateNodeW } private void checkStateAvailable(NodeMetadata node) { - checkState(node != null && node.getState() != NodeState.TERMINATED, "node %s terminated or unavailable!", node); + checkState(node != null && node.getStatus() != Status.TERMINATED, "node %s terminated or unavailable!", node); } @Override diff --git a/compute/src/main/java/org/jclouds/compute/strategy/impl/CreateNodesWithGroupEncodedIntoNameThenAddToSet.java b/compute/src/main/java/org/jclouds/compute/strategy/impl/CreateNodesWithGroupEncodedIntoNameThenAddToSet.java index b4e9e2ab66..04ff27860d 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/impl/CreateNodesWithGroupEncodedIntoNameThenAddToSet.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/impl/CreateNodesWithGroupEncodedIntoNameThenAddToSet.java @@ -41,8 +41,8 @@ import org.jclouds.Constants; import org.jclouds.compute.config.CustomizationResponse; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName; @@ -79,7 +79,7 @@ public class CreateNodesWithGroupEncodedIntoNameThenAddToSet implements CreateNo logger.debug(">> adding node location(%s) name(%s) image(%s) hardware(%s)", template.getLocation().getId(), name, template.getImage().getProviderId(), template.getHardware().getProviderId()); node = addNodeWithGroupStrategy.createNodeWithGroupEncodedIntoName(group, name, template); - logger.debug("<< %s node(%s)", node.getState(), node.getId()); + logger.debug("<< %s node(%s)", node.getStatus(), node.getId()); return new AtomicReference(node); } @@ -133,7 +133,7 @@ public class CreateNodesWithGroupEncodedIntoNameThenAddToSet implements CreateNo * to the jclouds {@link NodeMetadata} object. This call directly precedes customization, such as * executing scripts. * - *

The outcome of this operation does not imply the node is {@link NodeState#RUNNING + *

The outcome of this operation does not imply the node is {@link Status#RUNNING * running}. If you want to insert logic after the node is created, yet before an attempt to * customize the node, then append your behaviour to this method. * @@ -162,7 +162,7 @@ public class CreateNodesWithGroupEncodedIntoNameThenAddToSet implements CreateNo * @param group group the node belongs to * @param name generated name of the node * @param template user-specified template - * @return node that is created, yet not necessarily in {@link NodeState#RUNNING} + * @return node that is created, yet not necessarily in {@link Status#RUNNING} */ protected Future> createNodeInGroupWithNameAndTemplate(String group, String name, Template template) { diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java index 0200b4474e..2a7c002dec 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java @@ -36,10 +36,10 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.domain.Location; import org.jclouds.domain.LoginCredentials; import org.jclouds.location.suppliers.all.JustProvider; @@ -84,13 +84,13 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda this.osToVersionMap = osToVersionMap; } - protected void setStateOnNode(NodeState state, NodeMetadata node) { - nodes.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).state(state).build()); + protected void setStateOnNode(Status status, NodeMetadata node) { + nodes.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).status(status).build()); } - protected void setStateOnNodeAfterDelay(final NodeState state, final NodeMetadata node, final long millis) { + protected void setStateOnNodeAfterDelay(final Status status, final NodeMetadata node, final long millis) { if (millis == 0l) - setStateOnNode(state, node); + setStateOnNode(status, node); else ioThreads.execute(new Runnable() { @@ -101,7 +101,7 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda } catch (InterruptedException e) { Throwables.propagate(e); } - setStateOnNode(state, node); + setStateOnNode(status, node); } }); @@ -120,13 +120,13 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda builder.location(location.get()); builder.imageId(template.getImage().getId()); builder.operatingSystem(template.getImage().getOperatingSystem()); - builder.state(NodeState.PENDING); + builder.status(Status.PENDING); builder.publicAddresses(ImmutableSet. of(publicIpPrefix + id)); builder.privateAddresses(ImmutableSet. of(privateIpPrefix + id)); builder.credentials(LoginCredentials.builder().user("root").password(passwordPrefix + id).build()); NodeMetadata node = builder.build(); nodes.put(node.getId(), node); - setStateOnNodeAfterDelay(NodeState.RUNNING, node, 100); + setStateOnNodeAfterDelay(Status.RUNNING, node, 100); return new NodeWithInitialCredentials(node); } @@ -176,8 +176,8 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda NodeMetadata node = nodes.get(id); if (node == null) return; - setStateOnNodeAfterDelay(NodeState.PENDING, node, 0); - setStateOnNodeAfterDelay(NodeState.TERMINATED, node, 50); + setStateOnNodeAfterDelay(Status.PENDING, node, 0); + setStateOnNodeAfterDelay(Status.TERMINATED, node, 50); ioThreads.execute(new Runnable() { @Override @@ -199,8 +199,8 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda NodeMetadata node = nodes.get(id); if (node == null) throw new ResourceNotFoundException("node not found: " + id); - setStateOnNode(NodeState.PENDING, node); - setStateOnNodeAfterDelay(NodeState.RUNNING, node, 50); + setStateOnNode(Status.PENDING, node); + setStateOnNodeAfterDelay(Status.RUNNING, node, 50); } @Override @@ -208,12 +208,12 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda NodeMetadata node = nodes.get(id); if (node == null) throw new ResourceNotFoundException("node not found: " + id); - if (node.getState() == NodeState.RUNNING) + if (node.getStatus() == Status.RUNNING) return; - if (node.getState() != NodeState.SUSPENDED) - throw new IllegalStateException("to resume a node, it must be in suspended state, not: " + node.getState()); - setStateOnNode(NodeState.PENDING, node); - setStateOnNodeAfterDelay(NodeState.RUNNING, node, 50); + if (node.getStatus() != Status.SUSPENDED) + throw new IllegalStateException("to resume a node, it must be in suspended status, not: " + node.getStatus()); + setStateOnNode(Status.PENDING, node); + setStateOnNodeAfterDelay(Status.RUNNING, node, 50); } @Override @@ -221,11 +221,11 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda NodeMetadata node = nodes.get(id); if (node == null) throw new ResourceNotFoundException("node not found: " + id); - if (node.getState() == NodeState.SUSPENDED) + if (node.getStatus() == Status.SUSPENDED) return; - if (node.getState() != NodeState.RUNNING) - throw new IllegalStateException("to suspend a node, it must be in running state, not: " + node.getState()); - setStateOnNode(NodeState.PENDING, node); - setStateOnNodeAfterDelay(NodeState.SUSPENDED, node, 50); + if (node.getStatus() != Status.RUNNING) + throw new IllegalStateException("to suspend a node, it must be in running status, not: " + node.getStatus()); + setStateOnNode(Status.PENDING, node); + setStateOnNodeAfterDelay(Status.SUSPENDED, node, 50); } } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java index 4ec374c9d7..87360b08dd 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java @@ -29,9 +29,9 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.predicates.SocketOpen; import org.jclouds.rest.annotations.Identity; @@ -133,7 +133,7 @@ public class StubComputeServiceDependenciesModule extends AbstractModule { return false; String id = input.getHostText().replace(publicIpPrefix, ""); NodeMetadata node = nodes.get(id); - return node != null && node.getState() == NodeState.RUNNING; + return node != null && node.getStatus() == Status.RUNNING; } } diff --git a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java index 74e2c5827d..3648fef6b6 100644 --- a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java +++ b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java @@ -34,7 +34,7 @@ import org.jclouds.compute.config.ComputeServiceProperties; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.concurrent.MoreExecutors; @@ -91,7 +91,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { @Test(expectedExceptions = IllegalStateException.class) public void testWithoutInitThrowsIllegalStateException() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( new LoginCredentials("tester", "testpassword!", null, false)).build(); SshClient sshClient = createMock(SshClient.class); @@ -139,7 +139,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { */ private void runDefaults(IAnswer answerForScriptStatus, int timesForScriptStatus) { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING) + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING) .credentials(LoginCredentials.builder().user("tester").password("testpassword!").build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -193,7 +193,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testWithSudoPassword() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( new LoginCredentials("tester", "testpassword!", null, true)).build(); SshClient sshClient = createMock(SshClient.class); @@ -242,7 +242,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testNotRoot() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( new LoginCredentials("tester", "testpassword!", null, true)).build(); SshClient sshClient = createMock(SshClient.class); @@ -292,7 +292,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testBadReturnCode() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("badreturncode").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("badreturncode").status(Status.RUNNING).credentials( new LoginCredentials("tester", "testpassword!", null, true)).build(); SshClient sshClient = createMock(SshClient.class); diff --git a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java index 3716c746ba..42a0a54ec6 100644 --- a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java +++ b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java @@ -28,7 +28,7 @@ import static org.testng.Assert.assertEquals; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.domain.LoginCredentials; import org.jclouds.scriptbuilder.InitScript; @@ -51,7 +51,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { @Test(expectedExceptions = IllegalStateException.class) public void testWithoutInitThrowsIllegalStateException() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( LoginCredentials.builder().user("tester").password("notalot").build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -67,7 +67,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { public void testDefault() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( LoginCredentials.builder().user("tester").password("notalot").build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -108,7 +108,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { public void testWithSudoPassword() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( LoginCredentials.builder().user("tester").password("notalot").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -150,7 +150,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { public void testNotRoot() { Statement command = exec("doFoo"); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( LoginCredentials.builder().user("tester").password("notalot").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); diff --git a/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java b/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java index 31fb4918b1..a12caf03b3 100644 --- a/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java +++ b/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java @@ -30,7 +30,7 @@ import org.jclouds.compute.config.PersistNodeCredentialsModule.RefreshCredential import org.jclouds.compute.config.PersistNodeCredentialsModule.RefreshCredentialsForNodeIfRanAdminAccess; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.internal.PersistNodeCredentials; import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials; @@ -72,7 +72,7 @@ public class PersistNodeCredentialsTest { replay(credstore); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).build(); + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).build(); RefreshCredentialsForNodeIfRanAdminAccess fn = new PersistNodeCredentialsModule.RefreshCredentialsForNodeIfRanAdminAccess( credstore, null); assertEquals(node, fn.apply(node)); @@ -90,7 +90,7 @@ public class PersistNodeCredentialsTest { replay(credstore); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials(credentials).build(); + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials(credentials).build(); RefreshCredentialsForNode fn = new PersistNodeCredentialsModule.RefreshCredentialsForNode(credstore, null); assertEquals(node, fn.apply(node)); @@ -111,7 +111,7 @@ public class PersistNodeCredentialsTest { replay(statement); replay(credstore); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).build(); + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).build(); RefreshCredentialsForNodeIfRanAdminAccess fn = new PersistNodeCredentialsModule.RefreshCredentialsForNodeIfRanAdminAccess( credstore, statement); assertEquals(fn.apply(node).getCredentials(), credentials); @@ -136,7 +136,7 @@ public class PersistNodeCredentialsTest { replay(statement); replay(credstore); - NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).build(); + NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).build(); RefreshCredentialsForNode fn = new PersistNodeCredentialsModule.RefreshCredentialsForNode(credstore, statement); assertEquals(fn.apply(node).getCredentials(), credentials); diff --git a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java index d9f512ccfa..e24ff2cf35 100644 --- a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java @@ -52,10 +52,10 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; +import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; @@ -77,10 +77,10 @@ import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; @@ -468,7 +468,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte assertNotNull(node.getProviderId()); assertNotNull(node.getGroup()); assertEquals(node.getGroup(), group); - assertEquals(node.getState(), NodeState.RUNNING); + assertEquals(node.getStatus(), Status.RUNNING); Credentials fromStore = view.utils().credentialStore().get("node#" + node.getId()); assertEquals(fromStore, node.getCredentials()); assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; @@ -505,7 +505,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte assertLocationSameOrChild(metadata.getLocation(), template.getLocation()); checkImageIdMatchesTemplate(metadata); checkOsMatchesTemplate(metadata); - assert (metadata.getState() == NodeState.RUNNING) : metadata; + assert (metadata.getStatus() == Status.RUNNING) : metadata; // due to DHCP the addresses can actually change in-between runs. assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size(), String.format( "[%s] didn't match: [%s]", metadata.getPrivateAddresses(), node.getPrivateAddresses().size())); @@ -537,9 +537,9 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte @Override public boolean apply(NodeMetadata input) { - boolean returnVal = input.getState() == NodeState.SUSPENDED; + boolean returnVal = input.getStatus() == Status.SUSPENDED; if (!returnVal) - getAnonymousLogger().warning(format("node %s in state %s%n", input.getId(), input.getState())); + getAnonymousLogger().warning(format("node %s in state %s%n", input.getId(), input.getStatus())); return returnVal; } @@ -571,7 +571,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte // assert nodeMetadata.getImage() != null : node; // user specified name is not always supported // assert nodeMetadata.getName() != null : nodeMetadata; - if (nodeMetadata.getState() == NodeState.RUNNING) { + if (nodeMetadata.getStatus() == Status.RUNNING) { assert nodeMetadata.getPublicAddresses() != null : nodeMetadata; assert nodeMetadata.getPublicAddresses().size() > 0 || nodeMetadata.getPrivateAddresses().size() > 0 : nodeMetadata; assertNotNull(nodeMetadata.getPrivateAddresses()); @@ -585,7 +585,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte Set destroyed = client.destroyNodesMatching(inGroup(group)); assertEquals(toDestroy, destroyed.size()); for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), inGroup(group))) { - assert node.getState() == NodeState.TERMINATED : node; + assert node.getStatus() == Status.TERMINATED : node; assert view.utils().credentialStore().get("node#" + node.getId()) == null : "credential should have been null for " + "node#" + node.getId(); } @@ -794,7 +794,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte long time = currentTimeMillis(); Set nodes = client.createNodesInGroup(group, 1, options); NodeMetadata node = getOnlyElement(nodes); - assert node.getState() != NodeState.RUNNING : node; + assert node.getStatus() != Status.RUNNING : node; long duration = (currentTimeMillis() - time) / 1000; assert duration < nonBlockDurationSeconds : format("duration(%d) longer than expected(%d) seconds! ", duration, nonBlockDurationSeconds); diff --git a/compute/src/test/java/org/jclouds/compute/predicates/AtomicNodePredicatesTest.java b/compute/src/test/java/org/jclouds/compute/predicates/AtomicNodePredicatesTest.java index a9eabe2ef3..b9c6aabfae 100644 --- a/compute/src/test/java/org/jclouds/compute/predicates/AtomicNodePredicatesTest.java +++ b/compute/src/test/java/org/jclouds/compute/predicates/AtomicNodePredicatesTest.java @@ -27,7 +27,7 @@ import java.util.concurrent.atomic.AtomicReference; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.domain.LoginCredentials; import org.testng.Assert; @@ -47,7 +47,7 @@ public class AtomicNodePredicatesTest { @Test public void testNoUpdatesAtomicReferenceOnPass() { - NodeMetadata running = new NodeMetadataBuilder().id("myid").state(NodeState.RUNNING).build(); + NodeMetadata running = new NodeMetadataBuilder().id("myid").status(Status.RUNNING).build(); GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class); replay(computeService); @@ -63,7 +63,7 @@ public class AtomicNodePredicatesTest { @Test public void testRefreshUpdatesAtomicReferenceOnRecheckPending() { - NodeMetadata pending = new NodeMetadataBuilder().id("myid").state(NodeState.PENDING).build(); + NodeMetadata pending = new NodeMetadataBuilder().id("myid").status(Status.PENDING).build(); GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class); expect(computeService.getNode("myid")).andReturn(pending); @@ -82,11 +82,11 @@ public class AtomicNodePredicatesTest { @Test public void testRefreshUpdatesAtomicReferenceOnRecheckPendingAcceptsNewCredentials() { LoginCredentials creds = LoginCredentials.builder().user("user").password("password").build(); - NodeMetadata newNode = new NodeMetadataBuilder().id("myid").state(NodeState.UNRECOGNIZED).credentials(creds).build(); + NodeMetadata newNode = new NodeMetadataBuilder().id("myid").status(Status.UNRECOGNIZED).credentials(creds).build(); LoginCredentials creds2 = LoginCredentials.builder().user("user").password("password2").build(); - NodeMetadata pending = new NodeMetadataBuilder().id("myid").state(NodeState.PENDING).credentials(creds2).build(); + NodeMetadata pending = new NodeMetadataBuilder().id("myid").status(Status.PENDING).credentials(creds2).build(); GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class); @@ -104,8 +104,8 @@ public class AtomicNodePredicatesTest { @Test public void testRefreshUpdatesAtomicReferenceOnRecheckRunning() { - NodeMetadata running = new NodeMetadataBuilder().id("myid").state(NodeState.RUNNING).build(); - NodeMetadata pending = new NodeMetadataBuilder().id("myid").state(NodeState.PENDING).build(); + NodeMetadata running = new NodeMetadataBuilder().id("myid").status(Status.RUNNING).build(); + NodeMetadata pending = new NodeMetadataBuilder().id("myid").status(Status.PENDING).build(); GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class); expect(computeService.getNode("myid")).andReturn(running); @@ -133,7 +133,7 @@ public class AtomicNodePredicatesTest { @Test public void testNodeRunningReturnsTrueWhenRunning() { - expect(node.getState()).andReturn(NodeState.RUNNING).atLeastOnce(); + expect(node.getStatus()).andReturn(Status.RUNNING).atLeastOnce(); replay(node); replay(computeService); @@ -145,7 +145,7 @@ public class AtomicNodePredicatesTest { @Test(expectedExceptions = IllegalStateException.class) public void testNodeRunningFailsOnTerminated() { - expect(node.getState()).andReturn(NodeState.TERMINATED).atLeastOnce(); + expect(node.getStatus()).andReturn(Status.TERMINATED).atLeastOnce(); replay(node); replay(computeService); @@ -157,7 +157,7 @@ public class AtomicNodePredicatesTest { @Test(expectedExceptions = IllegalStateException.class) public void testNodeRunningFailsOnError() { - expect(node.getState()).andReturn(NodeState.ERROR).atLeastOnce(); + expect(node.getStatus()).andReturn(Status.ERROR).atLeastOnce(); replay(node); replay(computeService); diff --git a/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java b/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java index 9b36d3a382..bd8426cf36 100644 --- a/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java +++ b/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java @@ -34,7 +34,7 @@ import java.util.concurrent.atomic.AtomicReference; import org.jclouds.compute.config.CustomizationResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.TemplateOptionsToStatement; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.predicates.AtomicNodeRunning; @@ -54,7 +54,7 @@ import com.google.common.collect.Sets; /** * @author Adrian Cole */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest") public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { public void testBreakWhenNodeStillPending() { @@ -69,7 +69,7 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { Map badNodes = Maps.newLinkedHashMap(); Multimap customizationResponses = LinkedHashMultimap.create(); - final NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.PENDING).build(); + final NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); // node always stays pending GetNodeMetadataStrategy nodeRunning = new GetNodeMetadataStrategy(){ @@ -93,7 +93,7 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { assertEquals(goodNodes.size(), 0); assertEquals(badNodes.keySet(), ImmutableSet.of(node)); assertTrue(badNodes.get(node).getMessage() != null && badNodes.get(node).getMessage().matches( - "node\\(id\\) didn't achieve the state running, so we couldn't customize; aborting prematurely after .* seconds with final state: PENDING"), + "node\\(id\\) didn't achieve the status running, so we couldn't customize; aborting prematurely after .* seconds with final status: PENDING"), badNodes.get(node).getMessage()); assertEquals(customizationResponses.size(), 0); @@ -113,8 +113,8 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { Map badNodes = Maps.newLinkedHashMap(); Multimap customizationResponses = LinkedHashMultimap.create(); - final NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.PENDING).build(); - final NodeMetadata deadNnode = new NodeMetadataBuilder().ids("id").state(NodeState.TERMINATED).build(); + final NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); + final NodeMetadata deadNnode = new NodeMetadataBuilder().ids("id").status(Status.TERMINATED).build(); // node dies GetNodeMetadataStrategy nodeRunning = new GetNodeMetadataStrategy(){ @@ -156,8 +156,8 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { Map badNodes = Maps.newLinkedHashMap(); Multimap customizationResponses = LinkedHashMultimap.create(); - final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").state(NodeState.PENDING).build(); - final NodeMetadata runningNode = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).build(); + final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); + final NodeMetadata runningNode = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).build(); expect(openSocketFinder.findOpenSocketOnNode(runningNode, 22, portTimeoutSecs, TimeUnit.SECONDS)) .andThrow(new NoSuchElementException("could not connect to any ip address port")).once(); diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadata.java b/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadata.java index 9ded7d6ee3..bef2a123b4 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadata.java +++ b/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadata.java @@ -35,10 +35,10 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.compute.reference.ComputeServiceConstants; @@ -65,11 +65,11 @@ public class ServerDetailsToNodeMetadata implements Function serverStateToNodeState = ImmutableMap - . builder().put(ServerDetails.State.STOPPED, NodeState.SUSPENDED) - .put(ServerDetails.State.LOCKED, NodeState.PENDING) - .put(ServerDetails.State.RUNNING, NodeState.RUNNING) - .put(ServerDetails.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + public static final Map serverStateToNodeStatus = ImmutableMap + . builder().put(ServerDetails.State.STOPPED, Status.SUSPENDED) + .put(ServerDetails.State.LOCKED, Status.PENDING) + .put(ServerDetails.State.RUNNING, Status.RUNNING) + .put(ServerDetails.State.UNRECOGNIZED, Status.UNRECOGNIZED).build(); protected final Supplier> images; protected final FindLocationForServerDetails findLocationForServerDetails; @@ -112,7 +112,7 @@ public class ServerDetailsToNodeMetadata implements Function of(new VolumeImpl((float) from.getDiskSizeGB(), true, true))) .hypervisor(from.getPlatform()).build()); - builder.state(serverStateToNodeState.get(from.getState())); + builder.status(serverStateToNodeStatus.get(from.getState())); Iterable addresses = Iterables.filter(Iterables.transform(from.getIps(), new Function() { @Override diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java b/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java index c48ed8c28f..516283cf64 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java +++ b/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java @@ -25,11 +25,11 @@ import java.net.URI; import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.glesys.compute.internal.BaseGleSYSComputeServiceExpectTest; import org.jclouds.glesys.features.ServerClientExpectTest; @@ -89,6 +89,6 @@ public class ServerDetailsToNodeMetadataTest extends BaseGleSYSComputeServiceExp new HardwareBuilder().ids("xm3276891").ram(512) .processors(ImmutableList.of(new Processor(1, 1.0))) .volumes(ImmutableList. of(new VolumeImpl(5f, true, true))).hypervisor("Xen") - .build()).state(NodeState.RUNNING).build()); + .build()).status(Status.RUNNING).build()); } } diff --git a/labs/nodepool/src/test/java/org/jclouds/nodepool/AppTest.java b/labs/nodepool/src/test/java/org/jclouds/nodepool/AppTest.java index 7977cc8e58..d198d7dc5e 100644 --- a/labs/nodepool/src/test/java/org/jclouds/nodepool/AppTest.java +++ b/labs/nodepool/src/test/java/org/jclouds/nodepool/AppTest.java @@ -176,8 +176,8 @@ public class AppTest extends TestCase { if (NodeMetadata.class.isInstance(cm)) { String nodeGroup = ((NodeMetadata) cm).getGroup(); - if (!((NodeMetadata) cm).getState().equals(NodeState.SUSPENDED) - && !((NodeMetadata) cm).getState().equals(NodeState.TERMINATED)) { + if (!((NodeMetadata) cm).getState().equals(Status.SUSPENDED) + && !((NodeMetadata) cm).getState().equals(Status.TERMINATED)) { nodeCount++; } } diff --git a/labs/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/AdminClientExpectTest.java b/labs/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/AdminClientExpectTest.java index 87cd71cd47..16753c99a7 100644 --- a/labs/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/AdminClientExpectTest.java +++ b/labs/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/AdminClientExpectTest.java @@ -51,6 +51,7 @@ import com.google.common.collect.ImmutableSet; * * @author Adam Lowe */ +@Test(testName = "AdminClientExpectTest") public class AdminClientExpectTest extends BaseKeystoneRestClientExpectTest { private DateService dateService = new SimpleDateFormatDateService(); diff --git a/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java b/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java index d2a9df35c2..83bc5a5603 100644 --- a/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java +++ b/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java @@ -33,7 +33,7 @@ import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.CIMOperatingSystem; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.savvis.vpdc.domain.VM; @@ -51,11 +51,11 @@ import com.google.common.collect.Iterables; @Singleton public class VMToNodeMetadata implements Function { - public static final Map VAPPSTATUS_TO_NODESTATE = ImmutableMap - . builder().put(VM.Status.OFF, NodeState.SUSPENDED).put(VM.Status.ON, - NodeState.RUNNING).put(VM.Status.RESOLVED, NodeState.PENDING).put(VM.Status.UNRECOGNIZED, - NodeState.UNRECOGNIZED).put(VM.Status.UNKNOWN, NodeState.UNRECOGNIZED).put(VM.Status.SUSPENDED, - NodeState.SUSPENDED).put(VM.Status.UNRESOLVED, NodeState.PENDING).build(); + public static final Map VAPPSTATUS_TO_NODESTATE = ImmutableMap + . builder().put(VM.Status.OFF, Status.SUSPENDED).put(VM.Status.ON, + Status.RUNNING).put(VM.Status.RESOLVED, Status.PENDING).put(VM.Status.UNRECOGNIZED, + Status.UNRECOGNIZED).put(VM.Status.UNKNOWN, Status.UNRECOGNIZED).put(VM.Status.SUSPENDED, + Status.SUSPENDED).put(VM.Status.UNRESOLVED, Status.PENDING).build(); private final FindLocationForVM findLocationForVM; private final GroupNamingConvention nodeNamingConvention; @@ -81,7 +81,7 @@ public class VMToNodeMetadata implements Function { } // TODO build from resource allocation section // builder.hardware(findHardwareForVM.apply(from)); - builder.state(VAPPSTATUS_TO_NODESTATE.get(from.getStatus())); + builder.status(VAPPSTATUS_TO_NODESTATE.get(from.getStatus())); Set addresses = Utils.getIpsFromVM(from); builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE))); builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE)); diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/compute/functions/VmToNodeMetadata.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/compute/functions/VmToNodeMetadata.java index 9f18522498..e784d2ff32 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/compute/functions/VmToNodeMetadata.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/compute/functions/VmToNodeMetadata.java @@ -35,14 +35,13 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Credentials; import org.jclouds.logging.Logger; import org.jclouds.util.InetAddresses2.IsPrivateIPAddress; import org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType; -import org.jclouds.vcloud.director.v1_5.domain.ResourceEntity.Status; import org.jclouds.vcloud.director.v1_5.domain.Vm; +import org.jclouds.vcloud.director.v1_5.domain.ResourceEntity.Status; import org.jclouds.vcloud.director.v1_5.predicates.LinkPredicates; import com.google.common.base.Function; @@ -58,19 +57,19 @@ public class VmToNodeMetadata implements Function { protected final FindLocationForResource findLocationForResourceInVDC; protected final Function hardwareForVm; - protected final Map vAppStatusToNodeState; + protected final Map vAppStatusToNodeStatus; protected final Map credentialStore; protected final GroupNamingConvention nodeNamingConvention; @Inject - protected VmToNodeMetadata(Map vAppStatusToNodeState, Map credentialStore, + protected VmToNodeMetadata(Map vAppStatusToNodeStatus, Map credentialStore, FindLocationForResource findLocationForResourceInVDC, Function hardwareForVm, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); this.hardwareForVm = checkNotNull(hardwareForVm, "hardwareForVm"); this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); - this.vAppStatusToNodeState = checkNotNull(vAppStatusToNodeState, "vAppStatusToNodeState"); + this.vAppStatusToNodeStatus = checkNotNull(vAppStatusToNodeStatus, "vAppStatusToNodeStatus"); } public NodeMetadata apply(Vm from) { @@ -84,7 +83,7 @@ public class VmToNodeMetadata implements Function { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName())); builder.operatingSystem(toComputeOs(from)); builder.hardware(hardwareForVm.apply(from)); - builder.state(vAppStatusToNodeState.get(from.getStatus())); + builder.status(vAppStatusToNodeStatus.get(from.getStatus())); Set addresses = getIpsFromVm(from); builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE))); builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE)); diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/HardcodeLocalhostAsNodeMetadataSupplier.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/HardcodeLocalhostAsNodeMetadataSupplier.java index eb8bf949f3..196559ca20 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/HardcodeLocalhostAsNodeMetadataSupplier.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/HardcodeLocalhostAsNodeMetadataSupplier.java @@ -20,15 +20,16 @@ package org.jclouds.virtualbox.config; import java.io.File; import java.io.IOException; +import java.util.concurrent.Future; import javax.inject.Singleton; import org.jclouds.compute.callables.RunScriptOnNode; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.domain.LoginCredentials; @@ -103,7 +104,7 @@ public class HardcodeLocalhostAsNodeMetadataSupplier extends AbstractModule { .arch(System.getProperty("os.arch")) .version(System.getProperty("os.version")) .build()) - .state(NodeState.RUNNING) + .status(Status.RUNNING) .location(new LocationBuilder().id(HOST_ID) .scope(LocationScope.HOST) .description(HOSTNAME) diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java index 741cb9e950..fb55c3be7f 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java @@ -33,7 +33,7 @@ import org.jclouds.compute.config.ComputeServiceAdapterContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.domain.Location; @@ -174,23 +174,23 @@ public class VirtualBoxComputeServiceContextModule extends } @VisibleForTesting - public static final Map machineToNodeState = ImmutableMap - . builder().put(MachineState.Running, NodeState.RUNNING) - .put(MachineState.PoweredOff, NodeState.SUSPENDED) - .put(MachineState.DeletingSnapshot, NodeState.PENDING) - .put(MachineState.DeletingSnapshotOnline, NodeState.PENDING) - .put(MachineState.DeletingSnapshotPaused, NodeState.PENDING) - .put(MachineState.FaultTolerantSyncing, NodeState.PENDING) - .put(MachineState.LiveSnapshotting, NodeState.PENDING) - .put(MachineState.SettingUp, NodeState.PENDING) - .put(MachineState.Starting, NodeState.PENDING) - .put(MachineState.Stopping, NodeState.PENDING) - .put(MachineState.Restoring, NodeState.PENDING) + public static final Map machineToNodeStatus = ImmutableMap + . builder().put(MachineState.Running, Status.RUNNING) + .put(MachineState.PoweredOff, Status.SUSPENDED) + .put(MachineState.DeletingSnapshot, Status.PENDING) + .put(MachineState.DeletingSnapshotOnline, Status.PENDING) + .put(MachineState.DeletingSnapshotPaused, Status.PENDING) + .put(MachineState.FaultTolerantSyncing, Status.PENDING) + .put(MachineState.LiveSnapshotting, Status.PENDING) + .put(MachineState.SettingUp, Status.PENDING) + .put(MachineState.Starting, Status.PENDING) + .put(MachineState.Stopping, Status.PENDING) + .put(MachineState.Restoring, Status.PENDING) // TODO What to map these states to? - .put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING) - .put(MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING) - .put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING) - .put(MachineState.TeleportingPausedVM, NodeState.PENDING).put(MachineState.Aborted, NodeState.ERROR) - .put(MachineState.Stuck, NodeState.ERROR).put(MachineState.Null, NodeState.UNRECOGNIZED).build(); + .put(MachineState.FirstOnline, Status.PENDING).put(MachineState.FirstTransient, Status.PENDING) + .put(MachineState.LastOnline, Status.PENDING).put(MachineState.LastTransient, Status.PENDING) + .put(MachineState.Teleported, Status.PENDING).put(MachineState.TeleportingIn, Status.PENDING) + .put(MachineState.TeleportingPausedVM, Status.PENDING).put(MachineState.Aborted, Status.ERROR) + .put(MachineState.Stuck, Status.ERROR).put(MachineState.Null, Status.UNRECOGNIZED).build(); } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java index 5379d38cba..2258236dbe 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java @@ -19,7 +19,7 @@ package org.jclouds.virtualbox.functions; -import static org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule.machineToNodeState; +import static org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule.machineToNodeStatus; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_NAME_SEPARATOR; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_PREFIX; @@ -30,7 +30,7 @@ import javax.inject.Named; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; @@ -90,10 +90,10 @@ public class IMachineToNodeMetadata implements Function nodeMetadataBuilder.hostname(vm.getName()); MachineState vmState = vm.getState(); - NodeState nodeState = machineToNodeState.get(vmState); + NodeMetadata.Status nodeState = machineToNodeStatus.get(vmState); if (nodeState == null) - nodeState = NodeState.UNRECOGNIZED; - nodeMetadataBuilder.state(nodeState); + nodeState = Status.UNRECOGNIZED; + nodeMetadataBuilder.status(nodeState); /* // nat adapter diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java index a70f4ef2c4..df5c301552 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java @@ -177,7 +177,7 @@ public class NodeCreator implements Function instanceToNodeState, + protected AWSRunningInstanceToNodeMetadata(Map instanceToNodeStatus, Map credentialStore, Supplier> imageMap, @Memoized Supplier> locations, @Memoized Supplier> hardware, GroupNamingConvention.Factory namingConvention) { - super(instanceToNodeState, credentialStore, imageMap, locations, hardware, namingConvention); + super(instanceToNodeStatus, credentialStore, imageMap, locations, hardware, namingConvention); } @Override diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java index 1f7e7d58fd..c820dc1094 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java @@ -29,7 +29,7 @@ import org.jclouds.aws.ec2.domain.MonitoringState; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.date.DateService; import org.jclouds.domain.Credentials; @@ -135,7 +135,7 @@ public class AWSRunningInstanceToNodeMetadataTest { assertEquals( parser.apply(Iterables.get(contents, 0)).toString(), new NodeMetadataBuilder() - .state(NodeState.RUNNING) + .status(Status.RUNNING) .group("zkclustertest") .name("foo") .hostname("ip-10-212-81-7") @@ -149,7 +149,7 @@ public class AWSRunningInstanceToNodeMetadataTest { assertEquals( parser.apply(Iterables.get(contents, 1)), new NodeMetadataBuilder() - .state(NodeState.RUNNING) + .status(Status.RUNNING) .group("zkclustertest") .hostname("ip-10-212-185-8") .privateAddresses(ImmutableSet.of("10.212.185.8")) @@ -163,7 +163,7 @@ public class AWSRunningInstanceToNodeMetadataTest { protected AWSRunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, final ImmutableSet locations, Set images, Map credentialStore) { - Map instanceToNodeState = EC2ComputeServiceDependenciesModule.instanceToNodeState; + Map instanceToNodeStatus = EC2ComputeServiceDependenciesModule.instanceToNodeStatus; final Map backing = ImagesToRegionAndIdMap.imagesToMap(images); @@ -177,12 +177,12 @@ public class AWSRunningInstanceToNodeMetadataTest { }); - return createNodeParser(hardware, locations, credentialStore, instanceToNodeState, instanceToImage); + return createNodeParser(hardware, locations, credentialStore, instanceToNodeStatus, instanceToImage); } private AWSRunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, final ImmutableSet locations, Map credentialStore, - Map instanceToNodeState, LoadingCache instanceToImage) { + Map instanceToNodeStatus, LoadingCache instanceToImage) { Supplier> locationSupplier = new Supplier>() { @Override @@ -209,7 +209,7 @@ public class AWSRunningInstanceToNodeMetadataTest { }).getInstance(GroupNamingConvention.Factory.class); - AWSRunningInstanceToNodeMetadata parser = new AWSRunningInstanceToNodeMetadata(instanceToNodeState, + AWSRunningInstanceToNodeMetadata parser = new AWSRunningInstanceToNodeMetadata(instanceToNodeStatus, credentialStore, Suppliers.> ofInstance(instanceToImage), locationSupplier, hardwareSupplier, namingConvention); return parser; diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java index d4b1163cca..e3e258a5a5 100644 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java +++ b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java @@ -30,7 +30,7 @@ import org.jclouds.compute.config.ComputeServiceAdapterContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Location; import org.jclouds.functions.IdentityFunction; @@ -85,21 +85,21 @@ public class GoGridComputeServiceContextModule extends } @VisibleForTesting - static final Map serverStateToNodeState = ImmutableMap. builder() - .put(ServerState.ON, NodeState.RUNNING)// - .put(ServerState.STARTING, NodeState.PENDING)// - .put(ServerState.OFF, NodeState.SUSPENDED)// - .put(ServerState.STOPPING, NodeState.PENDING)// - .put(ServerState.RESTARTING, NodeState.PENDING)// - .put(ServerState.SAVING, NodeState.PENDING)// - .put(ServerState.UNRECOGNIZED, NodeState.UNRECOGNIZED)// - .put(ServerState.RESTORING, NodeState.PENDING)// - .put(ServerState.UPDATING, NodeState.PENDING).build(); + static final Map serverStateToNodeStatus = ImmutableMap. builder() + .put(ServerState.ON, Status.RUNNING)// + .put(ServerState.STARTING, Status.PENDING)// + .put(ServerState.OFF, Status.SUSPENDED)// + .put(ServerState.STOPPING, Status.PENDING)// + .put(ServerState.RESTARTING, Status.PENDING)// + .put(ServerState.SAVING, Status.PENDING)// + .put(ServerState.UNRECOGNIZED, Status.UNRECOGNIZED)// + .put(ServerState.RESTORING, Status.PENDING)// + .put(ServerState.UPDATING, Status.PENDING).build(); @Singleton @Provides - Map provideServerToNodeState() { - return serverStateToNodeState; + Map provideServerToNodeStatus() { + return serverStateToNodeStatus; } /** diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java index 9cea0a2159..91080f347d 100644 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java +++ b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java @@ -32,7 +32,7 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.gogrid.domain.Server; @@ -54,7 +54,7 @@ public class ServerToNodeMetadata implements Function { @Resource protected Logger logger = Logger.NULL; - private final Map serverStateToNodeState; + private final Map serverStateToNodeStatus; private final Supplier> images; private final Supplier> hardwares; private final Supplier> locations; @@ -91,12 +91,12 @@ public class ServerToNodeMetadata implements Function { } @Inject - ServerToNodeMetadata(Map serverStateToNodeState, + ServerToNodeMetadata(Map serverStateToNodeStatus, @Memoized Supplier> images, @Memoized Supplier> hardwares, @Memoized Supplier> locations, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); - this.serverStateToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); + this.serverStateToNodeStatus = checkNotNull(serverStateToNodeStatus, "serverStateToNodeStatus"); this.images = checkNotNull(images, "images"); this.hardwares = checkNotNull(hardwares, "hardwares"); this.locations = checkNotNull(locations, "locations"); @@ -117,7 +117,7 @@ public class ServerToNodeMetadata implements Function { if (image != null) builder.operatingSystem(image.getOperatingSystem()); - builder.state(serverStateToNodeState.get(from.getState())); + builder.status(serverStateToNodeStatus.get(from.getState())); builder.publicAddresses(ImmutableSet.of(from.getIp().getIp())); return builder.build(); } diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java index f5ec5c8fea..0ef1b33939 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java @@ -31,7 +31,7 @@ public class GoGridComputeServiceContextModuleTest { public void testAllStatusCovered() { for (ServerState state : ServerState.values()) { - assert GoGridComputeServiceContextModule.serverStateToNodeState.containsKey(state) : state; + assert GoGridComputeServiceContextModule.serverStateToNodeStatus.containsKey(state) : state; } } diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java index 117d11e795..31c9f68d33 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java @@ -30,8 +30,8 @@ import java.util.Set; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -60,7 +60,7 @@ public class ServerToNodeMetadataTest { @Test public void testApplySetsTagFromNameAndCredentialsFromName() { - Map serverStateToNodeState = createMock(Map.class); + Map serverStateToNodeStatus = createMock(Map.class); org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); Option dc = new Option(1l, "US-West-1", "US West 1 Datacenter"); Option ram = new Option(1l, "512MB", "Server with 512MB RAM"); @@ -72,7 +72,7 @@ public class ServerToNodeMetadataTest { expect(server.getName()).andReturn("group-ff").atLeastOnce(); expect(server.getState()).andReturn(ServerState.ON).atLeastOnce(); - expect(serverStateToNodeState.get(ServerState.ON)).andReturn(NodeState.RUNNING); + expect(serverStateToNodeStatus.get(ServerState.ON)).andReturn(Status.RUNNING); Location location = new LocationBuilder().scope(LocationScope.ZONE).id("1").description("US-West-1").build(); Set< ? extends Location> locations = ImmutableSet.< Location> of( location); @@ -88,12 +88,12 @@ public class ServerToNodeMetadataTest { expect(jcImage.getLocation()).andReturn(location).atLeastOnce(); expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce(); - replay(serverStateToNodeState); + replay(serverStateToNodeStatus); replay(server); replay(image); replay(jcImage); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, Suppliers + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers .> ofInstance(images), Suppliers .> ofInstance(GoGridHardwareSupplier.H_ALL), Suppliers .> ofInstance(locations), namingConvention); @@ -103,7 +103,7 @@ public class ServerToNodeMetadataTest { assertEquals(metadata.getImageId(), "2000"); assertEquals(metadata.getGroup(), "group"); - verify(serverStateToNodeState); + verify(serverStateToNodeStatus); verify(image); verify(server); verify(jcImage); diff --git a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java index 011861169b..f015dc4e5d 100644 --- a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java +++ b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/binder/RimuHostingJsonBinder.java @@ -18,7 +18,6 @@ */ package org.jclouds.rimuhosting.miro.binder; -import java.util.HashMap; import java.util.Map; import javax.inject.Inject; diff --git a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java index c1669347f9..5e47072577 100644 --- a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java +++ b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java @@ -23,7 +23,7 @@ import java.util.Map; import javax.inject.Singleton; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.rimuhosting.miro.compute.functions.ServerToNodeMetadata; import org.jclouds.rimuhosting.miro.domain.Server; import org.jclouds.rimuhosting.miro.domain.internal.RunningState; @@ -55,18 +55,18 @@ public class RimuHostingComputeServiceDependenciesModule extends AbstractModule } @VisibleForTesting - static final Map runningStateToNodeState = ImmutableMap. builder() - .put(RunningState.RUNNING, NodeState.RUNNING)// - .put(RunningState.NOTRUNNING, NodeState.SUSPENDED)// - .put(RunningState.POWERCYCLING, NodeState.PENDING)// - .put(RunningState.RESTARTING, NodeState.PENDING)// - .put(RunningState.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + static final Map runningStateToNodeStatus = ImmutableMap. builder() + .put(RunningState.RUNNING, Status.RUNNING)// + .put(RunningState.NOTRUNNING, Status.SUSPENDED)// + .put(RunningState.POWERCYCLING, Status.PENDING)// + .put(RunningState.RESTARTING, Status.PENDING)// + .put(RunningState.UNRECOGNIZED, Status.UNRECOGNIZED)// .build(); @Singleton @Provides - Map provideServerToNodeState() { - return runningStateToNodeState; + Map provideServerToNodeStatus() { + return runningStateToNodeStatus; } @Singleton diff --git a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java index e11c47d3d7..3d5a4f8536 100644 --- a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java +++ b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java @@ -32,8 +32,8 @@ import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -57,7 +57,7 @@ public class ServerToNodeMetadata implements Function { protected final Supplier> locations; protected final Function> getPublicAddresses; - protected final Map runningStateToNodeState; + protected final Map runningStateToNodeStatus; protected final Supplier> images; protected final GroupNamingConvention nodeNamingConvention; @@ -80,13 +80,13 @@ public class ServerToNodeMetadata implements Function { @Inject ServerToNodeMetadata(Function> getPublicAddresses, - @Memoized Supplier> locations, Map runningStateToNodeState, + @Memoized Supplier> locations, Map runningStateToNodeStatus, @Memoized Supplier> images, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); - this.getPublicAddresses = checkNotNull(getPublicAddresses, "serverStateToNodeState"); + this.getPublicAddresses = checkNotNull(getPublicAddresses, "serverStateToNodeStatus"); this.locations = checkNotNull(locations, "locations"); - this.runningStateToNodeState = checkNotNull(runningStateToNodeState, "serverStateToNodeState"); + this.runningStateToNodeStatus = checkNotNull(runningStateToNodeStatus, "serverStateToNodeStatus"); this.images = checkNotNull(images, "images"); } @@ -104,9 +104,9 @@ public class ServerToNodeMetadata implements Function { builder.hardware(null);// TODO if (from.getBillingData() != null && from.getBillingData().getDateCancelled() != null && RunningState.NOTRUNNING == from.getState()) - builder.state(NodeState.TERMINATED); + builder.status(Status.TERMINATED); else - builder.state(runningStateToNodeState.get(from.getState())); + builder.status(runningStateToNodeStatus.get(from.getState())); builder.publicAddresses(getPublicAddresses.apply(from)); return builder.build(); } diff --git a/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java b/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java index 23d743f76b..0d80742c2d 100644 --- a/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java +++ b/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModuleTest.java @@ -30,7 +30,7 @@ public class RimuHostingComputeServiceContextModuleTest { public void testAllStatusCovered() { for (RunningState state : RunningState.values()) { - assert RimuHostingComputeServiceDependenciesModule.runningStateToNodeState.containsKey(state) : state; + assert RimuHostingComputeServiceDependenciesModule.runningStateToNodeStatus.containsKey(state) : state; } } diff --git a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java index ecf26037d4..aabf941470 100644 --- a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java +++ b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java @@ -27,8 +27,8 @@ import org.jclouds.compute.config.ComputeServiceAdapterContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.internal.BaseComputeService; import org.jclouds.domain.Location; import org.jclouds.functions.IdentityFunction; @@ -79,18 +79,18 @@ public class SlicehostComputeServiceContextModule extends } @VisibleForTesting - public static final Map sliceStatusToNodeState = ImmutableMap - . builder().put(Slice.Status.ACTIVE, NodeState.RUNNING)// - .put(Slice.Status.BUILD, NodeState.PENDING)// - .put(Slice.Status.REBOOT, NodeState.PENDING)// - .put(Slice.Status.HARD_REBOOT, NodeState.PENDING)// - .put(Slice.Status.TERMINATED, NodeState.TERMINATED)// - .put(Slice.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + public static final Map sliceStatusToNodeStatus = ImmutableMap + . builder().put(Slice.Status.ACTIVE, Status.RUNNING)// + .put(Slice.Status.BUILD, Status.PENDING)// + .put(Slice.Status.REBOOT, Status.PENDING)// + .put(Slice.Status.HARD_REBOOT, Status.PENDING)// + .put(Slice.Status.TERMINATED, Status.TERMINATED)// + .put(Slice.Status.UNRECOGNIZED, Status.UNRECOGNIZED)// .build(); @Singleton @Provides - Map provideSliceToNodeState() { - return sliceStatusToNodeState; + Map provideSliceToNodeStatus() { + return sliceStatusToNodeStatus; } } diff --git a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java index 9bc4171242..2c106e2cc5 100644 --- a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java +++ b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java @@ -33,8 +33,8 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -51,7 +51,7 @@ import com.google.common.collect.Iterables; @Singleton public class SliceToNodeMetadata implements Function { protected final Supplier location; - protected final Map sliceToNodeState; + protected final Map sliceToNodeStatus; protected final Supplier> images; protected final Supplier> hardwares; protected final GroupNamingConvention nodeNamingConvention; @@ -86,12 +86,12 @@ public class SliceToNodeMetadata implements Function { } @Inject - SliceToNodeMetadata(Map sliceStateToNodeState, + SliceToNodeMetadata(Map sliceStateToNodeStatus, @Memoized Supplier> images, Supplier location, @Memoized Supplier> hardwares, GroupNamingConvention.Factory namingConvention) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); - this.sliceToNodeState = checkNotNull(sliceStateToNodeState, "sliceStateToNodeState"); + this.sliceToNodeStatus = checkNotNull(sliceStateToNodeStatus, "sliceStateToNodeStatus"); this.images = checkNotNull(images, "images"); this.location = checkNotNull(location, "location"); this.hardwares = checkNotNull(hardwares, "hardwares"); @@ -108,7 +108,7 @@ public class SliceToNodeMetadata implements Function { builder.imageId(from.getImageId() + ""); builder.operatingSystem(parseOperatingSystem(from)); builder.hardware(parseHardware(from)); - builder.state(sliceToNodeState.get(from.getStatus())); + builder.status(sliceToNodeStatus.get(from.getStatus())); builder.publicAddresses(Iterables.filter(from.getAddresses(), new Predicate() { @Override diff --git a/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java b/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java index ad258a7ed9..b6e9872596 100644 --- a/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java +++ b/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java @@ -30,7 +30,7 @@ public class SlicehostComputeServiceContextModuleTest { public void testAllStatusCovered() { for (Slice.Status state : Slice.Status.values()) { - assert SlicehostComputeServiceContextModule.sliceStatusToNodeState.containsKey(state) : state; + assert SlicehostComputeServiceContextModule.sliceStatusToNodeStatus.containsKey(state) : state; } } diff --git a/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java b/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java index c07a782dbd..8bba87443b 100644 --- a/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java +++ b/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java @@ -28,12 +28,12 @@ import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.VolumeBuilder; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -59,18 +59,18 @@ public class SliceToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareNotFound() { - Map sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Map sliceStateToNodeStatus = SlicehostComputeServiceContextModule.sliceStatusToNodeStatus; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Slice slice = SliceHandlerTest.parseSlice(); - SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, Suppliers + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeStatus, Suppliers .> ofInstance(images), Suppliers.ofInstance(provider), Suppliers .> ofInstance(hardwares), namingConvention); NodeMetadata metadata = parser.apply(slice); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + assertEquals(metadata, new NodeMetadataBuilder().status(Status.PENDING).publicAddresses( ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).group("jclouds") .imageId("2").id("1").providerId("1").name("jclouds-foo").hostname("jclouds-foo").location(provider) .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); @@ -78,18 +78,18 @@ public class SliceToNodeMetadataTest { @Test public void testApplyWhereImageFoundAndHardwareNotFound() { - Map sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Map sliceStateToNodeStatus = SlicehostComputeServiceContextModule.sliceStatusToNodeStatus; org.jclouds.compute.domain.Image jcImage = SlicehostImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); Set hardwares = ImmutableSet.of(); Slice slice = SliceHandlerTest.parseSlice(); - SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, Suppliers + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeStatus, Suppliers .> ofInstance(images), Suppliers.ofInstance(provider), Suppliers .> ofInstance(hardwares), namingConvention); NodeMetadata metadata = parser.apply(slice); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + assertEquals(metadata, new NodeMetadataBuilder().status(Status.PENDING).publicAddresses( ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).group("jclouds") .imageId("2").operatingSystem( new OperatingSystem.Builder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") @@ -100,17 +100,17 @@ public class SliceToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareFound() { - Map sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Map sliceStateToNodeStatus = SlicehostComputeServiceContextModule.sliceStatusToNodeStatus; Set images = ImmutableSet.of(SlicehostImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Slice slice = SliceHandlerTest.parseSlice(); - SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, Suppliers + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeStatus, Suppliers .> ofInstance(images), Suppliers.ofInstance(provider), Suppliers .> ofInstance(hardwares), namingConvention); NodeMetadata metadata = parser.apply(slice); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + assertEquals(metadata, new NodeMetadataBuilder().status(Status.PENDING).publicAddresses( ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).group("jclouds") .imageId("2").hardware( new HardwareBuilder().ids("1").name("256 slice").processors( diff --git a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java index bd1ee96cfe..b5a6bd8ee5 100644 --- a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java +++ b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java @@ -32,7 +32,7 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.softlayer.SoftLayerClient; @@ -54,10 +54,10 @@ import com.google.common.collect.Iterables; @Singleton public class VirtualGuestToNodeMetadata implements Function { - public static final Map serverStateToNodeState = ImmutableMap - . builder().put(VirtualGuest.State.HALTED, NodeState.PENDING) - .put(VirtualGuest.State.PAUSED, NodeState.SUSPENDED).put(VirtualGuest.State.RUNNING, NodeState.RUNNING) - .put(VirtualGuest.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + public static final Map serverStateToNodeStatus = ImmutableMap + . builder().put(VirtualGuest.State.HALTED, Status.PENDING) + .put(VirtualGuest.State.PAUSED, Status.SUSPENDED).put(VirtualGuest.State.RUNNING, Status.RUNNING) + .put(VirtualGuest.State.UNRECOGNIZED, Status.UNRECOGNIZED).build(); private final FindLocationForVirtualGuest findLocationForVirtualGuest; private final GetHardwareForVirtualGuest getHardwareForVirtualGuest; @@ -94,7 +94,7 @@ public class VirtualGuestToNodeMetadata implements Function { - public static final Map serverStatusToNodeState = ImmutableMap - . builder().put(Server.Status.ACTIVE, NodeState.RUNNING)// - .put(Server.Status.BUILD, NodeState.PENDING)// - .put(Server.Status.TERMINATED, NodeState.TERMINATED)// - .put(Server.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + public static final Map serverStatusToNodeStatus = ImmutableMap + . builder().put(Server.Status.ACTIVE, Status.RUNNING)// + .put(Server.Status.BUILD, Status.PENDING)// + .put(Server.Status.TERMINATED, Status.TERMINATED)// + .put(Server.Status.UNRECOGNIZED, Status.UNRECOGNIZED)// .build(); private final FindHardwareForServer findHardwareForServer; @@ -87,7 +87,7 @@ public class ServerToNodeMetadata implements Function { if (image != null) builder.operatingSystem(image.getOperatingSystem()); builder.hardware(findHardwareForServer.apply(from)); - builder.state(serverStatusToNodeState.get(from.status)); + builder.status(serverStatusToNodeStatus.get(from.status)); builder.publicAddresses(ImmutableSet. of(from.publicAddress)); builder.privateAddresses(ImmutableSet. of(from.privateAddress)); builder.credentials(LoginCredentials.fromCredentials(credentialStore.get(from.id + ""))); From ef17ef23ea508a531e2724c191ca0ddc1daa0b74 Mon Sep 17 00:00:00 2001 From: hhrasna Date: Wed, 30 May 2012 20:45:20 -0300 Subject: [PATCH 07/73] EC2 image architecture can be null. Don't throw NPE if architecture is null. --- apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java index 12a95d11cb..c3e8592799 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java @@ -78,7 +78,7 @@ public class Image implements Comparable { @Nullable String ramdiskId, RootDeviceType rootDeviceType, @Nullable String rootDeviceName, Map ebsBlockDevices, VirtualizationType virtualizationType, Hypervisor hypervisor) { this.region = checkNotNull(region, "region"); - this.architecture = checkNotNull(architecture, "architecture"); + this.architecture = architecture; this.imageId = checkNotNull(imageId, "imageId"); this.name = name; this.description = description; From 96773b8a1b9b03b36daf966294db9e58464ffc38 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Wed, 30 May 2012 21:20:01 -0700 Subject: [PATCH 08/73] Issue 952:add status field to image --- ...oudServersComputeServiceContextModule.java | 74 +++++++++++------- .../CloudServersImageExtension.java | 2 +- .../functions/CloudServersImageToImage.java | 11 ++- ...erversComputeServiceContextModuleTest.java | 2 +- .../CloudServersImageToImageTest.java | 23 +++--- .../functions/ServerToNodeMetadataTest.java | 6 +- .../functions/PreinstalledDiskToImage.java | 3 +- .../compute/functions/TemplateToImage.java | 3 + .../functions/TemplateToImageTest.java | 12 +-- .../functions/DeltacloudImageToImage.java | 2 + .../EC2ComputeServiceDependenciesModule.java | 35 +++++++-- .../ec2/compute/functions/EC2ImageParser.java | 11 ++- .../ec2/compute/EC2TemplateBuilderTest.java | 4 + .../compute/functions/EC2ImageParserTest.java | 26 ++++--- .../RunningInstanceToNodeMetadataTest.java | 6 +- .../functions/WellKnownImageToImage.java | 2 + .../NovaComputeServiceContextModule.java | 24 +++++- .../compute/functions/NovaImageToImage.java | 10 ++- .../NovaComputeServiceContextModuleTest.java | 2 +- .../functions/NovaImageToImageTest.java | 16 ++-- .../functions/ServerToNodeMetadataTest.java | 6 +- .../strategy/NovaReviseParsedImageTest.java | 8 +- .../NovaComputeServiceContextModule.java | 42 ++++++++++ .../compute/functions/ImageInZoneToImage.java | 8 +- .../functions/ServerInZoneToNodeMetadata.java | 13 ++-- .../openstack/nova/v1_1/domain/Server.java | 19 +---- .../functions/ImageInZoneToImageTest.java | 33 +++----- .../functions/OrphanedGroupsByZoneIdTest.java | 11 ++- .../ServerInZoneToNodeMetadataTest.java | 23 +++--- ...CloudComputeServiceDependenciesModule.java | 50 +++++++++--- .../functions/ImageForVAppTemplate.java | 9 ++- .../org/jclouds/vcloud/domain/Status.java | 22 +++++- .../ListImagesInVCloudExpectTest.java | 3 + .../functions/VAppToNodeMetadataTest.java | 2 +- ...markVCloudComputeServiceContextModule.java | 34 ++++++-- .../ImageForVCloudExpressVAppTemplate.java | 8 +- ...VCloudComputeServiceContextModuleTest.java | 2 +- .../org/jclouds/compute/domain/Image.java | 27 ++++++- .../jclouds/compute/domain/ImageBuilder.java | 44 +++-------- .../compute/domain/internal/ImageImpl.java | 34 ++++---- .../config/StubComputeServiceAdapter.java | 2 +- .../internal/TemplateBuilderImplTest.java | 5 +- .../compute/functions/OSTemplateToImage.java | 3 +- .../functions/CIMOperatingSystemToImage.java | 2 + .../functions/ImageForVAppTemplate.java | 9 ++- .../VCloudDirectorRestClientModule.java | 1 - ...VirtualBoxComputeServiceContextModule.java | 78 ++++++++++++++----- .../jclouds/virtualbox/domain/YamlImage.java | 2 +- .../virtualbox/functions/IMachineToImage.java | 8 +- .../functions/IMachineToNodeMetadata.java | 8 +- .../virtualbox/functions/NodeCreator.java | 2 +- .../VirtualBoxComputeServiceAdapterTest.java | 4 +- .../functions/IMachineToImageTest.java | 18 ++++- .../functions/IMachineToNodeMetadataTest.java | 7 +- .../admin/ImageFromYamlStringTest.java | 5 +- .../AWSRunningInstanceToNodeMetadataTest.java | 2 +- .../strategy/AWSEC2ImageParserTest.java | 40 ++++++---- .../strategy/AWSEC2ReviseParsedImageTest.java | 6 +- ...ptusPartnerCloudReviseParsedImageTest.java | 20 +++-- .../GoGridComputeServiceContextModule.java | 37 ++++++--- .../compute/functions/ServerImageToImage.java | 10 ++- ...GoGridComputeServiceContextModuleTest.java | 2 +- .../suppliers/RimuHostingImageSupplier.java | 2 + .../functions/SlicehostImageToImage.java | 1 + .../functions/SlicehostImageToImageTest.java | 17 ++-- .../compute/functions/ProductItemToImage.java | 1 + .../functions/ProductItemToImageTest.java | 2 +- .../VirtualGuestToNodeMetadataTest.java | 3 +- .../functions/ServerManagerImageToImage.java | 2 + 69 files changed, 663 insertions(+), 308 deletions(-) diff --git a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java index 8ab0b09680..2ac13e1994 100644 --- a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java +++ b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/config/CloudServersComputeServiceContextModule.java @@ -30,6 +30,7 @@ import org.jclouds.cloudservers.compute.functions.ServerToNodeMetadata; import org.jclouds.cloudservers.compute.predicates.GetImageWhenStatusActivePredicateWithResult; import org.jclouds.cloudservers.compute.strategy.CloudServersComputeServiceAdapter; import org.jclouds.cloudservers.domain.Flavor; +import org.jclouds.cloudservers.domain.ImageStatus; import org.jclouds.cloudservers.domain.Server; import org.jclouds.cloudservers.domain.ServerStatus; import org.jclouds.compute.ComputeServiceAdapter; @@ -38,7 +39,6 @@ import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.internal.BaseComputeService; import org.jclouds.domain.Location; @@ -93,36 +93,54 @@ public class CloudServersComputeServiceContextModule extends } @VisibleForTesting - public static final Map serverToNodeStatus = ImmutableMap - . builder().put(ServerStatus.ACTIVE, Status.RUNNING)// - .put(ServerStatus.SUSPENDED, Status.SUSPENDED)// - .put(ServerStatus.DELETED, Status.TERMINATED)// - .put(ServerStatus.QUEUE_RESIZE, Status.PENDING)// - .put(ServerStatus.PREP_RESIZE, Status.PENDING)// - .put(ServerStatus.RESIZE, Status.PENDING)// - .put(ServerStatus.VERIFY_RESIZE, Status.PENDING)// - .put(ServerStatus.QUEUE_MOVE, Status.PENDING)// - .put(ServerStatus.PREP_MOVE, Status.PENDING)// - .put(ServerStatus.MOVE, Status.PENDING)// - .put(ServerStatus.VERIFY_MOVE, Status.PENDING)// - .put(ServerStatus.RESCUE, Status.PENDING)// - .put(ServerStatus.ERROR, Status.ERROR)// - .put(ServerStatus.BUILD, Status.PENDING)// - .put(ServerStatus.RESTORING, Status.PENDING)// - .put(ServerStatus.PASSWORD, Status.PENDING)// - .put(ServerStatus.REBUILD, Status.PENDING)// - .put(ServerStatus.DELETE_IP, Status.PENDING)// - .put(ServerStatus.SHARE_IP_NO_CONFIG, Status.PENDING)// - .put(ServerStatus.SHARE_IP, Status.PENDING)// - .put(ServerStatus.REBOOT, Status.PENDING)// - .put(ServerStatus.HARD_REBOOT, Status.PENDING)// - .put(ServerStatus.UNKNOWN, Status.UNRECOGNIZED)// - .put(ServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED).build(); + public static final Map toPortableNodeStatus = ImmutableMap + . builder() + .put(ServerStatus.ACTIVE, NodeMetadata.Status.RUNNING) + .put(ServerStatus.SUSPENDED, NodeMetadata.Status.SUSPENDED) + .put(ServerStatus.DELETED, NodeMetadata.Status.TERMINATED) + .put(ServerStatus.QUEUE_RESIZE, NodeMetadata.Status.PENDING) + .put(ServerStatus.PREP_RESIZE, NodeMetadata.Status.PENDING) + .put(ServerStatus.RESIZE, NodeMetadata.Status.PENDING) + .put(ServerStatus.VERIFY_RESIZE, NodeMetadata.Status.PENDING) + .put(ServerStatus.QUEUE_MOVE, NodeMetadata.Status.PENDING) + .put(ServerStatus.PREP_MOVE, NodeMetadata.Status.PENDING) + .put(ServerStatus.MOVE, NodeMetadata.Status.PENDING) + .put(ServerStatus.VERIFY_MOVE, NodeMetadata.Status.PENDING) + .put(ServerStatus.RESCUE, NodeMetadata.Status.PENDING) + .put(ServerStatus.ERROR, NodeMetadata.Status.ERROR) + .put(ServerStatus.BUILD, NodeMetadata.Status.PENDING) + .put(ServerStatus.RESTORING, NodeMetadata.Status.PENDING) + .put(ServerStatus.PASSWORD, NodeMetadata.Status.PENDING) + .put(ServerStatus.REBUILD, NodeMetadata.Status.PENDING) + .put(ServerStatus.DELETE_IP, NodeMetadata.Status.PENDING) + .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeMetadata.Status.PENDING) + .put(ServerStatus.SHARE_IP, NodeMetadata.Status.PENDING) + .put(ServerStatus.REBOOT, NodeMetadata.Status.PENDING) + .put(ServerStatus.HARD_REBOOT, NodeMetadata.Status.PENDING) + .put(ServerStatus.UNKNOWN, NodeMetadata.Status.UNRECOGNIZED) + .put(ServerStatus.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).build(); @Singleton @Provides - Map provideServerToNodeStatus() { - return serverToNodeStatus; + Map toPortableNodeStatus() { + return toPortableNodeStatus; + } + + @VisibleForTesting + public static final Map toPortableImageStatus = ImmutableMap + . builder() + .put(ImageStatus.ACTIVE, Image.Status.AVAILABLE) + .put(ImageStatus.SAVING, Image.Status.PENDING) + .put(ImageStatus.PREPARING, Image.Status.PENDING) + .put(ImageStatus.QUEUED, Image.Status.PENDING) + .put(ImageStatus.FAILED, Image.Status.ERROR) + .put(ImageStatus.UNKNOWN, Image.Status.UNRECOGNIZED) + .put(ImageStatus.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build(); + + @Singleton + @Provides + Map toPortableImageStatus() { + return toPortableImageStatus; } @Override diff --git a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/extensions/CloudServersImageExtension.java b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/extensions/CloudServersImageExtension.java index 946e6e1017..24f4e4e873 100644 --- a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/extensions/CloudServersImageExtension.java +++ b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/extensions/CloudServersImageExtension.java @@ -52,7 +52,7 @@ import com.google.common.util.concurrent.ListenableFuture; * CloudServers implementation of {@link ImageExtension} * * @author David Alves - * + * @see
docs */ @Singleton public class CloudServersImageExtension implements ImageExtension { diff --git a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/CloudServersImageToImage.java b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/CloudServersImageToImage.java index bedecffe6b..68727aca42 100644 --- a/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/CloudServersImageToImage.java +++ b/apis/cloudservers/src/main/java/org/jclouds/cloudservers/compute/functions/CloudServersImageToImage.java @@ -18,12 +18,16 @@ */ package org.jclouds.cloudservers.compute.functions; +import java.util.Map; + import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.cloudservers.domain.ImageStatus; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.Image.Status; import com.google.common.base.Function; @@ -33,13 +37,15 @@ import com.google.common.base.Function; */ @Singleton public class CloudServersImageToImage implements Function { + private final Map toPortableImageStatus; private final Function imageToOs; @Inject - CloudServersImageToImage(Function imageToOs) { + CloudServersImageToImage(Map toPortableImageStatus, Function imageToOs) { + this.toPortableImageStatus=toPortableImageStatus; this.imageToOs = imageToOs; } - + public Image apply(org.jclouds.cloudservers.domain.Image from) { ImageBuilder builder = new ImageBuilder(); builder.ids(from.getId() + ""); @@ -47,6 +53,7 @@ public class CloudServersImageToImage implements Function serverStateToNodeStatus = CloudServersComputeServiceContextModule.serverToNodeStatus; + Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.toPortableNodeStatus; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); @@ -91,7 +91,7 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageFoundAndHardwareNotFound() { - Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.serverToNodeStatus; + Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.toPortableNodeStatus; org.jclouds.compute.domain.Image jcImage = CloudServersImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); Set hardwares = ImmutableSet.of(); @@ -126,7 +126,7 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareFound() { - Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.serverToNodeStatus; + Map serverStateToNodeStatus = CloudServersComputeServiceContextModule.toPortableNodeStatus; Set images = ImmutableSet.of(CloudServersImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Server server = ParseServerFromJsonResponseTest.parseServer(); diff --git a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java index 356fc1bec9..56b827c167 100644 --- a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java +++ b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java @@ -26,6 +26,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamilyVersion64Bit; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.domain.OperatingSystem.Builder; import org.jclouds.domain.Location; @@ -61,6 +62,6 @@ public class PreinstalledDiskToImage implements Function { return new ImageBuilder().ids(drive.getUuid()) .userMetadata(ImmutableMap. of("size", drive.getSize() / 1024 / 1024 / 1024 + "")) .location(locationSupplier.get()).name(drive.getName()).description(description) - .operatingSystem(builder.build()).version("").build(); + .operatingSystem(builder.build()).status(Status.AVAILABLE).version("").build(); } } \ No newline at end of file diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/TemplateToImage.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/TemplateToImage.java index 5384178636..f3c1ba4614 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/TemplateToImage.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/TemplateToImage.java @@ -31,6 +31,7 @@ import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.domain.Location; import com.google.common.base.Function; @@ -62,6 +63,8 @@ public class TemplateToImage implements Function { if (!template.isCrossZones()) builder.location(findLocationForTemplate.apply(template)); + //TODO: implement status mapping!!! + builder.status(Status.AVAILABLE); return builder.build(); } diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/TemplateToImageTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/TemplateToImageTest.java index 83bcefd268..413f608004 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/TemplateToImageTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/TemplateToImageTest.java @@ -27,6 +27,7 @@ import org.jclouds.cloudstack.domain.Template; import org.jclouds.cloudstack.parse.ListTemplatesResponseTest; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.domain.Location; import org.testng.annotations.Test; @@ -51,20 +52,21 @@ public class TemplateToImageTest { // location free image static Image one = new ImageBuilder().id("2").providerId("2").name("CentOS 5.3(64-bit) no GUI (XenServer)") .operatingSystem(TemplateToOperatingSystemTest.one).description("CentOS 5.3(64-bit) no GUI (XenServer)") - .build(); + .status(Status.AVAILABLE).build(); // location free image static Image two = new ImageBuilder().id("4").providerId("4").name("CentOS 5.5(64-bit) no GUI (KVM)") - .operatingSystem(TemplateToOperatingSystemTest.two).description("CentOS 5.5(64-bit) no GUI (KVM)").build(); + .operatingSystem(TemplateToOperatingSystemTest.two).description("CentOS 5.5(64-bit) no GUI (KVM)") + .status(Status.AVAILABLE).build(); static Image three = new ImageBuilder().id("203").providerId("203").name("Windows 7 KVM") .operatingSystem(TemplateToOperatingSystemTest.three).description("Windows 7 KVM") - .location(ZoneToLocationTest.two).build(); + .location(ZoneToLocationTest.two).status(Status.AVAILABLE).build(); // location free image static Image four = new ImageBuilder().id("7").providerId("7").name("CentOS 5.3(64-bit) no GUI (vSphere)") .operatingSystem(TemplateToOperatingSystemTest.four).description("CentOS 5.3(64-bit) no GUI (vSphere)") - .build(); + .status(Status.AVAILABLE).build(); static Image five = new ImageBuilder().id("241").providerId("241").name("kvmdev4") .operatingSystem(TemplateToOperatingSystemTest.five).description("v5.6.28_Dev4") - .location(ZoneToLocationTest.two).build(); + .location(ZoneToLocationTest.two).status(Status.AVAILABLE).build(); @Test public void test() { diff --git a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/DeltacloudImageToImage.java b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/DeltacloudImageToImage.java index a887502041..b8ad9edd0a 100644 --- a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/DeltacloudImageToImage.java +++ b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/DeltacloudImageToImage.java @@ -23,6 +23,7 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; +import org.jclouds.compute.domain.Image.Status; import com.google.common.base.Function; @@ -47,6 +48,7 @@ public class DeltacloudImageToImage implements Function instanceToNodeStatus = ImmutableMap - . builder().put(InstanceState.PENDING, Status.PENDING).put( - InstanceState.RUNNING, Status.RUNNING).put(InstanceState.SHUTTING_DOWN, Status.PENDING).put( - InstanceState.TERMINATED, Status.TERMINATED).put(InstanceState.STOPPING, Status.PENDING) - .put(InstanceState.STOPPED, Status.SUSPENDED).put(InstanceState.UNRECOGNIZED, Status.UNRECOGNIZED) + public static final Map toPortableNodeStatus = ImmutableMap + . builder() + .put(InstanceState.PENDING, Status.PENDING) + .put(InstanceState.RUNNING, Status.RUNNING) + .put(InstanceState.SHUTTING_DOWN, Status.PENDING) + .put(InstanceState.TERMINATED, Status.TERMINATED) + .put(InstanceState.STOPPING, Status.PENDING) + .put(InstanceState.STOPPED, Status.SUSPENDED) + .put(InstanceState.UNRECOGNIZED, Status.UNRECOGNIZED) .build(); + + @Singleton + @Provides + protected Map toPortableNodeStatus() { + return toPortableNodeStatus; + } + + @VisibleForTesting + public static final Map toPortableImageStatus = ImmutableMap + . builder() + .put(ImageState.AVAILABLE, Image.Status.AVAILABLE) + .put(ImageState.DEREGISTERED, Image.Status.DELETED) + .put(ImageState.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build(); @Singleton @Provides - Map provideServerToNodeStatus() { - return instanceToNodeStatus; + protected Map toPortableImageStatus() { + return toPortableImageStatus; } - + @Override protected void configure() { bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class); diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java index 7f14e25ad5..b500d94dbe 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java @@ -35,6 +35,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.compute.util.ComputeServiceUtils; @@ -43,6 +44,7 @@ import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.ec2.compute.strategy.ReviseParsedImage; import org.jclouds.ec2.domain.Image.Architecture; +import org.jclouds.ec2.domain.Image.ImageState; import org.jclouds.ec2.domain.Image.ImageType; import org.jclouds.logging.Logger; @@ -60,17 +62,21 @@ public class EC2ImageParser implements Function toPortableImageStatus; private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider; private final Supplier> locations; private final Supplier defaultLocation; private final Map> osVersionMap; private final ReviseParsedImage reviseParsedImage; + @Inject - public EC2ImageParser(PopulateDefaultLoginCredentialsForImageStrategy credentialProvider, + public EC2ImageParser(Map toPortableImageStatus, + PopulateDefaultLoginCredentialsForImageStrategy credentialProvider, Map> osVersionMap, @Memoized Supplier> locations, Supplier defaultLocation, ReviseParsedImage reviseParsedImage) { + this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider"); this.locations = checkNotNull(locations, "locations"); this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation"); @@ -120,6 +126,7 @@ public class EC2ImageParser implements Function imageMap = ImmutableMap.of( new RegionAndName(image.getLocation().getId(), image.getProviderId()), image); @@ -190,10 +192,12 @@ public class EC2TemplateBuilderTest { new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "hvm", "ubuntu", true)) .description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false)) + .status(Image.Status.AVAILABLE) .build(), new ImageBuilder().providerId("normal-image").name("image").id("us-east-1/normal-image").location(location) .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "paravirtual", "ubuntu", true)) .description("description").version("1.0").defaultCredentials(new LoginCredentials("root", false)) + .status(Image.Status.AVAILABLE) .build())); // weird compilation error means have to cast this - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=365818 diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java index 147210fdcc..1485987c28 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java @@ -32,6 +32,7 @@ import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.domain.LoginCredentials; +import org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.compute.strategy.ReviseParsedImage; import org.jclouds.ec2.domain.Image; @@ -51,26 +52,32 @@ import com.google.inject.Guice; /** * @author Adrian Cole */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "EC2ImageParserTest") public class EC2ImageParserTest { public void testParseAmznImage() { Set result = convertImages("/amzn_images.xml"); + for (org.jclouds.compute.domain.Image image : result) + assertEquals(image.getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( "137112412989/amzn-ami-0.9.7-beta.i386-ebs").is64Bit(false).build()).description("Amazon") - .defaultCredentials(new LoginCredentials("ec2-user", false)).id("us-east-1/ami-82e4b5c7").name("amzn-ami-0.9.7-beta.i386-ebs") - .providerId("ami-82e4b5c7").location(defaultLocation).userMetadata( - ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build()); + .defaultCredentials(new LoginCredentials("ec2-user", false)).id("us-east-1/ami-82e4b5c7").name( + "amzn-ami-0.9.7-beta.i386-ebs").providerId("ami-82e4b5c7").location(defaultLocation) + .userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status( + org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); assertEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( "amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml").is64Bit(true).build()) - .description("Amazon Linux AMI x86_64 S3").defaultCredentials(new LoginCredentials("ec2-user", false)).id( - "us-east-1/ami-f2e4b5b7").providerId("ami-f2e4b5b7").name("amzn-ami-0.9.7-beta.x86_64-S3").location(defaultLocation) - .userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build()); + .description("Amazon Linux AMI x86_64 S3").defaultCredentials(new LoginCredentials("ec2-user", false)) + .id("us-east-1/ami-f2e4b5b7").providerId("ami-f2e4b5b7").name("amzn-ami-0.9.7-beta.x86_64-S3").location( + defaultLocation) + .userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).status( + org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); + ; } static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id("us-east-1").description( @@ -83,8 +90,9 @@ public class EC2ImageParserTest { .getInstance(Json.class)); Set result = DescribeImagesResponseHandlerTest.parseImages(resource); - EC2ImageParser parser = new EC2ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, - Suppliers.> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers + EC2ImageParser parser = new EC2ImageParser(EC2ComputeServiceDependenciesModule.toPortableImageStatus, + new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, Suppliers + .> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers .ofInstance(defaultLocation), new ReviseParsedImage.NoopReviseParsedImage()); return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull())); } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java index ad62257ee3..be44775af5 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java @@ -68,7 +68,7 @@ public class RunningInstanceToNodeMetadataTest { public void testAllStatesCovered() { for (InstanceState status : InstanceState.values()) { - assert EC2ComputeServiceDependenciesModule.instanceToNodeStatus.containsKey(status) : status; + assert EC2ComputeServiceDependenciesModule.toPortableNodeStatus.containsKey(status) : status; } } @@ -210,7 +210,7 @@ public class RunningInstanceToNodeMetadataTest { RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), ImmutableSet .of(provider), ImmutableMap. of(), - EC2ComputeServiceDependenciesModule.instanceToNodeStatus, instanceToImage); + EC2ComputeServiceDependenciesModule.toPortableNodeStatus, instanceToImage); RunningInstance server = firstInstanceFromResource("/describe_instances_running.xml"); @@ -245,7 +245,7 @@ public class RunningInstanceToNodeMetadataTest { protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, final ImmutableSet locations, final Set images, Map credentialStore) { - Map instanceToNodeStatus = EC2ComputeServiceDependenciesModule.instanceToNodeStatus; + Map instanceToNodeStatus = EC2ComputeServiceDependenciesModule.toPortableNodeStatus; CacheLoader getRealImage = new CacheLoader() { diff --git a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java index 771c3e3593..27c5052eb3 100644 --- a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java +++ b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java @@ -26,6 +26,7 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LoginCredentials; @@ -67,6 +68,7 @@ public class WellKnownImageToImage implements Function { .location(locationSupplier.get()) .name(input.getDescription()) .description(drive.getName()) + .status(Status.AVAILABLE) .operatingSystem( new OperatingSystem.Builder().family(input.getOsFamily()).version(input.getOsVersion()) .name(input.getDescription()).description(drive.getName()).is64Bit(input.is64bit()).build()) diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java index 8d2d1c720d..907fa13e77 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceContextModule.java @@ -38,6 +38,7 @@ import org.jclouds.openstack.nova.compute.functions.NovaImageToOperatingSystem; import org.jclouds.openstack.nova.compute.functions.ServerToNodeMetadata; import org.jclouds.openstack.nova.compute.strategy.NovaComputeServiceAdapter; import org.jclouds.openstack.nova.domain.Flavor; +import org.jclouds.openstack.nova.domain.ImageStatus; import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.domain.ServerStatus; @@ -80,7 +81,7 @@ public class NovaComputeServiceContextModule extends } @VisibleForTesting - public static final Map serverToNodeStatus = ImmutableMap + public static final Map toPortableNodeStatus = ImmutableMap . builder().put(ServerStatus.ACTIVE, Status.RUNNING)// .put(ServerStatus.SUSPENDED, Status.SUSPENDED)// .put(ServerStatus.DELETED, Status.TERMINATED)// @@ -100,8 +101,25 @@ public class NovaComputeServiceContextModule extends @Singleton @Provides - Map provideServerToNodeStatus() { - return serverToNodeStatus; + Map toPortableNodeStatus() { + return toPortableNodeStatus; } + + @VisibleForTesting + public static final Map toPortableImageStatus = ImmutableMap + . builder() + .put(ImageStatus.ACTIVE, Image.Status.AVAILABLE) + .put(ImageStatus.SAVING, Image.Status.PENDING) + .put(ImageStatus.PREPARING, Image.Status.PENDING) + .put(ImageStatus.QUEUED, Image.Status.PENDING) + .put(ImageStatus.FAILED, Image.Status.ERROR) + .put(ImageStatus.UNKNOWN, Image.Status.UNRECOGNIZED) + .put(ImageStatus.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build(); + @Singleton + @Provides + Map toPortableImageStatus() { + return toPortableImageStatus; + } + } diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java index ef811ad851..154fbecb18 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java @@ -18,12 +18,16 @@ */ package org.jclouds.openstack.nova.compute.functions; +import java.util.Map; + import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.Image.Status; +import org.jclouds.openstack.nova.domain.ImageStatus; import com.google.common.base.Function; @@ -33,10 +37,13 @@ import com.google.common.base.Function; */ @Singleton public class NovaImageToImage implements Function { + private final Map toPortableImageStatus; private final Function imageToOs; @Inject - NovaImageToImage(Function imageToOs) { + NovaImageToImage(Map toPortableImageStatus, + Function imageToOs) { + this.toPortableImageStatus = toPortableImageStatus; this.imageToOs = imageToOs; } @@ -47,6 +54,7 @@ public class NovaImageToImage implements Function serverStateToNodeStatus = NovaComputeServiceContextModule.serverToNodeStatus; + Map serverStateToNodeStatus = NovaComputeServiceContextModule.toPortableNodeStatus; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); @@ -100,7 +100,7 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeStatus = NovaComputeServiceContextModule.serverToNodeStatus; + Map serverStateToNodeStatus = NovaComputeServiceContextModule.toPortableNodeStatus; org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); Set hardwares = ImmutableSet.of(); @@ -125,7 +125,7 @@ public class ServerToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeStatus = NovaComputeServiceContextModule.serverToNodeStatus; + Map serverStateToNodeStatus = NovaComputeServiceContextModule.toPortableNodeStatus; Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Server server = ParseServerFromJsonResponseTest.parseServer(); diff --git a/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java b/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java index d5b79955f9..e26338179c 100644 --- a/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java +++ b/apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java @@ -32,6 +32,7 @@ import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.domain.LoginCredentials; +import org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule; import org.jclouds.ec2.compute.functions.EC2ImageParser; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.domain.Image; @@ -74,9 +75,11 @@ public class NovaReviseParsedImageTest { .id("us-east-1/ami-000004d6") .providerId("ami-000004d6") .location(defaultLocation) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE) .userMetadata( ImmutableMap.of("owner", "", "rootDeviceType", "instance-store", "virtualizationType", "paravirtual", "hypervisor", "xen")).build().toString()); + assertEquals(Iterables.get(result, 4).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); } static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id("us-east-1").description( @@ -89,8 +92,9 @@ public class NovaReviseParsedImageTest { .getInstance(Json.class)); Set result = DescribeImagesResponseHandlerTest.parseImages(resource); - EC2ImageParser parser = new EC2ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, - Suppliers.> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers + EC2ImageParser parser = new EC2ImageParser(EC2ComputeServiceDependenciesModule.toPortableImageStatus, + new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, Suppliers + .> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers .ofInstance(defaultLocation), new NovaReviseParsedImage(new ImageToOperatingSystem(map))); return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull())); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/config/NovaComputeServiceContextModule.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/config/NovaComputeServiceContextModule.java index 17f081a5fd..3576c11fb2 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/config/NovaComputeServiceContextModule.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/config/NovaComputeServiceContextModule.java @@ -61,6 +61,7 @@ import org.jclouds.openstack.nova.v1_1.compute.options.NovaTemplateOptions; import org.jclouds.openstack.nova.v1_1.compute.predicates.GetImageWhenImageInZoneHasActiveStatusPredicateWithResult; import org.jclouds.openstack.nova.v1_1.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet; import org.jclouds.openstack.nova.v1_1.domain.KeyPair; +import org.jclouds.openstack.nova.v1_1.domain.Server; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.FlavorInZone; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.ImageInZone; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.SecurityGroupInZone; @@ -72,6 +73,7 @@ import org.jclouds.openstack.nova.v1_1.predicates.FindSecurityGroupWithNameAndRe import org.jclouds.predicates.PredicateWithResult; import org.jclouds.predicates.RetryablePredicate; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; @@ -217,6 +219,46 @@ public class NovaComputeServiceContextModule extends }, locations); } + + @VisibleForTesting + public static final Map toPortableNodeStatus = ImmutableMap + . builder().put(Server.Status.ACTIVE, NodeMetadata.Status.RUNNING)// + .put(Server.Status.SUSPENDED, NodeMetadata.Status.SUSPENDED)// + .put(Server.Status.DELETED, NodeMetadata.Status.TERMINATED)// + .put(Server.Status.PAUSED, NodeMetadata.Status.SUSPENDED)// + .put(Server.Status.RESIZE, NodeMetadata.Status.PENDING)// + .put(Server.Status.VERIFY_RESIZE, NodeMetadata.Status.PENDING)// + .put(Server.Status.REVERT_RESIZE, NodeMetadata.Status.PENDING)// + .put(Server.Status.BUILD, NodeMetadata.Status.PENDING)// + .put(Server.Status.PASSWORD, NodeMetadata.Status.PENDING)// + .put(Server.Status.REBUILD, NodeMetadata.Status.PENDING)// + .put(Server.Status.ERROR, NodeMetadata.Status.ERROR)// + .put(Server.Status.REBOOT, NodeMetadata.Status.PENDING)// + .put(Server.Status.HARD_REBOOT, NodeMetadata.Status.PENDING)// + .put(Server.Status.UNKNOWN, NodeMetadata.Status.UNRECOGNIZED)// + .put(Server.Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).build(); + + @Singleton + @Provides + protected Map toPortableNodeStatus() { + return toPortableNodeStatus; + } + + @VisibleForTesting + public static final Map toPortableImageStatus = ImmutableMap + . builder() + .put(org.jclouds.openstack.nova.v1_1.domain.Image.Status.ACTIVE, Image.Status.AVAILABLE) + .put(org.jclouds.openstack.nova.v1_1.domain.Image.Status.SAVING, Image.Status.PENDING) + .put(org.jclouds.openstack.nova.v1_1.domain.Image.Status.DELETED, Image.Status.DELETED) + .put(org.jclouds.openstack.nova.v1_1.domain.Image.Status.ERROR, Image.Status.ERROR) + .put(org.jclouds.openstack.nova.v1_1.domain.Image.Status.UNKNOWN, Image.Status.UNRECOGNIZED) + .put(org.jclouds.openstack.nova.v1_1.domain.Image.Status.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build(); + + @Singleton + @Provides + protected Map toPortableImageStatus() { + return toPortableImageStatus; + } @Override protected Optional provideImageExtension(Injector i) { diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ImageInZoneToImage.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ImageInZoneToImage.java index 68f6d03c62..5428b43223 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ImageInZoneToImage.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ImageInZoneToImage.java @@ -29,6 +29,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.domain.Location; +import org.jclouds.openstack.nova.v1_1.domain.Image.Status; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.ImageInZone; import com.google.common.base.Function; @@ -40,12 +41,15 @@ import com.google.common.base.Supplier; * @author Matt Stephenson */ public class ImageInZoneToImage implements Function { + private final Map toPortableImageStatus; private final Function imageToOs; private final Supplier> locationIndex; @Inject - public ImageInZoneToImage(Function imageToOs, + public ImageInZoneToImage(Map toPortableImageStatus, + Function imageToOs, Supplier> locationIndex) { + this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); this.imageToOs = checkNotNull(imageToOs, "imageToOs"); this.locationIndex = checkNotNull(locationIndex, "locationIndex"); } @@ -57,6 +61,6 @@ public class ImageInZoneToImage implements Function { org.jclouds.openstack.nova.v1_1.domain.Image image = imageInZone.getImage(); return new ImageBuilder().id(imageInZone.slashEncode()).providerId(image.getId()).name(image.getName()) .userMetadata(image.getMetadata()).operatingSystem(imageToOs.apply(image)).description(image.getName()) - .location(location).build(); + .location(location).status(toPortableImageStatus.get(image.getStatus())).build(); } } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java index 0c8433be2b..bc0cf80e53 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadata.java @@ -49,6 +49,7 @@ import org.jclouds.domain.LocationScope; import org.jclouds.logging.Logger; import org.jclouds.openstack.nova.v1_1.domain.Address; import org.jclouds.openstack.nova.v1_1.domain.Server; +import org.jclouds.openstack.nova.v1_1.domain.Server.Status; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.ServerInZone; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.ZoneAndId; import org.jclouds.util.InetAddresses2; @@ -69,16 +70,18 @@ public class ServerInZoneToNodeMetadata implements Function toPortableNodeStatus; protected final Supplier> locationIndex; protected final Supplier> images; protected final Supplier> hardwares; protected final GroupNamingConvention nodeNamingConvention; @Inject - public ServerInZoneToNodeMetadata(Supplier> locationIndex, - @Memoized Supplier> images, @Memoized Supplier> hardwares, - GroupNamingConvention.Factory namingConvention) { + public ServerInZoneToNodeMetadata(Map toPortableNodeStatus, + Supplier> locationIndex, @Memoized Supplier> images, + @Memoized Supplier> hardwares, GroupNamingConvention.Factory namingConvention) { + this.toPortableNodeStatus = checkNotNull(toPortableNodeStatus, "toPortableNodeStatus"); this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); this.locationIndex = checkNotNull(locationIndex, "locationIndex"); this.images = checkNotNull(images, "images"); @@ -103,7 +106,7 @@ public class ServerInZoneToNodeMetadata implements Function { - - private final OperatingSystem operatingSystem; - - public MockImageToOsConverter(OperatingSystem operatingSystem) { - this.operatingSystem = operatingSystem; - } - - @Override - public OperatingSystem apply(@Nullable Image image) { - return operatingSystem; - } - - @Override - public boolean equals(@Nullable Object o) { - return false; - } + @SuppressWarnings("unchecked") + private static Function constant(OperatingSystem operatingSystem){ + return Function.class.cast(Functions.constant(operatingSystem)); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/OrphanedGroupsByZoneIdTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/OrphanedGroupsByZoneIdTest.java index baf47f8329..215f1ba836 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/OrphanedGroupsByZoneIdTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/OrphanedGroupsByZoneIdTest.java @@ -30,6 +30,7 @@ import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.openstack.nova.v1_1.compute.config.NovaComputeServiceContextModule; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.ServerInZone; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.ZoneAndName; import org.jclouds.openstack.nova.v1_1.parse.ParseServerTest; @@ -66,7 +67,8 @@ public class OrphanedGroupsByZoneIdTest { ServerInZone withoutHost = new ServerInZone(new ServerInZoneToNodeMetadataTest().expectedServer(), "az-1.region-a.geo-1"); ServerInZone withHost = new ServerInZone(new ParseServerTest().expected(), "az-1.region-a.geo-1"); - ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata(locationIndex, Suppliers + ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata( + NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers .> ofInstance(ImmutableSet. of()), Suppliers .> ofInstance(ImmutableSet. of()), namingConvention); @@ -82,9 +84,10 @@ public class OrphanedGroupsByZoneIdTest { ServerInZone withoutHost = new ServerInZone(new ServerInZoneToNodeMetadataTest().expectedServer(), "az-1.region-a.geo-1"); ServerInZone withHost = new ServerInZone(new ParseServerTest().expected(), "az-1.region-a.geo-1"); - ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata(locationIndex, Suppliers - .> ofInstance(ImmutableSet. of()), Suppliers - .> ofInstance(ImmutableSet. of()), namingConvention); + ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata( + NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers + .> ofInstance(ImmutableSet. of()), Suppliers + .> ofInstance(ImmutableSet. of()), namingConvention); Set set = ImmutableSet.of(converter.apply(withHost), converter.apply(withoutHost)); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadataTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadataTest.java index c19306fbc6..6b9f64b290 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadataTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v1_1/compute/functions/ServerInZoneToNodeMetadataTest.java @@ -39,6 +39,7 @@ import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.openstack.domain.Link; import org.jclouds.openstack.domain.Resource; +import org.jclouds.openstack.nova.v1_1.compute.config.NovaComputeServiceContextModule; import org.jclouds.openstack.nova.v1_1.domain.Server; import org.jclouds.openstack.nova.v1_1.domain.zonescoped.ServerInZone; import org.jclouds.openstack.nova.v1_1.parse.ParseServerTest; @@ -75,7 +76,7 @@ public class ServerInZoneToNodeMetadataTest { .location(zone).build(); Image existingImage = new ImageBuilder().id("az-1.region-a.geo-1/FOOOOOOOO") .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description("foobuntu").build()) - .providerId("FOOOOOOOO").description("foobuntu").location(zone).build(); + .providerId("FOOOOOOOO").description("foobuntu").location(zone).status(Image.Status.AVAILABLE).build(); checkHardwareAndImageStatus(null, existingHardware, "az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54", null, existingImage); @@ -88,7 +89,8 @@ public class ServerInZoneToNodeMetadataTest { .providerId("52415800-8b69-11e0-9b19-734f216543fd").location(zone).build(); Image existingImage = new ImageBuilder().id("az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54") .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description("foobuntu").build()) - .providerId("52415800-8b69-11e0-9b19-734f6f006e54").description("foobuntu").location(zone).build(); + .providerId("52415800-8b69-11e0-9b19-734f6f006e54").description("foobuntu").status(Image.Status.AVAILABLE) + .location(zone).build(); checkHardwareAndImageStatus(existingHardware, existingHardware, existingImage.getId(), existingImage.getOperatingSystem(), existingImage); @@ -105,9 +107,10 @@ public class ServerInZoneToNodeMetadataTest { ServerInZone serverInZoneToConvert = new ServerInZone(serverToConvert, "az-1.region-a.geo-1"); - ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata(locationIndex, - Suppliers.> ofInstance(images), - Suppliers.> ofInstance(hardwares), namingConvention); + ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata( + NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers + .> ofInstance(images), Suppliers + .> ofInstance(hardwares), namingConvention); NodeMetadata convertedNodeMetadata = converter.apply(serverInZoneToConvert); @@ -127,7 +130,8 @@ public class ServerInZoneToNodeMetadataTest { assertEquals(convertedNodeMetadata.getHardware(), expectedHardware); - assertEquals(serverToConvert.getStatus().getNodeStatus(), convertedNodeMetadata.getStatus()); + assertEquals(NovaComputeServiceContextModule.toPortableNodeStatus.get(serverToConvert.getStatus()), + convertedNodeMetadata.getStatus()); assertNotNull(convertedNodeMetadata.getPrivateAddresses()); assertEquals(convertedNodeMetadata.getPrivateAddresses(), ImmutableSet.of("10.176.42.16")); @@ -151,9 +155,10 @@ public class ServerInZoneToNodeMetadataTest { ServerInZone serverInZoneToConvert = new ServerInZone(serverToConvert, "az-1.region-a.geo-1"); - ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata(locationIndex, - Suppliers.> ofInstance(images), - Suppliers.> ofInstance(hardwares), namingConvention); + ServerInZoneToNodeMetadata converter = new ServerInZoneToNodeMetadata( + NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers + .> ofInstance(images), Suppliers + .> ofInstance(hardwares), namingConvention); NodeMetadata convertedNodeMetadata = converter.apply(serverInZoneToConvert); diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceDependenciesModule.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceDependenciesModule.java index 1207c540ac..0a0d7129c2 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceDependenciesModule.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceDependenciesModule.java @@ -64,18 +64,50 @@ import com.google.inject.TypeLiteral; public class VCloudComputeServiceDependenciesModule extends AbstractModule { @VisibleForTesting - public static final Map VAPPSTATUS_TO_NODESTATE = ImmutableMap. builder().put( - Status.OFF, NodeMetadata.Status.SUSPENDED).put(Status.ON, NodeMetadata.Status.RUNNING).put(Status.RESOLVED, NodeMetadata.Status.PENDING) - .put(Status.ERROR, NodeMetadata.Status.ERROR).put(Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).put(Status.DEPLOYED, - NodeMetadata.Status.PENDING).put(Status.INCONSISTENT, NodeMetadata.Status.PENDING).put(Status.UNKNOWN, - NodeMetadata.Status.UNRECOGNIZED).put(Status.MIXED, NodeMetadata.Status.PENDING).put(Status.WAITING_FOR_INPUT, - NodeMetadata.Status.PENDING).put(Status.SUSPENDED, NodeMetadata.Status.SUSPENDED).put(Status.UNRESOLVED, - NodeMetadata.Status.PENDING).build(); + public static final Map toPortableNodeStatus = ImmutableMap + . builder() + .put(Status.OFF, NodeMetadata.Status.SUSPENDED) + .put(Status.ON, NodeMetadata.Status.RUNNING) + .put(Status.RESOLVED, NodeMetadata.Status.PENDING) + .put(Status.MIXED, NodeMetadata.Status.PENDING) + .put(Status.UNKNOWN, NodeMetadata.Status.UNRECOGNIZED) + .put(Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED) + .put(Status.DEPLOYED, NodeMetadata.Status.PENDING) + .put(Status.SUSPENDED, NodeMetadata.Status.SUSPENDED) + .put(Status.WAITING_FOR_INPUT, NodeMetadata.Status.PENDING) + .put(Status.INCONSISTENT, NodeMetadata.Status.PENDING) + .put(Status.ERROR, NodeMetadata.Status.ERROR) + .put(Status.UNRESOLVED, NodeMetadata.Status.PENDING).build(); @Singleton @Provides - protected Map provideVAppStatusToNodeStatus() { - return VAPPSTATUS_TO_NODESTATE; + protected Map toPortableNodeStatus() { + return toPortableNodeStatus; + } + + @VisibleForTesting + public static final Map toPortableImageStatus = ImmutableMap + . builder() + .put(Status.RESOLVED, Image.Status.AVAILABLE) + .put(Status.OFF, Image.Status.AVAILABLE) + .put(Status.MIXED, Image.Status.PENDING) + .put(Status.UNKNOWN, Image.Status.UNRECOGNIZED) + .put(Status.UNRECOGNIZED, Image.Status.UNRECOGNIZED) + .put(Status.DEPLOYED, Image.Status.PENDING) + .put(Status.PENDING_DESCRIPTOR, Image.Status.PENDING) + .put(Status.COPYING, Image.Status.PENDING) + .put(Status.PENDING_CONTENTS, Image.Status.PENDING) + .put(Status.QUARANTINED, Image.Status.PENDING) + .put(Status.QUARANTINE_EXPIRED, Image.Status.ERROR) + .put(Status.REJECTED, Image.Status.ERROR) + .put(Status.TRANSFER_TIMEOUT, Image.Status.ERROR) + .put(Status.ERROR, Image.Status.ERROR) + .put(Status.UNRESOLVED, Image.Status.PENDING).build(); + + @Singleton + @Provides + protected Map toPortableImageStatus() { + return toPortableImageStatus; } @SuppressWarnings("unchecked") diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java index 3bab9811d2..2e0405cbae 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java @@ -20,6 +20,8 @@ package org.jclouds.vcloud.compute.functions; import static com.google.common.base.Preconditions.checkNotNull; +import java.util.Map; + import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; @@ -31,6 +33,7 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; import org.jclouds.ovf.Envelope; +import org.jclouds.vcloud.domain.Status; import org.jclouds.vcloud.domain.VAppTemplate; import com.google.common.base.Function; @@ -45,12 +48,15 @@ public class ImageForVAppTemplate implements Function { @Named(ComputeServiceConstants.COMPUTE_LOGGER) public Logger logger = Logger.NULL; + private final Map toPortableImageStatus; private final Function templateToEnvelope; private final FindLocationForResource findLocationForResource; + @Inject - protected ImageForVAppTemplate(Function templateToEnvelope, + protected ImageForVAppTemplate(Map toPortableImageStatus, Function templateToEnvelope, FindLocationForResource findLocationForResource) { + this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); this.templateToEnvelope = checkNotNull(templateToEnvelope, "templateToEnvelope"); this.findLocationForResource = checkNotNull(findLocationForResource, "findLocationForResource"); } @@ -71,6 +77,7 @@ public class ImageForVAppTemplate implements Function { } builder.description(from.getDescription() != null ? from.getDescription() : from.getName()); builder.operatingSystem(CIMOperatingSystem.toComputeOs(ovf)); + builder.status(toPortableImageStatus.get(from.getStatus())); return builder.build(); } diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/domain/Status.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/domain/Status.java index 9413b3daa3..1baa6af0c2 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/domain/Status.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/domain/Status.java @@ -137,7 +137,19 @@ public enum Status { * * @since vcloud api 1.0 */ - QUARANTINE_EXPIRED; + QUARANTINE_EXPIRED, + /** + * The {@link VAppTemplate} rejected + * + * @since vcloud api 1.0 + */ + REJECTED, + /** + * The {@link VAppTemplate} transfer timeout + * + * @since vcloud api 1.0 + */ + TRANSFER_TIMEOUT; public String value() { switch (this) { @@ -173,6 +185,10 @@ public enum Status { return "14"; case QUARANTINE_EXPIRED: return "15"; + case REJECTED: + return "16"; + case TRANSFER_TIMEOUT: + return "17"; default: return "7"; } @@ -220,6 +236,10 @@ public enum Status { return QUARANTINED; case 15: return QUARANTINE_EXPIRED; + case 16: + return REJECTED; + case 17: + return TRANSFER_TIMEOUT; default: return UNRECOGNIZED; } diff --git a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/ListImagesInVCloudExpectTest.java b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/ListImagesInVCloudExpectTest.java index 91664671a0..0f82ca9afd 100644 --- a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/ListImagesInVCloudExpectTest.java +++ b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/ListImagesInVCloudExpectTest.java @@ -81,8 +81,11 @@ public class ListImagesInVCloudExpectTest extends BaseVCloudComputeServiceExpect // TODO: this looks like a bug, as it says network interfaces .description("This is a special place-holder used for disconnected network interfaces.") .defaultCredentials(LoginCredentials.builder().identity("root").build()) + .status(Image.Status.AVAILABLE) .location(vdcLocation).build(); assertEquals(onlyImage, expectedImage); + assertEquals(onlyImage.getStatus(), Image.Status.AVAILABLE); + } } diff --git a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java index 6b335b26c2..b228b542b6 100644 --- a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java +++ b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadataTest.java @@ -101,7 +101,7 @@ public class VAppToNodeMetadataTest { @Singleton @Provides protected Map provideVAppStatusToNodeStatus() { - return VCloudComputeServiceDependenciesModule.VAPPSTATUS_TO_NODESTATE; + return VCloudComputeServiceDependenciesModule.toPortableNodeStatus; } }); diff --git a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java index b448da1041..fcafc8e2a0 100644 --- a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java +++ b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/config/TerremarkVCloudComputeServiceContextModule.java @@ -59,19 +59,37 @@ import com.google.inject.TypeLiteral; public class TerremarkVCloudComputeServiceContextModule extends BaseComputeServiceContextModule { @VisibleForTesting - public static final Map VAPPSTATUS_TO_NODESTATE = ImmutableMap - . builder().put(Status.OFF, NodeMetadata.Status.SUSPENDED).put(Status.ON, - NodeMetadata.Status.RUNNING).put(Status.RESOLVED, NodeMetadata.Status.PENDING).put( - Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED).put(Status.DEPLOYED, - NodeMetadata.Status.PENDING).put(Status.SUSPENDED, NodeMetadata.Status.SUSPENDED).put( - Status.UNRESOLVED, NodeMetadata.Status.PENDING).build(); + public static final Map toPortableNodeStatus = ImmutableMap + . builder() + .put(Status.OFF, NodeMetadata.Status.SUSPENDED) + .put(Status.ON, NodeMetadata.Status.RUNNING) + .put(Status.RESOLVED, NodeMetadata.Status.PENDING) + .put(Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED) + .put(Status.DEPLOYED, NodeMetadata.Status.PENDING) + .put(Status.SUSPENDED, NodeMetadata.Status.SUSPENDED) + .put(Status.UNRESOLVED, NodeMetadata.Status.PENDING).build(); @Singleton @Provides - protected Map provideVAppStatusToNodeStatus() { - return VAPPSTATUS_TO_NODESTATE; + protected Map toPortableNodeStatus() { + return toPortableNodeStatus; } + + @VisibleForTesting + public static final Map toPortableImageStatus = ImmutableMap + . builder() + .put(Status.RESOLVED, Image.Status.AVAILABLE) + .put(Status.OFF, Image.Status.AVAILABLE) + .put(Status.UNRECOGNIZED, Image.Status.UNRECOGNIZED) + .put(Status.DEPLOYED, Image.Status.PENDING) + .put(Status.UNRESOLVED, Image.Status.PENDING).build(); + @Singleton + @Provides + protected Map toPortableImageStatus() { + return toPortableImageStatus; + } + @Override protected void configure() { super.configure(); diff --git a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/ImageForVCloudExpressVAppTemplate.java b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/ImageForVCloudExpressVAppTemplate.java index 167e1828d7..a06b76b1f1 100644 --- a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/ImageForVCloudExpressVAppTemplate.java +++ b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/functions/ImageForVCloudExpressVAppTemplate.java @@ -20,6 +20,8 @@ package org.jclouds.trmk.vcloud_0_8.compute.functions; import static com.google.common.base.Preconditions.checkNotNull; +import java.util.Map; + import javax.inject.Inject; import org.jclouds.compute.domain.Image; @@ -27,6 +29,7 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.trmk.vcloud_0_8.domain.ReferenceType; +import org.jclouds.trmk.vcloud_0_8.domain.Status; import org.jclouds.trmk.vcloud_0_8.domain.VAppTemplate; import com.google.common.base.Function; @@ -35,6 +38,7 @@ import com.google.common.base.Function; * @author Adrian Cole */ public class ImageForVCloudExpressVAppTemplate implements Function { + private final Map toPortableImageStatus; private final FindLocationForResource findLocationForResource; private final PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider; private final Function osParser; @@ -42,8 +46,9 @@ public class ImageForVCloudExpressVAppTemplate implements Function toPortableImageStatus, FindLocationForResource findLocationForResource, PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider, Function osParser) { + this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); this.findLocationForResource = checkNotNull(findLocationForResource, "findLocationForResource"); this.credentialsProvider = checkNotNull(credentialsProvider, "credentialsProvider"); this.osParser = osParser; @@ -63,6 +68,7 @@ public class ImageForVCloudExpressVAppTemplate implements Function { + + public static enum Status { + /** + * The image is in transition + */ + PENDING, + /** + * The image is visible, and in the process of being deleted. + */ + DELETED, + /** + * The image is available. + */ + AVAILABLE, + /** + * There is an error on the image + */ + ERROR, + /** + * The state of the image is unrecognized. + */ + UNRECOGNIZED; + + } + /** * The operating system installed on this image */ diff --git a/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java index b079e92864..46e283559d 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java @@ -23,11 +23,10 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.net.URI; import java.util.Map; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.domain.internal.ImageImpl; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LoginCredentials; -import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.javax.annotation.Nullable; /** @@ -35,6 +34,7 @@ import org.jclouds.javax.annotation.Nullable; */ public class ImageBuilder extends ComputeMetadataBuilder { private OperatingSystem operatingSystem; + private Status status; private String version; private String description; private LoginCredentials defaultLoginCredentials; @@ -47,7 +47,12 @@ public class ImageBuilder extends ComputeMetadataBuilder { this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); return this; } - + + public ImageBuilder status(Status status) { + this.status = checkNotNull(status, "status"); + return this; + } + public ImageBuilder version(@Nullable String version) { this.version = version; return this; @@ -58,32 +63,6 @@ public class ImageBuilder extends ComputeMetadataBuilder { return this; } - /** - *

will be removed in jclouds 1.4.0

- * - * @see LoginCredentials#shouldAuthenticateSudo - */ - @Deprecated - public ImageBuilder adminPassword(@Nullable String adminPassword) { - if (adminPassword != null) { - Builder builder = defaultLoginCredentials != null ? defaultLoginCredentials.toBuilder() : LoginCredentials - .builder(); - builder.authenticateSudo(true); - builder.password(adminPassword); - this.defaultLoginCredentials = builder.build(); - } - return this; - } - /** - *

will be removed in jclouds 1.4.0

- * - * @see #defaultCredentials(LoginCredentials) - */ - @Deprecated - public ImageBuilder defaultCredentials(@Nullable Credentials defaultLoginCredentials) { - return defaultCredentials(LoginCredentials.fromCredentials(defaultLoginCredentials)); - } - public ImageBuilder defaultCredentials(@Nullable LoginCredentials defaultLoginCredentials) { this.defaultLoginCredentials = defaultLoginCredentials; return this; @@ -130,15 +109,16 @@ public class ImageBuilder extends ComputeMetadataBuilder { @Override public Image build() { - return new ImageImpl(providerId, name, id, location, uri, userMetadata, tags, operatingSystem, description, - version, defaultLoginCredentials); + return new ImageImpl(providerId, name, id, location, uri, userMetadata, tags, operatingSystem, status, + description, version, defaultLoginCredentials); } public static ImageBuilder fromImage(Image image) { return new ImageBuilder().providerId(image.getProviderId()).name(image.getName()).id(image.getId()) .location(image.getLocation()).uri(image.getUri()).userMetadata(image.getUserMetadata()) .tags(image.getTags()).version(image.getVersion()).description(image.getDescription()) - .operatingSystem(image.getOperatingSystem()).defaultCredentials(image.getDefaultCredentials()); + .operatingSystem(image.getOperatingSystem()).status(image.getStatus()) + .defaultCredentials(image.getDefaultCredentials()); } } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java index ca1a8d9276..edf8ceb946 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java @@ -27,10 +27,8 @@ import java.util.Set; import org.jclouds.compute.domain.ComputeType; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LoginCredentials; -import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.javax.annotation.Nullable; /** @@ -42,34 +40,18 @@ public class ImageImpl extends ComputeMetadataImpl implements Image { private static final long serialVersionUID = 7856744554191025307L; private final OperatingSystem operatingSystem; + private final Status status; private final String version; private final String description; private final LoginCredentials defaultCredentials; - /** - *

will be removed in jclouds 1.4.0

- */ - @Deprecated - public ImageImpl(String providerId, String name, String id, Location location, URI uri, - Map userMetadata, Set tags, OperatingSystem operatingSystem, String description, - @Nullable String version, @Nullable String adminPassword, @Nullable Credentials defaultCredentials) { - super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata, tags); - this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); - this.version = version; - this.description = checkNotNull(description, "description"); - Builder builder = LoginCredentials.builder(defaultCredentials); - if (adminPassword != null) { - builder.authenticateSudo(true); - builder.password(adminPassword); - } - this.defaultCredentials = builder.build(); - } public ImageImpl(String providerId, String name, String id, Location location, URI uri, - Map userMetadata, Set tags, OperatingSystem operatingSystem, String description, + Map userMetadata, Set tags, OperatingSystem operatingSystem, Image.Status status, String description, @Nullable String version, @Nullable LoginCredentials defaultCredentials) { super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata, tags); this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); + this.status = checkNotNull(status, "status"); this.version = version; this.description = checkNotNull(description, "description"); this.defaultCredentials = defaultCredentials; @@ -83,6 +65,14 @@ public class ImageImpl extends ComputeMetadataImpl implements Image { return operatingSystem; } + /** + * {@inheritDoc} + */ + @Override + public Status getStatus() { + return status; + } + /** * {@inheritDoc} */ @@ -168,4 +158,6 @@ public class ImageImpl extends ComputeMetadataImpl implements Image { return true; } + + } diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java index 2a7c002dec..991bd18e2d 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java @@ -149,7 +149,7 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda String desc = String.format("stub %s %s", osVersions.getKey(), is64Bit); images.add(new ImageBuilder().ids(id++ + "").name(osVersions.getKey().name()).location(location.get()) .operatingSystem(new OperatingSystem(osVersions.getKey(), desc, version, null, desc, is64Bit)) - .description(desc).build()); + .description(desc).status(Image.Status.AVAILABLE).build()); } } return images.build(); diff --git a/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java b/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java index 992e49f9e5..9a80ef4c3c 100644 --- a/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java +++ b/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java @@ -39,6 +39,7 @@ import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.predicates.ImagePredicates; import org.jclouds.domain.Location; @@ -55,7 +56,7 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -@Test(groups = "unit", singleThreaded = true) +@Test(groups = "unit", singleThreaded = true, testName = "TemplateBuilderImplTest") public class TemplateBuilderImplTest { Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id("aws-ec2").description("aws-ec2").build(); @@ -797,6 +798,7 @@ public class TemplateBuilderImplTest { .name("Ubuntu 11.04 x64") .description("Ubuntu 11.04 x64") .location(region) + .status(Status.AVAILABLE) .operatingSystem( OperatingSystem.builder().name("Ubuntu 11.04 x64").description("Ubuntu 11.04 x64") .is64Bit(true).version("11.04").family(OsFamily.UBUNTU).build()).build(), @@ -805,6 +807,7 @@ public class TemplateBuilderImplTest { .name("Ubuntu 11.04 64-bit") .description("Ubuntu 11.04 64-bit") .location(region) + .status(Status.AVAILABLE) .operatingSystem( OperatingSystem.builder().name("Ubuntu 11.04 64-bit").description("Ubuntu 11.04 64-bit") .is64Bit(true).version("11.04").family(OsFamily.UBUNTU).build()).build())); diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/OSTemplateToImage.java b/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/OSTemplateToImage.java index 3815ddef8f..f7c45277c2 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/OSTemplateToImage.java +++ b/labs/glesys/src/main/java/org/jclouds/glesys/compute/functions/OSTemplateToImage.java @@ -27,6 +27,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamilyVersion64Bit; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.domain.OperatingSystem.Builder; import org.jclouds.glesys.domain.OSTemplate; @@ -52,6 +53,6 @@ public class OSTemplateToImage implements Function { builder.name(template.getName()).description(template.getName()).is64Bit(parsed.is64Bit).version(parsed.version) .family(parsed.family); return new ImageBuilder().ids(template.getName()).name(template.getName()).description(template.getName()) - .operatingSystem(builder.build()).build(); + .operatingSystem(builder.build()).status(Status.AVAILABLE).build(); } } diff --git a/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/CIMOperatingSystemToImage.java b/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/CIMOperatingSystemToImage.java index 6b2bdcbeba..050b9c8807 100644 --- a/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/CIMOperatingSystemToImage.java +++ b/labs/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/CIMOperatingSystemToImage.java @@ -23,6 +23,7 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.CIMOperatingSystem; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; +import org.jclouds.compute.domain.Image.Status; import com.google.common.base.Function; @@ -39,6 +40,7 @@ public class CIMOperatingSystemToImage implements Function { @Named(ComputeServiceConstants.COMPUTE_LOGGER) public Logger logger = Logger.NULL; + private final Map toPortableImageStatus; private final Function templateToEnvelope; private final FindLocationForResource findLocationForResource; + @Inject - protected ImageForVAppTemplate(Function templateToEnvelope, + protected ImageForVAppTemplate(Map toPortableImageStatus, Function templateToEnvelope, FindLocationForResource findLocationForResource) { + this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); this.templateToEnvelope = checkNotNull(templateToEnvelope, "templateToEnvelope"); this.findLocationForResource = checkNotNull(findLocationForResource, "findLocationForResource"); } @@ -76,6 +82,7 @@ public class ImageForVAppTemplate implements Function { } builder.description(from.getDescription() != null ? from.getDescription() : from.getName()); builder.operatingSystem(CIMOperatingSystem.toComputeOs(ovf)); + builder.status(toPortableImageStatus.get(from.getStatus())); return builder.build(); } diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/config/VCloudDirectorRestClientModule.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/config/VCloudDirectorRestClientModule.java index 2f560e50a1..d8af02ac6e 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/config/VCloudDirectorRestClientModule.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/config/VCloudDirectorRestClientModule.java @@ -43,7 +43,6 @@ import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.vcloud.director.v1_5.admin.VCloudDirectorAdminAsyncClient; import org.jclouds.vcloud.director.v1_5.admin.VCloudDirectorAdminClient; import org.jclouds.vcloud.director.v1_5.annotations.Login; -import org.jclouds.vcloud.director.v1_5.compute.util.VCloudDirectorComputeUtils; import org.jclouds.vcloud.director.v1_5.domain.Session; import org.jclouds.vcloud.director.v1_5.domain.SessionWithToken; import org.jclouds.vcloud.director.v1_5.features.CatalogAsyncClient; diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java index fb55c3be7f..3bf037aecb 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java @@ -33,7 +33,6 @@ import org.jclouds.compute.config.ComputeServiceAdapterContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.domain.Location; @@ -174,23 +173,64 @@ public class VirtualBoxComputeServiceContextModule extends } @VisibleForTesting - public static final Map machineToNodeStatus = ImmutableMap - . builder().put(MachineState.Running, Status.RUNNING) - .put(MachineState.PoweredOff, Status.SUSPENDED) - .put(MachineState.DeletingSnapshot, Status.PENDING) - .put(MachineState.DeletingSnapshotOnline, Status.PENDING) - .put(MachineState.DeletingSnapshotPaused, Status.PENDING) - .put(MachineState.FaultTolerantSyncing, Status.PENDING) - .put(MachineState.LiveSnapshotting, Status.PENDING) - .put(MachineState.SettingUp, Status.PENDING) - .put(MachineState.Starting, Status.PENDING) - .put(MachineState.Stopping, Status.PENDING) - .put(MachineState.Restoring, Status.PENDING) + public static final Map toPortableNodeStatus = ImmutableMap + . builder().put(MachineState.Running, NodeMetadata.Status.RUNNING) + .put(MachineState.PoweredOff, NodeMetadata.Status.SUSPENDED) + .put(MachineState.DeletingSnapshot, NodeMetadata.Status.PENDING) + .put(MachineState.DeletingSnapshotOnline, NodeMetadata.Status.PENDING) + .put(MachineState.DeletingSnapshotPaused, NodeMetadata.Status.PENDING) + .put(MachineState.FaultTolerantSyncing, NodeMetadata.Status.PENDING) + .put(MachineState.LiveSnapshotting, NodeMetadata.Status.PENDING) + .put(MachineState.SettingUp, NodeMetadata.Status.PENDING) + .put(MachineState.Starting, NodeMetadata.Status.PENDING) + .put(MachineState.Stopping, NodeMetadata.Status.PENDING) + .put(MachineState.Restoring, NodeMetadata.Status.PENDING) // TODO What to map these states to? - .put(MachineState.FirstOnline, Status.PENDING).put(MachineState.FirstTransient, Status.PENDING) - .put(MachineState.LastOnline, Status.PENDING).put(MachineState.LastTransient, Status.PENDING) - .put(MachineState.Teleported, Status.PENDING).put(MachineState.TeleportingIn, Status.PENDING) - .put(MachineState.TeleportingPausedVM, Status.PENDING).put(MachineState.Aborted, Status.ERROR) - .put(MachineState.Stuck, Status.ERROR).put(MachineState.Null, Status.UNRECOGNIZED).build(); - + .put(MachineState.FirstOnline, NodeMetadata.Status.PENDING) + .put(MachineState.FirstTransient, NodeMetadata.Status.PENDING) + .put(MachineState.LastOnline, NodeMetadata.Status.PENDING) + .put(MachineState.LastTransient, NodeMetadata.Status.PENDING) + .put(MachineState.Teleported, NodeMetadata.Status.PENDING) + .put(MachineState.TeleportingIn, NodeMetadata.Status.PENDING) + .put(MachineState.TeleportingPausedVM, NodeMetadata.Status.PENDING) + .put(MachineState.Aborted, NodeMetadata.Status.ERROR) + .put(MachineState.Stuck, NodeMetadata.Status.ERROR) + .put(MachineState.Null, NodeMetadata.Status.TERMINATED).build(); + + @Singleton + @Provides + protected Map toPortableNodeStatus() { + return toPortableNodeStatus; + } + + @VisibleForTesting + public static final Map toPortableImageStatus = ImmutableMap + . builder().put(MachineState.Running, Image.Status.PENDING) + .put(MachineState.PoweredOff, Image.Status.AVAILABLE) + .put(MachineState.DeletingSnapshot, Image.Status.PENDING) + .put(MachineState.DeletingSnapshotOnline, Image.Status.PENDING) + .put(MachineState.DeletingSnapshotPaused, Image.Status.PENDING) + .put(MachineState.FaultTolerantSyncing, Image.Status.PENDING) + .put(MachineState.LiveSnapshotting, Image.Status.PENDING) + .put(MachineState.SettingUp, Image.Status.PENDING) + .put(MachineState.Starting, Image.Status.PENDING) + .put(MachineState.Stopping, Image.Status.PENDING) + .put(MachineState.Restoring, Image.Status.PENDING) + // TODO What to map these states to? + .put(MachineState.FirstOnline, Image.Status.PENDING) + .put(MachineState.FirstTransient, Image.Status.PENDING) + .put(MachineState.LastOnline, Image.Status.PENDING) + .put(MachineState.LastTransient, Image.Status.PENDING) + .put(MachineState.Teleported, Image.Status.PENDING) + .put(MachineState.TeleportingIn, Image.Status.PENDING) + .put(MachineState.TeleportingPausedVM, Image.Status.PENDING) + .put(MachineState.Aborted, Image.Status.ERROR) + .put(MachineState.Stuck, Image.Status.ERROR) + .put(MachineState.Null, Image.Status.DELETED).build(); + + @Singleton + @Provides + protected Map toPortableImageStatus() { + return toPortableImageStatus; + } } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java index 37dbb7fc89..bff48a2632 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java @@ -142,7 +142,7 @@ public class YamlImage { .version(arg0.os_version).is64Bit(arg0.os_64bit).arch(arg0.os_arch).build(); return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description) - .operatingSystem(operatingSystem).build(); + .operatingSystem(operatingSystem).status(Image.Status.AVAILABLE).build(); } }; diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java index dab6dac6ec..0b6ab199f0 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java @@ -32,10 +32,12 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.javax.annotation.Nullable; import org.jclouds.virtualbox.config.VirtualBoxConstants; import org.virtualbox_4_1.IGuestOSType; import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.MachineState; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; @@ -44,11 +46,13 @@ import com.google.common.base.Supplier; @Singleton public class IMachineToImage implements Function { + private final Map toPortableImageStatus; private final Supplier virtualboxManager; private final Map> osVersionMap; @Inject - public IMachineToImage(Supplier virtualboxManager, Map> osVersionMap) { + public IMachineToImage(Map toPortableImageStatus, Supplier virtualboxManager, Map> osVersionMap) { + this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); this.virtualboxManager = checkNotNull(virtualboxManager, "virtualboxManager"); this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap"); } @@ -67,7 +71,7 @@ public class IMachineToImage implements Function { return new ImageBuilder() .id(from.getName().substring(VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX.length(), from.getName().length())).name(from.getName()).description(from.getDescription()) - .operatingSystem(os).build(); + .operatingSystem(os).status(toPortableImageStatus.get(from.getState())).build(); } } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java index 2258236dbe..d4c07c1651 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java @@ -19,11 +19,11 @@ package org.jclouds.virtualbox.functions; -import static org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule.machineToNodeStatus; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_NAME_SEPARATOR; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_PREFIX; import java.util.List; +import java.util.Map; import javax.annotation.Resource; import javax.inject.Named; @@ -58,10 +58,12 @@ public class IMachineToNodeMetadata implements Function @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; + private final Map toPortableNodeStatus; private final MachineUtils machineUtils; @Inject - public IMachineToNodeMetadata(MachineUtils machineUtils) { + public IMachineToNodeMetadata(Map toPortableNodeStatus, MachineUtils machineUtils) { + this.toPortableNodeStatus = toPortableNodeStatus; this.machineUtils = machineUtils; } @@ -90,7 +92,7 @@ public class IMachineToNodeMetadata implements Function nodeMetadataBuilder.hostname(vm.getName()); MachineState vmState = vm.getState(); - NodeMetadata.Status nodeState = machineToNodeStatus.get(vmState); + NodeMetadata.Status nodeState = toPortableNodeStatus.get(vmState); if (nodeState == null) nodeState = Status.UNRECOGNIZED; nodeMetadataBuilder.status(nodeState); diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java index df5c301552..935ed4805c 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java @@ -177,7 +177,7 @@ public class NodeCreator implements Function iMachineToImage = new IMachineToImage(Suppliers.ofInstance(manager), osMap); + Function iMachineToImage = new IMachineToImage( + VirtualBoxComputeServiceContextModule.toPortableImageStatus, Suppliers.ofInstance(manager), osMap); // VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(Suppliers.ofInstance(manager), iMachineToImage, new ImageFromYamlString(), new Supplier() { // // @Override diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java index 8db2dfbeb8..348f800195 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java @@ -34,17 +34,19 @@ import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; +import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule; import org.jclouds.virtualbox.config.VirtualBoxConstants; import org.testng.annotations.Test; import org.virtualbox_4_1.IGuestOSType; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IVirtualBox; +import org.virtualbox_4_1.MachineState; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Suppliers; import com.google.inject.Guice; -@Test(groups = "unit") +@Test(groups = "unit", testName = "IMachineToImageTest") public class IMachineToImageTest { Map> map = new BaseComputeServiceContextModule() { @@ -67,10 +69,12 @@ public class IMachineToImageTest { expect(vm.getDescription()).andReturn("my-ubuntu-machine").anyTimes(); expect(guestOsType.getDescription()).andReturn(linuxDescription).anyTimes(); expect(guestOsType.getIs64Bit()).andReturn(true); + expect(vm.getState()).andReturn(MachineState.PoweredOff); replay(vbm, vBox, vm, guestOsType); - IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map); + IMachineToImage fn = new IMachineToImage(VirtualBoxComputeServiceContextModule.toPortableImageStatus, Suppliers + .ofInstance(vbm), map); Image image = fn.apply(vm); @@ -80,6 +84,7 @@ public class IMachineToImageTest { assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(image.getOperatingSystem().getVersion(), "10.04"); assertEquals(image.getId(), "my-vm-id"); + assertEquals(image.getStatus(), Image.Status.AVAILABLE); } @@ -100,10 +105,12 @@ public class IMachineToImageTest { expect(vm.getDescription()).andReturn(vmDescription).anyTimes(); expect(guestOsType.getDescription()).andReturn(guestOsDescription).anyTimes(); expect(guestOsType.getIs64Bit()).andReturn(true); + expect(vm.getState()).andReturn(MachineState.Running); replay(vbm, vBox, vm, guestOsType); - IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map); + IMachineToImage fn = new IMachineToImage(VirtualBoxComputeServiceContextModule.toPortableImageStatus, Suppliers + .ofInstance(vbm), map); Image image = fn.apply(vm); @@ -113,6 +120,7 @@ public class IMachineToImageTest { assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(image.getOperatingSystem().getVersion(), "11.04"); assertEquals(image.getId(), "my-vm-id"); + assertEquals(image.getStatus(), Image.Status.PENDING); } @@ -133,10 +141,12 @@ public class IMachineToImageTest { expect(guestOsType.getDescription()).andReturn(unknownOsDescription).anyTimes(); expect(guestOsType.getIs64Bit()).andReturn(true); expect(vBox.getGuestOSType(eq("os-type"))).andReturn(guestOsType); + expect(vm.getState()).andReturn(MachineState.PoweredOff); replay(vbm, vBox, vm, guestOsType); - IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map); + IMachineToImage fn = new IMachineToImage(VirtualBoxComputeServiceContextModule.toPortableImageStatus, Suppliers + .ofInstance(vbm), map); Image image = fn.apply(vm); diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java index 9443c40965..adc755cbdf 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java @@ -29,6 +29,7 @@ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_PREFIX; import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule; import org.jclouds.virtualbox.util.MachineUtils; import org.testng.annotations.Test; import org.virtualbox_4_1.IMachine; @@ -67,7 +68,8 @@ public class IMachineToNodeMetadataTest { replay(vm, nat, natEng, hostOnly, machineUtils); - NodeMetadata node = new IMachineToNodeMetadata(machineUtils).apply(vm); + NodeMetadata node = new IMachineToNodeMetadata(VirtualBoxComputeServiceContextModule.toPortableNodeStatus, + machineUtils).apply(vm); assertEquals(MASTER_NAME, node.getName()); assertEquals(1, node.getPrivateAddresses().size()); @@ -105,7 +107,8 @@ public class IMachineToNodeMetadataTest { replay(vm, nat, natEng, hostOnly, machineUtils); - NodeMetadata node = new IMachineToNodeMetadata(machineUtils).apply(vm); + NodeMetadata node = new IMachineToNodeMetadata(VirtualBoxComputeServiceContextModule.toPortableNodeStatus, + machineUtils).apply(vm); assertEquals(name, node.getName()); assertEquals(group, node.getGroup()); diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java index 8a51a69b74..843071ad80 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java @@ -37,7 +37,7 @@ import com.google.common.collect.Iterables; /** * @author Andrea Turli */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "ImageFromYamlStringTest") public class ImageFromYamlStringTest { public static final Image TEST1 = new ImageBuilder() @@ -46,7 +46,8 @@ public class ImageFromYamlStringTest { .description("ubuntu 11.04 server (i386)") .operatingSystem( OperatingSystem.builder().description("ubuntu").family(OsFamily.UBUNTU).version("11.04") - .arch("x86").build()).build(); + .arch("x86").build()) + .status(Image.Status.AVAILABLE).build(); Map images; diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java index c820dc1094..d48317b563 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java @@ -163,7 +163,7 @@ public class AWSRunningInstanceToNodeMetadataTest { protected AWSRunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, final ImmutableSet locations, Set images, Map credentialStore) { - Map instanceToNodeStatus = EC2ComputeServiceDependenciesModule.instanceToNodeStatus; + Map instanceToNodeStatus = EC2ComputeServiceDependenciesModule.toPortableNodeStatus; final Map backing = ImagesToRegionAndIdMap.imagesToMap(images); diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java index 4893990d11..141e20966b 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java @@ -32,6 +32,7 @@ import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.domain.LoginCredentials; +import org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule; import org.jclouds.ec2.compute.functions.EC2ImageParser; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.domain.Image; @@ -52,7 +53,7 @@ import com.google.inject.Guice; /** * @author Adrian Cole */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "AWSEC2ImageParserTest") public class AWSEC2ImageParserTest { public void testParseAlesticCanonicalImage() { @@ -73,7 +74,9 @@ public class AWSEC2ImageParserTest { "rootDeviceType", "instance-store", "virtualizationType", "paravirtual", "hypervisor", "xen")) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE) .build()); + assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); assertEquals( Iterables.get(result, 4), @@ -84,7 +87,9 @@ public class AWSEC2ImageParserTest { .build()).description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml") .defaultCredentials(new LoginCredentials("ubuntu", false)).id("us-east-1/ami-c0fa1ea9") .providerId("ami-c0fa1ea9").location(defaultLocation).version("20080905") - .userMetadata(ImmutableMap.of("owner", "063491364108", "rootDeviceType", "instance-store")).build()); + .userMetadata(ImmutableMap.of("owner", "063491364108", "rootDeviceType", "instance-store")) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); + assertEquals(Iterables.get(result, 4).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); assertEquals( Iterables.get(result, 6), @@ -102,7 +107,8 @@ public class AWSEC2ImageParserTest { "rootDeviceType", "ebs", "virtualizationType", "paravirtual", "hypervisor", "xen")) - .build()); + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); + assertEquals(Iterables.get(result, 6).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); } @@ -120,7 +126,8 @@ public class AWSEC2ImageParserTest { .description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml") .defaultCredentials(new LoginCredentials("root", false)).id("us-east-1/ami-870de2ee") .providerId("ami-870de2ee").location(defaultLocation).version("5622") - .userMetadata(ImmutableMap.of("owner", "133804938231", "rootDeviceType", "instance-store")).build()); + .userMetadata(ImmutableMap.of("owner", "133804938231", "rootDeviceType", "instance-store")) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); } @@ -143,7 +150,8 @@ public class AWSEC2ImageParserTest { "rootDeviceType", "ebs", "virtualizationType", "hvm", "hypervisor", "xen")) - .build()); + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); + assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); } @@ -160,15 +168,17 @@ public class AWSEC2ImageParserTest { .build()).description("rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml") .defaultCredentials(new LoginCredentials("root", false)).id("us-east-1/ami-ccb35ea5") .providerId("ami-ccb35ea5").location(defaultLocation).version("4.4.10") - .userMetadata(ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store")).build()); + .userMetadata(ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store")) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); + assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); assertEquals( new Gson().toJson(Iterables.get(result, 1)), - "{\"operatingSystem\":{\"family\":\"UBUNTU\",\"arch\":\"paravirtual\",\"version\":\"9.10\",\"description\":\"411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"is64Bit\":true},\"version\":\"4.5.3_EBS_Alpha\",\"description\":\"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"defaultCredentials\":{\"authenticateSudo\":false,\"identity\":\"root\"},\"id\":\"us-east-1/ami-c19db6b5\",\"type\":\"IMAGE\",\"tags\":[],\"providerId\":\"ami-c19db6b5\",\"name\":\"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"paravirtual\",\"hypervisor\":\"xen\"}}"); + "{\"operatingSystem\":{\"family\":\"UBUNTU\",\"arch\":\"paravirtual\",\"version\":\"9.10\",\"description\":\"411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"is64Bit\":true},\"status\":\"AVAILABLE\",\"version\":\"4.5.3_EBS_Alpha\",\"description\":\"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"defaultCredentials\":{\"authenticateSudo\":false,\"identity\":\"root\"},\"id\":\"us-east-1/ami-c19db6b5\",\"type\":\"IMAGE\",\"tags\":[],\"providerId\":\"ami-c19db6b5\",\"name\":\"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"paravirtual\",\"hypervisor\":\"xen\"}}"); assertEquals( new Gson().toJson(Iterables.get(result, 2)), - "{\"operatingSystem\":{\"family\":\"WINDOWS\",\"arch\":\"hvm\",\"version\":\"2003\",\"description\":\"411009282317/RightImage Windows_2003_i386_v5.4.3\",\"is64Bit\":false},\"version\":\"5.4.3\",\"description\":\"Built by RightScale\",\"defaultCredentials\":{\"authenticateSudo\":false,\"identity\":\"root\"},\"id\":\"us-east-1/ami-710c2605\",\"type\":\"IMAGE\",\"tags\":[],\"providerId\":\"ami-710c2605\",\"name\":\"RightImage Windows_2003_i386_v5.4.3\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"hvm\",\"hypervisor\":\"xen\"}}"); + "{\"operatingSystem\":{\"family\":\"WINDOWS\",\"arch\":\"hvm\",\"version\":\"2003\",\"description\":\"411009282317/RightImage Windows_2003_i386_v5.4.3\",\"is64Bit\":false},\"status\":\"AVAILABLE\",\"version\":\"5.4.3\",\"description\":\"Built by RightScale\",\"defaultCredentials\":{\"authenticateSudo\":false,\"identity\":\"root\"},\"id\":\"us-east-1/ami-710c2605\",\"type\":\"IMAGE\",\"tags\":[],\"providerId\":\"ami-710c2605\",\"name\":\"RightImage Windows_2003_i386_v5.4.3\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"hvm\",\"hypervisor\":\"xen\"}}"); } public void testParseAmznImage() { @@ -190,7 +200,8 @@ public class AWSEC2ImageParserTest { "rootDeviceType", "ebs", "virtualizationType", "paravirtual", "hypervisor", "xen")) - .build()); + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); + assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); assertEquals( Iterables.get(result, 3), @@ -208,7 +219,9 @@ public class AWSEC2ImageParserTest { "rootDeviceType", "ebs", "virtualizationType", "paravirtual", "hypervisor", "xen")) - .build()); + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); + assertEquals(Iterables.get(result, 3).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); + } static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id("us-east-1") @@ -221,9 +234,10 @@ public class AWSEC2ImageParserTest { .getInstance(Json.class)); Set result = DescribeImagesResponseHandlerTest.parseImages(resource); - EC2ImageParser parser = new EC2ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, - Suppliers.> ofInstance(ImmutableSet. of(defaultLocation)), - Suppliers.ofInstance(defaultLocation), new AWSEC2ReviseParsedImage(map)); + EC2ImageParser parser = new EC2ImageParser(EC2ComputeServiceDependenciesModule.toPortableImageStatus, + new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, Suppliers + .> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers + .ofInstance(defaultLocation), new AWSEC2ReviseParsedImage(map)); return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull())); } } diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java index c85cf1f944..e66252726c 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java @@ -57,7 +57,8 @@ public class AWSEC2ReviseParsedImageTest { Image from = newImage("amazon", "Windows_Server-2008-R2_SP1-English-64Bit-Base-2012.03.13"); OperatingSystem.Builder osBuilder = OperatingSystem.builder().description("test"); - ImageBuilder builder = new ImageBuilder().id("1").operatingSystem(osBuilder.build()).description("test"); + ImageBuilder builder = new ImageBuilder().id("1").operatingSystem(osBuilder.build()).status( + org.jclouds.compute.domain.Image.Status.AVAILABLE).description("test"); OsFamily family = OsFamily.WINDOWS; rpi.reviseParsedImage(from, builder, family, osBuilder); @@ -74,7 +75,8 @@ public class AWSEC2ReviseParsedImageTest { Image from = newImage("amazon", "Windows-2008R2-SP1-English-Base-2012.01.12"); OperatingSystem.Builder osBuilder = OperatingSystem.builder().description("test"); - ImageBuilder builder = new ImageBuilder().id("1").operatingSystem(osBuilder.build()).description("test"); + ImageBuilder builder = new ImageBuilder().id("1").operatingSystem(osBuilder.build()).status( + org.jclouds.compute.domain.Image.Status.AVAILABLE).description("test"); OsFamily family = OsFamily.WINDOWS; rpi.reviseParsedImage(from, builder, family, osBuilder); diff --git a/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java b/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java index be7dc10a7b..bd5cc3a898 100644 --- a/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java +++ b/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java @@ -32,6 +32,7 @@ import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.domain.LoginCredentials; +import org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule; import org.jclouds.ec2.compute.functions.EC2ImageParser; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.domain.Image; @@ -52,7 +53,7 @@ import com.google.inject.Guice; /** * @author Adrian Cole */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "EucalyptusPartnerCloudReviseParsedImageTest") public class EucalyptusPartnerCloudReviseParsedImageTest { public void testParseEucalyptusImage() { @@ -74,7 +75,9 @@ public class EucalyptusPartnerCloudReviseParsedImageTest { .location(defaultLocation) .userMetadata( ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store", "virtualizationType", - "paravirtual", "hypervisor", "xen")).build().toString()); + "paravirtual", "hypervisor", "xen")) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build().toString()); + assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); assertEquals( Iterables.get(result, 1).toString(), @@ -90,7 +93,9 @@ public class EucalyptusPartnerCloudReviseParsedImageTest { .location(defaultLocation) .userMetadata( ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store", "virtualizationType", - "paravirtual", "hypervisor", "xen")).build().toString()); + "paravirtual", "hypervisor", "xen")) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build().toString()); + assertEquals(Iterables.get(result, 1).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); assertEquals( Iterables.get(result, 2).toString(), @@ -106,7 +111,9 @@ public class EucalyptusPartnerCloudReviseParsedImageTest { .location(defaultLocation) .userMetadata( ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store", "virtualizationType", - "paravirtual", "hypervisor", "xen")).build().toString()); + "paravirtual", "hypervisor", "xen")) + .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build().toString()); + assertEquals(Iterables.get(result, 2).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); } @@ -120,8 +127,9 @@ public class EucalyptusPartnerCloudReviseParsedImageTest { .getInstance(Json.class)); Set result = DescribeImagesResponseHandlerTest.parseImages(resource); - EC2ImageParser parser = new EC2ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, - Suppliers.> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers + EC2ImageParser parser = new EC2ImageParser(EC2ComputeServiceDependenciesModule.toPortableImageStatus, + new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, Suppliers + .> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers .ofInstance(defaultLocation), new EucalyptusPartnerCloudReviseParsedImage(map)); return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull())); } diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java index e3e258a5a5..7c3a5125b8 100644 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java +++ b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java @@ -42,6 +42,7 @@ import org.jclouds.gogrid.compute.strategy.GoGridComputeServiceAdapter; import org.jclouds.gogrid.domain.Option; import org.jclouds.gogrid.domain.Server; import org.jclouds.gogrid.domain.ServerImage; +import org.jclouds.gogrid.domain.ServerImageState; import org.jclouds.gogrid.domain.ServerState; import com.google.common.annotations.VisibleForTesting; @@ -85,23 +86,37 @@ public class GoGridComputeServiceContextModule extends } @VisibleForTesting - static final Map serverStateToNodeStatus = ImmutableMap. builder() - .put(ServerState.ON, Status.RUNNING)// - .put(ServerState.STARTING, Status.PENDING)// - .put(ServerState.OFF, Status.SUSPENDED)// - .put(ServerState.STOPPING, Status.PENDING)// - .put(ServerState.RESTARTING, Status.PENDING)// - .put(ServerState.SAVING, Status.PENDING)// - .put(ServerState.UNRECOGNIZED, Status.UNRECOGNIZED)// - .put(ServerState.RESTORING, Status.PENDING)// + static final Map toPortableNodeStatus = ImmutableMap. builder() + .put(ServerState.ON, Status.RUNNING) + .put(ServerState.STARTING, Status.PENDING) + .put(ServerState.OFF, Status.SUSPENDED) + .put(ServerState.STOPPING, Status.PENDING) + .put(ServerState.RESTARTING, Status.PENDING) + .put(ServerState.SAVING, Status.PENDING) + .put(ServerState.UNRECOGNIZED, Status.UNRECOGNIZED) + .put(ServerState.RESTORING, Status.PENDING) .put(ServerState.UPDATING, Status.PENDING).build(); @Singleton @Provides - Map provideServerToNodeStatus() { - return serverStateToNodeStatus; + Map toPortableNodeStatus() { + return toPortableNodeStatus; } + + @VisibleForTesting + static final Map toPortableImageStatus = ImmutableMap + . builder() + .put(ServerImageState.AVAILABLE, Image.Status.AVAILABLE) + .put(ServerImageState.SAVING, Image.Status.PENDING) + .put(ServerImageState.TRASH, Image.Status.DELETED) + .put(ServerImageState.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build(); + @Singleton + @Provides + Map toPortableImageStatus() { + return toPortableImageStatus; + } + /** * Finds matches to required configurations. GoGrid's documentation only specifies how much RAM * one can get with different instance types. The # of cores and disk sizes are purely empyrical diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerImageToImage.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerImageToImage.java index 52aedc3328..604815e3ad 100644 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerImageToImage.java +++ b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerImageToImage.java @@ -31,9 +31,11 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.util.ComputeServiceUtils; import org.jclouds.gogrid.domain.ServerImage; +import org.jclouds.gogrid.domain.ServerImageState; import org.jclouds.logging.Logger; import com.google.common.base.Function; @@ -50,11 +52,14 @@ public class ServerImageToImage implements Function { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - + + private final Map toPortableImageStatus; private final Map> osVersionMap; @Inject - ServerImageToImage(Map> osVersionMap) { + ServerImageToImage(Map toPortableImageStatus, + Map> osVersionMap) { + this.toPortableImageStatus = toPortableImageStatus; this.osVersionMap = osVersionMap; } @@ -93,6 +98,7 @@ public class ServerImageToImage implements Function { builder.name(from.getFriendlyName()); builder.description(from.getDescription()); builder.operatingSystem(parseOs(from)); + builder.status(toPortableImageStatus.get(from.getState())); return builder.build(); } diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java index 0ef1b33939..81d84f9376 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java @@ -31,7 +31,7 @@ public class GoGridComputeServiceContextModuleTest { public void testAllStatusCovered() { for (ServerState state : ServerState.values()) { - assert GoGridComputeServiceContextModule.serverStateToNodeStatus.containsKey(state) : state; + assert GoGridComputeServiceContextModule.toPortableNodeStatus.containsKey(state) : state; } } diff --git a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java index 050b5f88be..0af668e5b3 100644 --- a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java +++ b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java @@ -31,6 +31,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; import org.jclouds.rimuhosting.miro.RimuHostingClient; @@ -66,6 +67,7 @@ public class RimuHostingImageSupplier implements Supplier> builder.name(from.getDescription()); builder.description(from.getDescription()); builder.operatingSystem(parseOs(from)); + builder.status(Status.AVAILABLE); images.add(builder.build()); } logger.debug("<< images(%d)", images.size()); diff --git a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java index 3c20cbf76f..2f7ad3e4a2 100644 --- a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java +++ b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java @@ -46,6 +46,7 @@ public class SlicehostImageToImage implements Function { .ids(imageId().apply(productItem)) .description(description) .operatingSystem(os) + .status(Image.Status.AVAILABLE) .build(); } diff --git a/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/ProductItemToImageTest.java b/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/ProductItemToImageTest.java index 39f8c9babc..33da52801c 100644 --- a/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/ProductItemToImageTest.java +++ b/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/ProductItemToImageTest.java @@ -46,7 +46,7 @@ import com.google.common.collect.ImmutableSet; * * @author Jason King */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "ProductItemToImageTest") public class ProductItemToImageTest { // Operating Systems available MAR 2012 private static final List operatingSystems = Arrays.asList( diff --git a/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java b/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java index 2b668ba698..fa8be24ad2 100644 --- a/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java +++ b/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java @@ -212,7 +212,8 @@ public class VirtualGuestToNodeMetadataTest { @Override public Image getImage(VirtualGuest guest) { return new ImageBuilder().ids("123").description("mocked image") - .operatingSystem(OperatingSystem.builder().description("foo os").build()).build(); + .operatingSystem(OperatingSystem.builder().description("foo os").build()) + .status(Image.Status.AVAILABLE).build(); } } } diff --git a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerManagerImageToImage.java b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerManagerImageToImage.java index 28fe56b947..1084ce2d6d 100644 --- a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerManagerImageToImage.java +++ b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerManagerImageToImage.java @@ -26,6 +26,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Image.Status; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; @@ -55,6 +56,7 @@ public class ServerManagerImageToImage implements Function Date: Thu, 31 May 2012 10:16:09 +0100 Subject: [PATCH 09/73] Adding multiple varargs HttpRequestOptions support --- .../internal/RestAnnotationProcessor.java | 31 +++---- .../internal/RestAnnotationProcessorTest.java | 86 +++++++++++-------- 2 files changed, 62 insertions(+), 55 deletions(-) diff --git a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java index 30478ebd0a..a0268d6b9a 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -472,8 +472,7 @@ public class RestAnnotationProcessor { } Payload payload = null; - HttpRequestOptions options = findOptionsIn(method, args); - if (options != null) { + for(HttpRequestOptions options : findOptionsIn(method, args)) { injector.injectMembers(options);// TODO test case for (Entry header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), Strings2.replaceTokens(header.getValue(), tokenValues.entries())); @@ -1051,30 +1050,26 @@ public class RestAnnotationProcessor { } //TODO: change to LoadingCache findOptionsIn(Method method, Object... args) throws ExecutionException { + ImmutableSet.Builder result = ImmutableSet.builder(); + for (int index : methodToIndexesOfOptions.get(method)) { if (args.length >= index + 1) {// accomodate varargs if (args[index] instanceof Object[]) { - Object[] options = (Object[]) args[index]; - if (options.length == 0) { - } else if (options.length == 1) { - if (options[0] instanceof HttpRequestOptions) { - HttpRequestOptions binder = (HttpRequestOptions) options[0]; - injector.injectMembers(binder); - return binder; - } - } else { - if (options[0] instanceof HttpRequestOptions) { - throw new IllegalArgumentException("we currently do not support multiple varargs options in: " - + method.getName()); + for (Object option : (Object[]) args[index]) { + if (option instanceof HttpRequestOptions) { + result.add((HttpRequestOptions) option); } } } else { - return (HttpRequestOptions) args[index]; + for (; index < args.length; index++) { + if (args[index] instanceof HttpRequestOptions) { + result.add((HttpRequestOptions) args[index]); + } + } } } } - return null; + return result.build(); } public Multimap buildHeaders(Collection> tokenValues, Method method, diff --git a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java index 9b18a027f3..cd979810a5 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -511,6 +511,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST public void varargs(HttpRequestOptions... options); + @POST + public void varargsWithReq(String required, HttpRequestOptions... options); + @POST public void post(HttpRequestOptions options); @@ -530,6 +533,12 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "", "application/octet-stream", false); } + + private class TestHttpRequestOptions extends BaseHttpRequestOptions { + TestHttpRequestOptions payload(String payload) { this.payload = payload; return this; } + TestHttpRequestOptions headerParams(Multimap headers) { this.headers.putAll(headers); return this; } + TestHttpRequestOptions queryParams(Multimap params) { this.queryParameters.putAll(params); return this; } + } public void testHttpRequestOptionsPayloadParam() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPayloadParamVarargs.class.getMethod("post", Payload.class); @@ -541,48 +550,51 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testHttpRequestWithOnlyContentType() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPayloadParamVarargs.class.getMethod("post", HttpRequestOptions.class); - verifyTestPostOptions(method); - } - - public void testPayloadParamVarargs() throws SecurityException, NoSuchMethodException, IOException { - Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance(HttpRequestOptions.class, 0) - .getClass()); - verifyTestPostOptions(method); - } - - private void verifyTestPostOptions(Method method) throws IOException { - HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, new HttpRequestOptions() { - - public Multimap buildMatrixParameters() { - return LinkedHashMultimap.create(); - } - - public String buildPathSuffix() { - return null; - } - - public Multimap buildQueryParameters() { - return LinkedHashMultimap.create(); - } - - public Multimap buildFormParameters() { - return LinkedHashMultimap.create(); - } - - public Multimap buildRequestHeaders() { - return LinkedHashMultimap.create(); - } - - public String buildStringPayload() { - return "fooya"; - } - - }); + HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, new TestHttpRequestOptions().payload("fooya")); assertRequestLineEquals(request, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "fooya", "application/unknown", false); } + public void testHeaderAndQueryVarargs() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance(HttpRequestOptions.class, 0) + .getClass()); + HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, + new TestHttpRequestOptions().payload("fooya"), + new TestHttpRequestOptions().headerParams(ImmutableMultimap.of("X-header-1", "fooya")), + new TestHttpRequestOptions().queryParams(ImmutableMultimap.of("key", "value"))); + assertRequestLineEquals(request, "POST http://localhost:9999?key=value HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "X-header-1: fooya\n"); + assertPayloadEquals(request, "fooya", "application/unknown", false); + } + + public void testHeaderAndQueryVarargsPlusReq() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPayloadParamVarargs.class.getMethod("varargsWithReq", String.class, Array.newInstance(HttpRequestOptions.class, 0) + .getClass()); + HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, "required param", + new Object[]{ new TestHttpRequestOptions().payload("fooya"), + new TestHttpRequestOptions().headerParams(ImmutableMultimap.of("X-header-1", "fooya")), + new TestHttpRequestOptions().queryParams(ImmutableMultimap.of("key", "value"))}); + assertRequestLineEquals(request, "POST http://localhost:9999?key=value HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "X-header-1: fooya\n"); + assertPayloadEquals(request, "fooya", "application/unknown", false); + } + + public void testDuplicateHeaderAndQueryVarargs() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance(HttpRequestOptions.class, 0) + .getClass()); + HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, + new TestHttpRequestOptions().queryParams(ImmutableMultimap.of("key", "value")), + new TestHttpRequestOptions().payload("fooya"), + new TestHttpRequestOptions().headerParams(ImmutableMultimap.of("X-header-1", "fooya")), + new TestHttpRequestOptions().queryParams(ImmutableMultimap.of("key", "anothervalue")), + new TestHttpRequestOptions().headerParams(ImmutableMultimap.of("X-header-1", "fooya again!")), + new TestHttpRequestOptions().payload("last_payload_wins!")); + assertRequestLineEquals(request, "POST http://localhost:9999?key=value&key=anothervalue HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "X-header-1: fooya\nX-header-1: fooya again!\n"); + assertPayloadEquals(request, "last_payload_wins!", "application/unknown", false); + } + public class TestCustomMethod { @FOO public void foo() { From 03267c6e331792606eb9ae566bed774efc54c662 Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Thu, 31 May 2012 13:36:42 +0100 Subject: [PATCH 10/73] openstack-glance: Adding create, reserve, update, upload and delete methods to ImageClient --- .../openstack/options/BaseListOptions.java | 27 +- .../glance/v1_0/domain/ImageDetails.java | 4 + .../glance/v1_0/domain/StoreType.java | 57 ++++ .../v1_0/features/ImageAsyncClient.java | 66 ++++- .../glance/v1_0/features/ImageClient.java | 69 ++++- .../ParseImageDetailsFromHeaders.java | 43 +-- .../v1_0/options/CreateImageOptions.java | 126 ++++++++ .../glance/v1_0/options/ImageField.java | 45 +++ .../glance/v1_0/options/ListImageOptions.java | 240 +++++++++++++++ .../v1_0/options/UpdateImageOptions.java | 233 +++++++++++++++ .../v1_0/features/ImageClientExpectTest.java | 278 ++++++++++++++++++ .../v1_0/features/ImageClientLiveTest.java | 76 ++++- .../v1_0/parse/ParseImageDetailsTest.java | 65 ++++ .../src/test/resources/image.json | 1 + 14 files changed, 1281 insertions(+), 49 deletions(-) create mode 100644 labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/StoreType.java create mode 100644 labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java create mode 100644 labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ImageField.java create mode 100644 labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java create mode 100644 labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java create mode 100644 labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/parse/ParseImageDetailsTest.java create mode 100644 labs/openstack-glance/src/test/resources/image.json diff --git a/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java b/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java index d8e277e661..26f62eded8 100644 --- a/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java +++ b/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java @@ -48,6 +48,10 @@ public class BaseListOptions extends BaseHttpRequestOptions { * Indicates where to begin listing. The list will only include objects that occur after the * offset. This is convenient for pagination: To get the next page of results use the last result * number of the current page + current page offset as the offset. + *

+ * This isn't supported by newer openstack API implementations + * + * @see #marker(String) for the new mechanism to set the page offset */ public BaseListOptions startAt(long offset) { checkState(offset >= 0, "offset must be >= 0"); @@ -55,6 +59,19 @@ public class BaseListOptions extends BaseHttpRequestOptions { return this; } + /** + * The marker parameter is the ID of the last item in the previous list + * (i.e. return the page of items after the marker). + *

+ * This is only supported by newer openstack API implementations + * + * @see #startAt for the old mechanism to set the page offset + */ + public BaseListOptions marker(String marker) { + queryParameters.put("marker", checkNotNull(marker, "marker")); + return this; + } + /** * To reduce load on the service, list operations will return a maximum of 1,000 items at a time. * To navigate the collection, the parameters limit and offset can be set in the URI @@ -81,7 +98,15 @@ public class BaseListOptions extends BaseHttpRequestOptions { } /** - * @see BaseListOptions#maxResults(long) + * @see BaseListOptions#marker + */ + public static BaseListOptions marker(String marker) { + BaseListOptions options = new BaseListOptions(); + return options.marker(marker); + } + + /** + * @see BaseListOptions#maxResults */ public static BaseListOptions maxResults(int maxKeys) { BaseListOptions options = new BaseListOptions(); diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/ImageDetails.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/ImageDetails.java index 6504b68fe8..343143c5d6 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/ImageDetails.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/ImageDetails.java @@ -246,6 +246,10 @@ public class ImageDetails extends Image { return this.location; } + public Optional getOwner() { + return owner; + } + public Date getUpdatedAt() { return this.updatedAt; } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/StoreType.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/StoreType.java new file mode 100644 index 0000000000..3b28ff137b --- /dev/null +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/domain/StoreType.java @@ -0,0 +1,57 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.domain; + +/** + * Backing store types for glance images + * + * @author Adam Lowe + * @see + */ +public enum StoreType { + /** + * Filesystem store + */ + FILE, + /** + * S3 store + */ + S3, + /** + * Openstack swift store + */ + SWIFT, + /** + * RADOS (Reliable Autonomic Distributed Object Store) Block Device store + */ + RBD, + /** + * HTTP (read-only) store + */ + HTTP; + + public String value() { + return name().toLowerCase().replace("_", "+"); + } + + @Override + public String toString() { + return value(); + } +} \ No newline at end of file diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncClient.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncClient.java index 6d4d140a64..da64dfceb6 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncClient.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncClient.java @@ -21,23 +21,24 @@ package org.jclouds.openstack.glance.v1_0.features; import java.io.InputStream; import java.util.Set; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HEAD; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; +import org.jclouds.io.Payload; import org.jclouds.openstack.filters.AuthenticateRequest; import org.jclouds.openstack.glance.v1_0.domain.Image; import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; import org.jclouds.openstack.glance.v1_0.functions.ParseImageDetailsFromHeaders; +import org.jclouds.openstack.glance.v1_0.options.CreateImageOptions; +import org.jclouds.openstack.glance.v1_0.options.ListImageOptions; +import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; @@ -47,6 +48,7 @@ import com.google.common.util.concurrent.ListenableFuture; * * @see ImageClient * @author Adrian Cole + * @author Adam Lowe * @see api doc * @see api src */ @@ -62,7 +64,7 @@ public interface ImageAsyncClient { @Consumes(MediaType.APPLICATION_JSON) @Path("/images") @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> list(); + ListenableFuture> list(ListImageOptions... options); /** * @see ImageClient#listInDetail @@ -72,7 +74,7 @@ public interface ImageAsyncClient { @Consumes(MediaType.APPLICATION_JSON) @Path("/images/detail") @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listInDetail(); + ListenableFuture> listInDetail(ListImageOptions... options); /** * @see ImageClient#show @@ -91,9 +93,49 @@ public interface ImageAsyncClient { @ExceptionParser(ReturnNullOnNotFoundOr404.class) ListenableFuture getAsStream(@PathParam("id") String id); -// POST /images -- Store image data and return metadata about the -// newly-stored image -// PUT /images/ -- Update image metadata and/or upload image -// data for a previously-reserved image -// DELETE /images/ -- Delete the image with id + /** + * @see ImageClient#create + */ + @POST + @Path("/images") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @SelectJson("image") + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture create(@HeaderParam("x-image-meta-name") String name, Payload payload, CreateImageOptions... options); + + /** + * @see ImageClient#reserve + */ + @POST + @Path("/images") + @SelectJson("image") + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture reserve(@HeaderParam("x-image-meta-name") String name, CreateImageOptions... options); + + /** + * @see ImageClient#upload + */ + @PUT + @Path("/images/{id}") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @SelectJson("image") + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture upload(@PathParam("id") String id, Payload imageData, UpdateImageOptions... options); + + /** + * @see ImageClient#update + */ + @PUT + @Path("/images/{id}") + @SelectJson("image") + @Consumes(MediaType.APPLICATION_JSON) + ListenableFuture update(@PathParam("id") String id, UpdateImageOptions... options); + + /** + * @see ImageClient#delete + */ + @DELETE + @Path("/images/{id}") + @ExceptionParser(ReturnFalseOnNotFoundOr404.class) + ListenableFuture delete(@PathParam("id") String id); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageClient.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageClient.java index 4e50c938ba..3e318e3fa9 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageClient.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageClient.java @@ -23,15 +23,21 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; +import org.jclouds.io.Payload; import org.jclouds.javax.annotation.Nullable; +import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; import org.jclouds.openstack.glance.v1_0.domain.Image; import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; +import org.jclouds.openstack.glance.v1_0.options.CreateImageOptions; +import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; +import org.jclouds.openstack.glance.v1_0.options.ListImageOptions; /** * Image Services - * - * @see ImageAsyncClient + * * @author Adrian Cole + * @author Adam Lowe + * @see ImageAsyncClient * @see api doc */ @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @@ -39,13 +45,13 @@ public interface ImageClient { /** * Returns a set of brief metadata about images */ - Set list(); - + Set list(ListImageOptions... options); + /** * Returns a set of detailed metadata about images */ - Set listInDetail(); - + Set listInDetail(ListImageOptions... options); + /** * Return metadata about an image with id */ @@ -53,14 +59,51 @@ public interface ImageClient { ImageDetails show(String id); /** - * Return image data for image with id + * Return image data for image with id */ @Nullable InputStream getAsStream(String id); - -// POST /images -- Store image data and return metadata about the -// newly-stored image -// PUT /images/ -- Update image metadata and/or upload image -// data for a previously-reserved image -// DELETE /images/ -- Delete the image with id + + /** + * Create a new image + * + * @return detailed metadata about the newly stored image + */ + ImageDetails create(String name, Payload imageData, CreateImageOptions... options); + + /** + * Reserve a new image to be uploaded later + * + * @return detailed metadata about the newly stored image + * @see #upload + */ + ImageDetails reserve(String name, CreateImageOptions... options); + + /** + * Adjust the metadata stored for an existing image + * + * @return detailed metadata about the updated image + */ + ImageDetails update(String id, UpdateImageOptions... options); + + /** + * Upload image data for a previously-reserved image + *

+ * If an image was previously reserved, and thus is in the queued state, then image data can be added using this method. + * If the image already as data associated with it (e.g. not in the queued state), then you will receive a 409 + * Conflict exception. + * + * @param imageData the new image to upload + * @param options can be used to adjust the metadata stored for the image in the same call + * @return detailed metadata about the updated image + * @see #reserve + */ + ImageDetails upload(String id, Payload imageData, UpdateImageOptions... options); + + /** + * Delete the image with the specified id + * + * @return true if successful + */ + Boolean delete(String id); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/ParseImageDetailsFromHeaders.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/ParseImageDetailsFromHeaders.java index 4edb1915b4..7c8ecbe890 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/ParseImageDetailsFromHeaders.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/ParseImageDetailsFromHeaders.java @@ -18,16 +18,19 @@ */ package org.jclouds.openstack.glance.v1_0.functions; +import static org.jclouds.openstack.glance.v1_0.options.ImageField.*; + import javax.inject.Inject; import org.jclouds.date.DateService; import org.jclouds.http.HttpResponse; import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; -import org.jclouds.openstack.glance.v1_0.domain.Image; import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; +import org.jclouds.openstack.glance.v1_0.domain.Image.Status; import com.google.common.base.Function; +import com.google.common.base.Optional; /** * This parses {@link ImageDetails} from HTTP headers. @@ -44,23 +47,27 @@ public class ParseImageDetailsFromHeaders implements Function builder = ImageDetails.builder() - .id(from.getFirstHeaderOrNull("X-Image-Meta-Id")) - .name(from.getFirstHeaderOrNull("X-Image-Meta-Name")) - .checksum(from.getFirstHeaderOrNull("X-Image-Meta-Checksum")) - .containerFormat(ContainerFormat.fromValue(from.getFirstHeaderOrNull("X-Image-Meta-Container_format"))) - .diskFormat(DiskFormat.fromValue(from.getFirstHeaderOrNull("X-Image-Meta-Disk_format"))) - .size(Long.parseLong(from.getFirstHeaderOrNull("X-Image-Meta-Size"))) - .minDisk(Long.parseLong(from.getFirstHeaderOrNull("X-Image-Meta-Min_disk"))) - .minRam(Long.parseLong(from.getFirstHeaderOrNull("X-Image-Meta-Min_ram"))) - .isPublic(Boolean.parseBoolean(from.getFirstHeaderOrNull("X-Image-Meta-Is_public"))) - .createdAt(dateService.iso8601SecondsDateParse(from.getFirstHeaderOrNull("X-Image-Meta-Created_at"))) - .updatedAt(dateService.iso8601SecondsDateParse(from.getFirstHeaderOrNull("X-Image-Meta-Updated_at"))) - .owner(from.getFirstHeaderOrNull("X-Image-Meta-Owner")) - .status(Image.Status.fromValue(from.getFirstHeaderOrNull("X-Image-Meta-Status"))); - - String deletedAt = from.getFirstHeaderOrNull("X-Image-Meta-Deleted_at"); - if (deletedAt != null) - builder.deletedAt(dateService.iso8601SecondsDateParse(deletedAt)); + .id(from.getFirstHeaderOrNull(ID.asHeader())) + .name(from.getFirstHeaderOrNull(NAME.asHeader())) + .checksum(Optional.fromNullable(from.getFirstHeaderOrNull(CHECKSUM.asHeader()))) + .minDisk(Long.parseLong(from.getFirstHeaderOrNull(MIN_DISK.asHeader()))) + .minRam(Long.parseLong(from.getFirstHeaderOrNull(MIN_RAM.asHeader()))) + .isPublic(Boolean.parseBoolean(from.getFirstHeaderOrNull(IS_PUBLIC.asHeader()))) + .createdAt(dateService.iso8601SecondsDateParse(from.getFirstHeaderOrNull(CREATED_AT.asHeader()))) + .updatedAt(dateService.iso8601SecondsDateParse(from.getFirstHeaderOrNull(UPDATED_AT.asHeader()))) + .owner(Optional.fromNullable(from.getFirstHeaderOrNull(OWNER.asHeader()))) + .location(Optional.fromNullable(from.getFirstHeaderOrNull(LOCATION.asHeader()))) + .status(Status.fromValue(from.getFirstHeaderOrNull(STATUS.asHeader()))); + + String containerFormat = from.getFirstHeaderOrNull(CONTAINER_FORMAT.asHeader()); + String diskFormat = from.getFirstHeaderOrNull(DISK_FORMAT.asHeader()); + String deletedAt = from.getFirstHeaderOrNull(DELETED_AT.asHeader()); + String size = from.getFirstHeaderOrNull(SIZE.asHeader()); + + if (containerFormat != null) builder.containerFormat(ContainerFormat.fromValue(containerFormat)); + if (diskFormat != null) builder.diskFormat(DiskFormat.fromValue(diskFormat)); + if (deletedAt != null) builder.deletedAt(dateService.iso8601SecondsDateParse(deletedAt)); + if (size != null) builder.size(Long.parseLong(size)); return builder.build(); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java new file mode 100644 index 0000000000..112e2b140a --- /dev/null +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java @@ -0,0 +1,126 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.options; + +import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; +import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; +import org.jclouds.openstack.glance.v1_0.domain.StoreType; + +/** + * @author Adam Lowe + * @see + */ +public class CreateImageOptions extends UpdateImageOptions { + + /** + * When present, Glance will use the supplied identifier for the image instead of generating one. If the identifier + * already exists in that Glance node, then a 409 Conflict will be returned by Glance. The value of the header must + * be a uuid in hexadecimal string notation (i.e. 71c675ab-d94f-49cd-a114-e12490b328d9). + */ + public CreateImageOptions id(String id) { + headers.put(ImageField.ID.asHeader(), id); + return this; + } + + public static class Builder { + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#id + */ + public static CreateImageOptions id(String id) { + return new CreateImageOptions().id(id); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#storeType + */ + public static CreateImageOptions storeType(StoreType storeType) { + return CreateImageOptions.class.cast(new CreateImageOptions().storeType(storeType)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#diskFormat + */ + public static CreateImageOptions diskFormat(DiskFormat diskFormat) { + return CreateImageOptions.class.cast(new CreateImageOptions().diskFormat(diskFormat)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#containerFormat + */ + public static CreateImageOptions containerFormat(ContainerFormat containerFormat) { + return CreateImageOptions.class.cast(new CreateImageOptions().containerFormat(containerFormat)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#size + */ + public static CreateImageOptions size(long size) { + return CreateImageOptions.class.cast(new CreateImageOptions().size(size)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#checksum + */ + public static CreateImageOptions checksum(String checksum) { + return CreateImageOptions.class.cast(new CreateImageOptions().checksum(checksum)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#isPublic + */ + public static CreateImageOptions isPublic(boolean isPublic) { + return CreateImageOptions.class.cast(new CreateImageOptions().isPublic(isPublic)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#isProtected + */ + public static CreateImageOptions isProtected(boolean isProtected) { + return CreateImageOptions.class.cast(new CreateImageOptions().isProtected(isProtected)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#minRam + */ + public static CreateImageOptions minRam(long ram) { + return CreateImageOptions.class.cast(new CreateImageOptions().minRam(ram)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#minDisk + */ + public static CreateImageOptions minDisk(long disk) { + return CreateImageOptions.class.cast(new CreateImageOptions().minDisk(disk)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#owner + */ + public static CreateImageOptions owner(String owner) { + return CreateImageOptions.class.cast(new CreateImageOptions().owner(owner)); + } + + /** + * @see org.jclouds.openstack.glance.v1_0.options.CreateImageOptions#property + */ + public static CreateImageOptions property(String key, String value) { + return CreateImageOptions.class.cast(new CreateImageOptions().property(key, value)); + } + } +} diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ImageField.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ImageField.java new file mode 100644 index 0000000000..fd67d2c355 --- /dev/null +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ImageField.java @@ -0,0 +1,45 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.options; + +import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE; +import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; + +import org.jclouds.util.Strings2; + +import com.google.common.base.CaseFormat; +import com.google.common.base.Strings; + +/** + * Fields used in Glance options + */ +public enum ImageField { + ID, NAME, CHECKSUM, MIN_DISK, MIN_RAM, IS_PUBLIC, PROTECTED, CREATED_AT, UPDATED_AT, DELETED_AT, + OWNER, LOCATION, STATUS, DISK_FORMAT, CONTAINER_FORMAT, SIZE, SIZE_MIN, SIZE_MAX, STORE, PROPERTY; + + public static final String HEADER_PREFIX = "X-Image-Meta-"; + + public String asParam() { + return name().toLowerCase(); + } + + public String asHeader() { + return HEADER_PREFIX + name().charAt(0) + name().substring(1).toLowerCase(); + } +} diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java new file mode 100644 index 0000000000..b095a1cd88 --- /dev/null +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java @@ -0,0 +1,240 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.options; + +import static org.jclouds.openstack.glance.v1_0.options.ImageField.*; + +import java.util.Date; + +import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; +import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; +import org.jclouds.openstack.glance.v1_0.domain.Image.Status; +import org.jclouds.openstack.options.BaseListOptions; + +/** + * @author Adam Lowe + * @see + */ +public class ListImageOptions extends BaseListOptions { + /** + * Return only those images having a matching name attribute + */ + public ListImageOptions name(String name) { + queryParameters.put(NAME.asParam(), name); + return this; + } + + /** + * Return only those images that have the requested status + */ + public ListImageOptions status(Status status) { + queryParameters.put(STATUS.asParam(), status.toString()); + return this; + } + + /** + * Return only those images having a matching container format + */ + public ListImageOptions containerFormat(ContainerFormat containerFormat) { + queryParameters.put(CONTAINER_FORMAT.asParam(), containerFormat.toString()); + return this; + } + + /** + * Return only those images having a matching disk format + */ + public ListImageOptions diskFormat(DiskFormat diskFormat) { + queryParameters.put(DISK_FORMAT.asParam(), diskFormat.toString()); + return this; + } + + /** + * Return only those images having a matching min ram size + */ + public ListImageOptions minRam(long ram) { + queryParameters.put(MIN_RAM.asParam(), Long.toString(ram)); + return this; + } + + /** + * Return only those images having a matching min disk size + */ + public ListImageOptions minDisk(long disk) { + queryParameters.put(MIN_DISK.asParam(), Long.toString(disk)); + return this; + } + + /** + * Return those images that have a size attribute greater than or equal to size + */ + public ListImageOptions minSize(long size) { + queryParameters.put(SIZE_MIN.asParam(), Long.toString(size)); + return this; + } + + /** + * Return those images that have a size attribute less than or equal to size + */ + public ListImageOptions maxSize(long size) { + queryParameters.put(SIZE_MAX.asParam(), Long.toString(size)); + return this; + } + + /** + * Return only public images or only private images + */ + public ListImageOptions isPublic(boolean isPublic) { + queryParameters.put(IS_PUBLIC.asParam(), Boolean.toString(isPublic)); + return this; + } + + /** + * Filter to only protected or unprotected images + */ + public ListImageOptions isProtected(boolean isProtected) { + queryParameters.put(PROTECTED.asParam(), Boolean.toString(isProtected)); + return this; + } + + /** + * Results will be ordered by the specified image attribute. + */ + public ListImageOptions sortBy(ImageField key) { + queryParameters.put("sort_key", key.asParam()); + return this; + } + + /** + * Ascending sort order (smallest first). + *

+ * NOTE: default behavior is to sort descending (largest first) + */ + public ListImageOptions sortAscending() { + queryParameters.put("sort_dir", "asc"); + return this; + } + + public static class Builder { + /** + * @see ListImageOptions#name + */ + public static ListImageOptions name(String name) { + return new ListImageOptions().name(name); + } + + /** + * @see ListImageOptions#diskFormat + */ + public static ListImageOptions diskFormat(DiskFormat diskFormat) { + return new ListImageOptions().diskFormat(diskFormat); + } + + /** + * @see ListImageOptions#containerFormat + */ + public static ListImageOptions containerFormat(ContainerFormat containerFormat) { + return new ListImageOptions().containerFormat(containerFormat); + } + + /** + * @see ListImageOptions#minRam + */ + public static ListImageOptions minRam(long size) { + return new ListImageOptions().minRam(size); + } + + + /** + * @see ListImageOptions#minDisk + */ + public static ListImageOptions minDisk(long size) { + return new ListImageOptions().minDisk(size); + } + + /** + * @see ListImageOptions#minSize + */ + public static ListImageOptions minSize(long size) { + return new ListImageOptions().minSize(size); + } + + /** + * @see ListImageOptions#maxSize + */ + public static ListImageOptions maxSize(long size) { + return new ListImageOptions().maxSize(size); + } + + /** + * @see ListImageOptions#sortBy + */ + public static ListImageOptions status(Status status) { + return new ListImageOptions().status(status); + } + + /** + * @see ListImageOptions#sortBy + */ + public static ListImageOptions sortBy(ImageField sortKey) { + return new ListImageOptions().sortBy(sortKey); + } + + /** + * @see ListImageOptions#sortAscending + */ + public static ListImageOptions sortAscending() { + return new ListImageOptions().sortAscending(); + } + + /** + * @see ListImageOptions#isPublic + */ + public static ListImageOptions isPublic(boolean isPublic) { + return ListImageOptions.class.cast(new ListImageOptions().isPublic(isPublic)); + } + + /** + * @see ListImageOptions#isProtected + */ + public static ListImageOptions isProtected(boolean isProtected) { + return ListImageOptions.class.cast(new ListImageOptions().isProtected(isProtected)); + } + + /** + * @see BaseListOptions#maxResults + */ + public static ListImageOptions maxResults(int limit) { + return ListImageOptions.class.cast(new ListImageOptions().maxResults(limit)); + } + + /** + * @see BaseListOptions#marker + */ + public static ListImageOptions marker(String marker) { + return ListImageOptions.class.cast(new ListImageOptions().marker(marker)); + } + + /** + * @see BaseListOptions#changesSince + */ + public static ListImageOptions changesSince(Date ifModifiedSince) { + return ListImageOptions.class.cast(new BaseListOptions().changesSince(ifModifiedSince)); + } + } +} diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java new file mode 100644 index 0000000000..834ae9a7f3 --- /dev/null +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java @@ -0,0 +1,233 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.options; + +import static org.jclouds.openstack.glance.v1_0.options.ImageField.*; + +import org.jclouds.http.options.BaseHttpRequestOptions; +import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; +import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; +import org.jclouds.openstack.glance.v1_0.domain.StoreType; + +/** + * @author Adam Lowe + * @see + */ +public class UpdateImageOptions extends BaseHttpRequestOptions { + + /** + * Adjust the name of the image + */ + public UpdateImageOptions name(String name) { + headers.put(NAME.asHeader(), name); + return this; + } + + /** + * When present, Glance will attempt to store the disk image data in the backing store indicated by the value of the + * header. If the Glance node does not support the backing store, Glance will return a 400 Bad Request. + */ + public UpdateImageOptions storeType(StoreType storeType) { + headers.put(STORE.asHeader(), storeType.toString()); + return this; + } + + public UpdateImageOptions diskFormat(DiskFormat diskFormat) { + headers.put(DISK_FORMAT.asHeader(), diskFormat.toString()); + return this; + } + + public UpdateImageOptions containerFormat(ContainerFormat containerFormat) { + headers.put(CONTAINER_FORMAT.asHeader(), containerFormat.toString()); + return this; + } + + /** + * When present, Glance assumes that the expected size of the request body will be the value of this header. If the + * length in bytes of the request body does not match the value of this header, Glance will return a 400 Bad Request. + */ + public UpdateImageOptions size(long size) { + headers.put(SIZE.asHeader(), Long.toString(size)); + return this; + } + + /** + * MD5 checksum of the image + *

+ * When present, Glance will verify the checksum generated from the backend store when storing your image against + * this value and return a 400 Bad Request if the values do not match. + */ + public UpdateImageOptions checksum(String checksum) { + headers.put(CHECKSUM.asHeader(), checksum); + return this; + } + + public UpdateImageOptions location(String location) { + headers.put(LOCATION.asHeader(), location); + return this; + } + + /** + * Mark the image as public, meaning that any user may view its metadata and may read the disk image + * from Glance. + */ + public UpdateImageOptions isPublic(boolean isPublic) { + headers.put(IS_PUBLIC.asHeader(), Boolean.toString(isPublic)); + return this; + } + + /** + * Mark the image as protected - if set to true the image cannot be deleted till it is unset. + */ + public UpdateImageOptions isProtected(boolean isProtected) { + headers.put(PROTECTED.asHeader(), Boolean.toString(isProtected)); + return this; + } + + /** + * The expected minimum ram required in megabytes to run this image on a server (default 0). + */ + public UpdateImageOptions minRam(long ram) { + headers.put(MIN_RAM.asHeader(), Long.toString(ram)); + return this; + } + + /** + * The expected minimum disk required in gigabytes to run this image on a server (default 0). + */ + public UpdateImageOptions minDisk(long disk) { + headers.put(MIN_DISK.asHeader(), Long.toString(disk)); + return this; + } + + /** + * Glance normally sets the owner of an image to be the tenant or user (depending on the “owner_is_tenant” + * configuration option) of the authenticated user issuing the request. However, if the authenticated user has the + * Admin role, this default may be overridden by setting this header to null or to a string identifying the owner of + * the image. + */ + public UpdateImageOptions owner(String owner) { + headers.put(OWNER.asHeader(), owner); + return this; + } + + /** + * Custom, free-form image properties stored with the image. + */ + public UpdateImageOptions property(String key, String value) { + if (!key.toLowerCase().startsWith(PROPERTY.asHeader() + "-")) { + key = PROPERTY.asHeader() + "-" + key; + } + headers.put(key, value); + return this; + } + + public static class Builder { + /** + * @see UpdateImageOptions#name + */ + public static UpdateImageOptions name(String name) { + return new UpdateImageOptions().name(name); + } + + /** + * @see UpdateImageOptions#storeType + */ + public static UpdateImageOptions storeType(StoreType storeType) { + return new UpdateImageOptions().storeType(storeType); + } + + /** + * @see UpdateImageOptions#diskFormat + */ + public static UpdateImageOptions diskFormat(DiskFormat diskFormat) { + return new UpdateImageOptions().diskFormat(diskFormat); + } + + /** + * @see UpdateImageOptions#containerFormat + */ + public static UpdateImageOptions containerFormat(ContainerFormat containerFormat) { + return new UpdateImageOptions().containerFormat(containerFormat); + } + + /** + * @see UpdateImageOptions#size + */ + public static UpdateImageOptions size(long size) { + return new UpdateImageOptions().size(size); + } + + /** + * @see UpdateImageOptions#checksum + */ + public static UpdateImageOptions checksum(String checksum) { + return new UpdateImageOptions().checksum(checksum); + } + + /** + * @see UpdateImageOptions#location + */ + public static UpdateImageOptions location(String location) { + return new UpdateImageOptions().location(location); + } + + /** + * @see UpdateImageOptions#isPublic + */ + public static UpdateImageOptions isPublic(boolean isPublic) { + return new UpdateImageOptions().isPublic(isPublic); + } + + /** + * @see UpdateImageOptions#isProtected + */ + public static UpdateImageOptions isProtected(boolean isProtected) { + return new UpdateImageOptions().isProtected(isProtected); + } + + /** + * @see UpdateImageOptions#minRam + */ + public static UpdateImageOptions minRam(long ram) { + return new UpdateImageOptions().minRam(ram); + } + + /** + * @see UpdateImageOptions#minDisk + */ + public static UpdateImageOptions minDisk(long disk) { + return new UpdateImageOptions().minDisk(disk); + } + + /** + * @see UpdateImageOptions#owner + */ + public static UpdateImageOptions owner(String owner) { + return new UpdateImageOptions().owner(owner); + } + + /** + * @see UpdateImageOptions#property + */ + public static UpdateImageOptions property(String key, String value) { + return new UpdateImageOptions().property(key, value); + } + } +} diff --git a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientExpectTest.java b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientExpectTest.java index 4796b15fad..415803bd5c 100644 --- a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientExpectTest.java +++ b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientExpectTest.java @@ -19,19 +19,28 @@ package org.jclouds.openstack.glance.v1_0.features; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.net.URI; +import javax.ws.rs.core.MediaType; + import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; +import org.jclouds.io.payloads.StringPayload; import org.jclouds.openstack.glance.v1_0.GlanceClient; import org.jclouds.openstack.glance.v1_0.functions.ParseImageDetailsFromHeadersTest; import org.jclouds.openstack.glance.v1_0.internal.BaseGlanceClientExpectTest; +import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; +import org.jclouds.openstack.glance.v1_0.parse.ParseImageDetailsTest; import org.jclouds.openstack.glance.v1_0.parse.ParseImagesInDetailTest; import org.jclouds.openstack.glance.v1_0.parse.ParseImagesTest; +import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.util.Strings2; import org.testng.annotations.Test; @@ -40,6 +49,7 @@ import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole + * @author Adam Lowe */ @Test(groups = "unit", testName = "ImageClientExpectTest") public class ImageClientExpectTest extends BaseGlanceClientExpectTest { @@ -198,5 +208,273 @@ public class ImageClientExpectTest extends BaseGlanceClientExpectTest { assertNull(clientWhenNoExist.getImageClientForRegion("az-1.region-a.geo-1").getAsStream("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); } + + public void testCreateWhenResponseIs2xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("POST") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images")) + .headers( + ImmutableMultimap.builder() + .put("x-image-meta-name", "test").put("Accept", MediaType.APPLICATION_JSON).put("X-Auth-Token", authToken).build()) + .payload(payloadFromStringWithContentType("somedata", MediaType.APPLICATION_OCTET_STREAM)) + .build(); + + HttpResponse createResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/image.json")).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, createResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + assertEquals(clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").create("test", new StringPayload("somedata")), + new ParseImageDetailsTest().expected()); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testCreateWhenResponseIs4xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("POST") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images")) + .headers( + ImmutableMultimap.builder() + .put("x-image-meta-name", "test").put("Accept", MediaType.APPLICATION_JSON).put("X-Auth-Token", authToken).build()) + .payload(payloadFromStringWithContentType("somedata", MediaType.APPLICATION_OCTET_STREAM)) + .build(); + + HttpResponse createResponse = HttpResponse.builder().statusCode(401) + .payload(payloadFromResource("/image.json")).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, createResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").create("test", new StringPayload("somedata")); + } + + public void testReserveWhenResponseIs2xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("POST") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images")) + .headers( + ImmutableMultimap.builder() + .put("x-image-meta-name", "test").put("Accept", MediaType.APPLICATION_JSON).put("X-Auth-Token", authToken).build()) + .build(); + + HttpResponse createResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/image.json")).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, createResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + assertEquals(clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").reserve("test"), new ParseImageDetailsTest().expected()); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testReserveWhenResponseIs4xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("POST") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images")) + .headers( + ImmutableMultimap.builder() + .put("x-image-meta-name", "test").put("Accept", MediaType.APPLICATION_JSON).put("X-Auth-Token", authToken).build()) + .build(); + + HttpResponse createResponse = HttpResponse.builder().statusCode(401) + .payload(payloadFromResource("/image.json")).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, createResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").reserve("test"); + } + public void testUpdateMetadataWhenResponseIs2xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("PUT") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images/fcc451d0-f6e4-4824-ad8f-70ec12326d07")) + .headers( + ImmutableMultimap.builder() + .put("Accept", MediaType.APPLICATION_JSON) + .put("X-Image-Meta-Name", "newname") + .put("X-Image-Meta-Is_public", "true") + .put("X-Image-Meta-Protected", "true") + .put("X-Image-Meta-Checksum", "XXXX") + .put("X-Image-Meta-Location", "somewhere") + .put("X-Image-Meta-Min_disk", "10") + .put("X-Image-Meta-Min_ram", "2048") + .put("X-Auth-Token", authToken).build()) + .build(); + + HttpResponse updateResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/image.json")).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, updateResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + assertEquals(clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1") + .update("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + UpdateImageOptions.Builder.name("newname"), + UpdateImageOptions.Builder.isPublic(true), + UpdateImageOptions.Builder.isProtected(true), + UpdateImageOptions.Builder.checksum("XXXX"), + UpdateImageOptions.Builder.location("somewhere"), + UpdateImageOptions.Builder.minDisk(10), + UpdateImageOptions.Builder.minRam(2048)), + new ParseImageDetailsTest().expected()); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void testUpdateMetadataWhenResponseIs4xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("PUT") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images/fcc451d0-f6e4-4824-ad8f-70ec12326d07")) + .headers( + ImmutableMultimap.builder() + .put("Accept", MediaType.APPLICATION_JSON) + .put("X-Image-Meta-Name", "newname") + .put("X-Image-Meta-Is_public", "true") + .put("X-Auth-Token", authToken).build()) + .build(); + + HttpResponse updateResponse = HttpResponse.builder().statusCode(404).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, updateResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1") + .update("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + UpdateImageOptions.Builder.name("newname"), + UpdateImageOptions.Builder.isPublic(true)); + } + + public void testUpdateImageWhenResponseIs2xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("PUT") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images/fcc451d0-f6e4-4824-ad8f-70ec12326d07")) + .headers( + ImmutableMultimap.builder() + .put("Accept", MediaType.APPLICATION_JSON).put("X-Auth-Token", authToken).build()) + .payload(payloadFromStringWithContentType("somenewdata", MediaType.APPLICATION_OCTET_STREAM)) + .build(); + + HttpResponse updateResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/image.json")).build(); + + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, updateResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + assertEquals(clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + new StringPayload("somenewdata")), new ParseImageDetailsTest().expected()); + } + + public void testUpdateNameAndImageWhenResponseIs2xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("PUT") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images/fcc451d0-f6e4-4824-ad8f-70ec12326d07")) + .headers( + ImmutableMultimap.builder() + .put("Accept", MediaType.APPLICATION_JSON) + .put("X-Image-Meta-Name", "anothernewname") + .put("X-Auth-Token", authToken).build()) + .payload(payloadFromStringWithContentType("somenewdata", MediaType.APPLICATION_OCTET_STREAM)) + .build(); + + HttpResponse updateResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/image.json")).build(); + + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, updateResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + assertEquals(clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + new StringPayload("somenewdata"), UpdateImageOptions.Builder.name("anothernewname")), new ParseImageDetailsTest().expected()); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testUpdateNameAndImageWhenResponseIs4xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("PUT") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images/fcc451d0-f6e4-4824-ad8f-70ec12326d07")) + .headers( + ImmutableMultimap.builder() + .put("Accept", MediaType.APPLICATION_JSON) + .put("X-Image-Meta-Name", "anothernewname") + .put("X-Auth-Token", authToken).build()) + .payload(payloadFromStringWithContentType("somenewdata", MediaType.APPLICATION_OCTET_STREAM)) + .build(); + + HttpResponse updateResponse = HttpResponse.builder().statusCode(403).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, updateResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + new StringPayload("somenewdata"), UpdateImageOptions.Builder.name("anothernewname")); + } + + public void testDeleteWhenResponseIs2xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("DELETE") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images/fcc451d0-f6e4-4824-ad8f-70ec12326d07")) + .headers( + ImmutableMultimap.builder() + .put("X-Auth-Token", authToken).build()) + .build(); + + HttpResponse getResponse = HttpResponse.builder().statusCode(200).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, getResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + assertTrue(clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").delete("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); + } + + public void testDeleteWhenResponseIs4xx() throws Exception { + HttpRequest get = HttpRequest + .builder() + .method("DELETE") + .endpoint(URI.create("https://glance.jclouds.org:9292/v1.0/images/fcc451d0-f6e4-4824-ad8f-70ec12326d07")) + .headers( + ImmutableMultimap.builder() + .put("X-Auth-Token", authToken).build()) + .build(); + + HttpResponse getResponse = HttpResponse.builder().statusCode(404).build(); + + GlanceClient clientWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, getResponse); + + assertEquals(clientWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + + assertFalse(clientWhenExist.getImageClientForRegion("az-1.region-a.geo-1").delete("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); + } } diff --git a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java index 88f03d3115..62bf4d7e6c 100644 --- a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java +++ b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java @@ -18,17 +18,34 @@ */ package org.jclouds.openstack.glance.v1_0.features; -import static org.testng.Assert.assertEquals; +import static org.jclouds.openstack.glance.v1_0.options.CreateImageOptions.Builder.containerFormat; +import static org.jclouds.openstack.glance.v1_0.options.CreateImageOptions.Builder.diskFormat; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.io.File; import java.util.Set; +import org.jclouds.io.Payload; +import org.jclouds.io.payloads.FilePayload; +import org.jclouds.io.payloads.StringPayload; +import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; +import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; import org.jclouds.openstack.glance.v1_0.domain.Image; import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; import org.jclouds.openstack.glance.v1_0.internal.BaseGlanceClientLiveTest; +import org.jclouds.openstack.glance.v1_0.options.ListImageOptions; +import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; import org.testng.annotations.Test; +import com.google.common.base.Optional; +import com.google.common.collect.Iterables; + /** * @author Adrian Cole + * @author Adam Lowe */ @Test(groups = "live", testName = "ImageClientLiveTest") public class ImageClientLiveTest extends BaseGlanceClientLiveTest { @@ -37,7 +54,7 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { public void testList() throws Exception { for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { ImageClient client = glanceContext.getApi().getImageClientForRegion(zoneId); - Set response = client.list(); + Set response = client.list(ListImageOptions.Builder.maxResults(100)); assert null != response; for (Image image : response) { checkImage(image); @@ -49,8 +66,6 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { assert image.getId() != null : image; assert image.getSize().isPresent() : image; assert image.getChecksum().isPresent() : image; - assert image.getContainerFormat().isPresent() : image; - assert image.getContainerFormat().isPresent() : image; } @Test @@ -69,7 +84,8 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { } private void checkImageDetails(ImageDetails image) { - //TODO + checkImage(image); + // TODO } private void checkImageDetailsEqual(ImageDetails image, ImageDetails newDetails) { @@ -78,4 +94,54 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { assertEquals(newDetails.getLinks(), image.getLinks()); } + @Test + public void testCreateUpdateAndDeleteImage() { + StringPayload imageData = new StringPayload("This isn't really an image!"); + for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { + ImageClient client = glanceContext.getApi().getImageClientForRegion(zoneId); + ImageDetails details = client.create("jclouds-live-test", imageData, diskFormat(DiskFormat.RAW), containerFormat(ContainerFormat.BARE)); + assertEquals(details.getName(), "jclouds-live-test"); + assertEquals(details.getSize().get().longValue(), imageData.getRawContent().length()); + + details = client.update(details.getId(), UpdateImageOptions.Builder.name("jclouds-live-test2"), UpdateImageOptions.Builder.minDisk(10)); + assertEquals(details.getName(), "jclouds-live-test2"); + assertEquals(details.getMinDisk(), 10); + + Image fromListing = Iterables.getOnlyElement(client.list(ListImageOptions.Builder.name("jclouds-live-test2"), ListImageOptions.Builder.maxResults(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); + assertEquals(fromListing.getId(), details.getId()); + assertEquals(fromListing.getSize(), details.getSize()); + + assertEquals(Iterables.getOnlyElement(client.listInDetail(ListImageOptions.Builder.name("jclouds-live-test2"))), details); + + assertTrue(client.delete(details.getId())); + + assertTrue(client.list(ListImageOptions.Builder.name("jclouds-live-test2")).isEmpty()); + } + } + + @Test + public void testReserveUploadAndDeleteImage() { + StringPayload imageData = new StringPayload("This isn't an image!"); + for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { + ImageClient client = glanceContext.getApi().getImageClientForRegion(zoneId); + ImageDetails details = client.reserve("jclouds-live-res-test", diskFormat(DiskFormat.RAW), containerFormat(ContainerFormat.BARE)); + assertEquals(details.getName(), "jclouds-live-res-test"); + + details = client.upload(details.getId(), imageData, UpdateImageOptions.Builder.name("jclouds-live-res-test2"), UpdateImageOptions.Builder.minDisk(10)); + assertEquals(details.getName(), "jclouds-live-res-test2"); + assertEquals(details.getSize().get().longValue(), imageData.getRawContent().length()); + assertEquals(details.getMinDisk(), 10); + + Image fromListing = Iterables.getOnlyElement(client.list(ListImageOptions.Builder.name("jclouds-live-res-test2"), ListImageOptions.Builder.maxResults(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); + assertEquals(fromListing.getId(), details.getId()); + assertEquals(fromListing.getSize(), details.getSize()); + + assertEquals(Iterables.getOnlyElement(client.listInDetail(ListImageOptions.Builder.name("jclouds-live-res-test2"))), details); + + assertTrue(client.delete(details.getId())); + + assertTrue(client.list(ListImageOptions.Builder.name("jclouds-live-res-test2")).isEmpty()); + } + } + } diff --git a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/parse/ParseImageDetailsTest.java b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/parse/ParseImageDetailsTest.java new file mode 100644 index 0000000000..68bc45b8d1 --- /dev/null +++ b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/parse/ParseImageDetailsTest.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.parse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.date.internal.SimpleDateFormatDateService; +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; +import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; +import org.jclouds.openstack.glance.v1_0.domain.Image; +import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +/** + * + * @author Adam Lowe + */ +@Test(groups = "unit", testName = "ParseImageDetailTest") +public class ParseImageDetailsTest extends BaseItemParserTest { + + @Override + public String resource() { + return "/image.json"; + } + + @Override + @SelectJson("image") + @Consumes(MediaType.APPLICATION_JSON) + public ImageDetails expected() { + return ImageDetails + .builder() + .id("02fa0378-f305-43cf-8058-8572fe1da795") + .name("jclouds-live-test") + .containerFormat(ContainerFormat.BARE) + .diskFormat(DiskFormat.RAW) + .checksum("6ae4e0fdc3c108a1bfe10ef5e436f4f4") + .size(27) + .status(Image.Status.ACTIVE) + .owner("68a7c7abb7bf45ada1536dfa28ec2115") + .isPublic(false) + .createdAt(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-31T10:13:47")) + .updatedAt(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-05-31T10:13:47")) + .build(); + } + +} diff --git a/labs/openstack-glance/src/test/resources/image.json b/labs/openstack-glance/src/test/resources/image.json new file mode 100644 index 0000000000..0e47c7865c --- /dev/null +++ b/labs/openstack-glance/src/test/resources/image.json @@ -0,0 +1 @@ +{"image": {"status": "active", "name": "jclouds-live-test", "deleted": false, "container_format": "bare", "created_at": "2012-05-31T10:13:47", "disk_format": "raw", "updated_at": "2012-05-31T10:13:47", "properties": {}, "min_disk": 0, "protected": false, "id": "02fa0378-f305-43cf-8058-8572fe1da795", "checksum": "6ae4e0fdc3c108a1bfe10ef5e436f4f4", "owner": "68a7c7abb7bf45ada1536dfa28ec2115", "is_public": false, "deleted_at": null, "min_ram": 0, "size": 27}} \ No newline at end of file From 7de87a123811e338f982c5a1d593f675812d7b7d Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Thu, 31 May 2012 14:08:40 +0100 Subject: [PATCH 11/73] openstack-glance: adjusting to allow tests to pass when images have been reserved --- .../glance/v1_0/features/ImageClientLiveTest.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java index 62bf4d7e6c..908a835aeb 100644 --- a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java +++ b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java @@ -23,13 +23,9 @@ import static org.jclouds.openstack.glance.v1_0.options.CreateImageOptions.Build import static org.jclouds.openstack.glance.v1_0.options.CreateImageOptions.Builder.diskFormat; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; -import java.io.File; import java.util.Set; -import org.jclouds.io.Payload; -import org.jclouds.io.payloads.FilePayload; import org.jclouds.io.payloads.StringPayload; import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; @@ -40,7 +36,6 @@ import org.jclouds.openstack.glance.v1_0.options.ListImageOptions; import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; import org.testng.annotations.Test; -import com.google.common.base.Optional; import com.google.common.collect.Iterables; /** @@ -64,8 +59,8 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { private void checkImage(Image image) { assert image.getId() != null : image; - assert image.getSize().isPresent() : image; - assert image.getChecksum().isPresent() : image; + assert image.getName() != null : image; + assert image.getLinks() != null : image; } @Test @@ -85,7 +80,8 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { private void checkImageDetails(ImageDetails image) { checkImage(image); - // TODO + assertTrue(image.getMinDisk() >= 0); + assertTrue(image.getMinRam() >= 0); } private void checkImageDetailsEqual(ImageDetails image, ImageDetails newDetails) { From fe53765de0a6262aee573bf3fc708cb92edd38f8 Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Thu, 31 May 2012 14:19:51 +0100 Subject: [PATCH 12/73] openstack-glance: documenting multiple vararg usage --- .../glance/v1_0/options/CreateImageOptions.java | 12 ++++++++++++ .../glance/v1_0/options/ListImageOptions.java | 11 +++++++++++ .../glance/v1_0/options/UpdateImageOptions.java | 10 ++++++++++ 3 files changed, 33 insertions(+) diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java index 112e2b140a..119b469990 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/CreateImageOptions.java @@ -23,6 +23,18 @@ import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; import org.jclouds.openstack.glance.v1_0.domain.StoreType; /** + * + *

Usage The recommended way to instantiate a CreateImageOptions object is to statically import + * CreateImageOptions.Builder.* and invoke a static creation method for each option as needed: + *

+ * + * import static org.jclouds.openstack.glance.v1_0.options.CreateImageOptions.Builder.* + * + * + * // this will create an image with the name "imageName", minimum required disk of 10GB, etc. + * details = client.create("imageName", minDisk(10), isPublic(true), property("mykey", "somevalue")); + * + * @author Adam Lowe * @see */ diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java index b095a1cd88..1069547236 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java @@ -28,6 +28,17 @@ import org.jclouds.openstack.glance.v1_0.domain.Image.Status; import org.jclouds.openstack.options.BaseListOptions; /** + *

Usage The recommended way to instantiate a ListImageOptions object is to statically import + * ListImageOptions.Builder.* and invoke a static creation method for each option as needed: + *

+ * + * import static org.jclouds.openstack.glance.v1_0.options.ListImageOptions.Builder.* + * + * + * // this will list the first 10 images with the name "name", minimum required disk of 5GB. + * list = client.list(name("newName"), maxResults(10), minDisk(5)); + * + * * @author Adam Lowe * @see */ diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java index 834ae9a7f3..da0e4e9fb8 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/UpdateImageOptions.java @@ -26,6 +26,16 @@ import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; import org.jclouds.openstack.glance.v1_0.domain.StoreType; /** + *

Usage The recommended way to instantiate a UpdateImageOptions object is to statically import + * UpdateImageOptions.Builder.* and invoke a static creation method for each option as needed: + *

+ * + * import static org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions.Builder.* + * + * + * // this will adjust the image with id 'id' the name "newName", minimum required disk of 5GB, etc. + * details = client.update(id, name("newName"), minDisk(5), isPublic(true), property("mykey", "somevalue")); + * * @author Adam Lowe * @see */ From 57c11155fb5712fc71dd1754be62d0898ca2d049 Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Thu, 31 May 2012 14:40:45 +0100 Subject: [PATCH 13/73] openstack-glance: following example in swift and not extending openstack-common BaseListOptions --- .../openstack/options/BaseListOptions.java | 25 ---------- .../glance/v1_0/options/ListImageOptions.java | 48 ++++++++++++------- .../v1_0/features/ImageClientLiveTest.java | 6 +-- 3 files changed, 34 insertions(+), 45 deletions(-) diff --git a/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java b/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java index 26f62eded8..fa0aed3632 100644 --- a/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java +++ b/common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java @@ -48,10 +48,6 @@ public class BaseListOptions extends BaseHttpRequestOptions { * Indicates where to begin listing. The list will only include objects that occur after the * offset. This is convenient for pagination: To get the next page of results use the last result * number of the current page + current page offset as the offset. - *

- * This isn't supported by newer openstack API implementations - * - * @see #marker(String) for the new mechanism to set the page offset */ public BaseListOptions startAt(long offset) { checkState(offset >= 0, "offset must be >= 0"); @@ -59,19 +55,6 @@ public class BaseListOptions extends BaseHttpRequestOptions { return this; } - /** - * The marker parameter is the ID of the last item in the previous list - * (i.e. return the page of items after the marker). - *

- * This is only supported by newer openstack API implementations - * - * @see #startAt for the old mechanism to set the page offset - */ - public BaseListOptions marker(String marker) { - queryParameters.put("marker", checkNotNull(marker, "marker")); - return this; - } - /** * To reduce load on the service, list operations will return a maximum of 1,000 items at a time. * To navigate the collection, the parameters limit and offset can be set in the URI @@ -97,14 +80,6 @@ public class BaseListOptions extends BaseHttpRequestOptions { return options.startAt(prefix); } - /** - * @see BaseListOptions#marker - */ - public static BaseListOptions marker(String marker) { - BaseListOptions options = new BaseListOptions(); - return options.marker(marker); - } - /** * @see BaseListOptions#maxResults */ diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java index 1069547236..b81c07c9bc 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java @@ -18,14 +18,14 @@ */ package org.jclouds.openstack.glance.v1_0.options; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import static org.jclouds.openstack.glance.v1_0.options.ImageField.*; -import java.util.Date; - +import org.jclouds.http.options.BaseHttpRequestOptions; import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; import org.jclouds.openstack.glance.v1_0.domain.Image.Status; -import org.jclouds.openstack.options.BaseListOptions; /** *

Usage The recommended way to instantiate a ListImageOptions object is to statically import @@ -36,13 +36,33 @@ import org.jclouds.openstack.options.BaseListOptions; * * * // this will list the first 10 images with the name "name", minimum required disk of 5GB. - * list = client.list(name("newName"), maxResults(10), minDisk(5)); + * list = client.list(name("newName"), limit(10), minDisk(5)); * * * @author Adam Lowe * @see */ -public class ListImageOptions extends BaseListOptions { +public class ListImageOptions extends BaseHttpRequestOptions { + public static final ListImageOptions NONE = new ListImageOptions(); + + /** + * Given a string value x, return object names greater in value than the specified marker. + */ + public ListImageOptions marker(String marker) { + queryParameters.put("marker", checkNotNull(marker, "marker")); + return this; + } + + /** + * For an integer value n, limits the number of results to n values. + */ + public ListImageOptions limit(int limit) { + checkState(limit >= 0, "limit must be >= 0"); + checkState(limit <= 10000, "limit must be <= 10000"); + queryParameters.put("limit", Integer.toString(limit)); + return this; + } + /** * Return only those images having a matching name attribute */ @@ -228,24 +248,18 @@ public class ListImageOptions extends BaseListOptions { } /** - * @see BaseListOptions#maxResults + * @see ListImageOptions#limit */ - public static ListImageOptions maxResults(int limit) { - return ListImageOptions.class.cast(new ListImageOptions().maxResults(limit)); + public static ListImageOptions limit(int limit) { + return new ListImageOptions().limit(limit); } /** - * @see BaseListOptions#marker + * @see ListImageOptions#marker */ public static ListImageOptions marker(String marker) { - return ListImageOptions.class.cast(new ListImageOptions().marker(marker)); - } - - /** - * @see BaseListOptions#changesSince - */ - public static ListImageOptions changesSince(Date ifModifiedSince) { - return ListImageOptions.class.cast(new BaseListOptions().changesSince(ifModifiedSince)); + ListImageOptions options = new ListImageOptions(); + return options.marker(marker); } } } diff --git a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java index 908a835aeb..76d835e706 100644 --- a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java +++ b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageClientLiveTest.java @@ -49,7 +49,7 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { public void testList() throws Exception { for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { ImageClient client = glanceContext.getApi().getImageClientForRegion(zoneId); - Set response = client.list(ListImageOptions.Builder.maxResults(100)); + Set response = client.list(ListImageOptions.Builder.limit(100)); assert null != response; for (Image image : response) { checkImage(image); @@ -103,7 +103,7 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { assertEquals(details.getName(), "jclouds-live-test2"); assertEquals(details.getMinDisk(), 10); - Image fromListing = Iterables.getOnlyElement(client.list(ListImageOptions.Builder.name("jclouds-live-test2"), ListImageOptions.Builder.maxResults(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); + Image fromListing = Iterables.getOnlyElement(client.list(ListImageOptions.Builder.name("jclouds-live-test2"), ListImageOptions.Builder.limit(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); assertEquals(fromListing.getId(), details.getId()); assertEquals(fromListing.getSize(), details.getSize()); @@ -128,7 +128,7 @@ public class ImageClientLiveTest extends BaseGlanceClientLiveTest { assertEquals(details.getSize().get().longValue(), imageData.getRawContent().length()); assertEquals(details.getMinDisk(), 10); - Image fromListing = Iterables.getOnlyElement(client.list(ListImageOptions.Builder.name("jclouds-live-res-test2"), ListImageOptions.Builder.maxResults(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); + Image fromListing = Iterables.getOnlyElement(client.list(ListImageOptions.Builder.name("jclouds-live-res-test2"), ListImageOptions.Builder.limit(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); assertEquals(fromListing.getId(), details.getId()); assertEquals(fromListing.getSize(), details.getSize()); From e0ad035606866b75a23e1a91125fdecac235c9e6 Mon Sep 17 00:00:00 2001 From: vijaykiran Date: Fri, 1 Jun 2012 11:31:07 +0200 Subject: [PATCH 14/73] Set port in the request header from the endpoint --- .../http/internal/JavaUrlHttpCommandExecutorService.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java b/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java index 87a862419d..a8334f3e8f 100644 --- a/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java +++ b/core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java @@ -209,7 +209,12 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe for (Map.Entry entry : request.getHeaders().entries()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } - connection.setRequestProperty(HttpHeaders.HOST, request.getEndpoint().getHost()); + + String host = request.getEndpoint().getHost(); + if(request.getEndpoint().getPort() != -1) { + host += ":" + request.getEndpoint().getPort(); + } + connection.setRequestProperty(HttpHeaders.HOST, host); connection.setRequestProperty(HttpHeaders.USER_AGENT, USER_AGENT); if (request.getPayload() != null) { From df919fb1874a96b85999db7b2054d168812ce1e0 Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Fri, 1 Jun 2012 14:54:31 +0100 Subject: [PATCH 15/73] openstack-quantum: adding NETWORK service type and corresponding service in keystoneAuthResponse.json --- .../jclouds/openstack/services/ServiceType.java | 4 ++++ .../keystone/v2_0/parse/ParseAccessTest.java | 15 +++++++++++++-- .../src/test/resources/keystoneAuthResponse.json | 16 +++++++++++++++- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/common/openstack/src/main/java/org/jclouds/openstack/services/ServiceType.java b/common/openstack/src/main/java/org/jclouds/openstack/services/ServiceType.java index 4d97aec0fd..abd5f667af 100644 --- a/common/openstack/src/main/java/org/jclouds/openstack/services/ServiceType.java +++ b/common/openstack/src/main/java/org/jclouds/openstack/services/ServiceType.java @@ -45,4 +45,8 @@ public interface ServiceType { * Identity Service (Keystone) */ public static final String IDENTITY = "identity"; + /** + * Network Service (Quantum) + */ + public static final String NETWORK = "network"; } \ No newline at end of file diff --git a/common/openstack/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java b/common/openstack/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java index 2a95cb6947..b4dd8e8277 100644 --- a/common/openstack/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java +++ b/common/openstack/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java @@ -95,8 +95,19 @@ public class ParseAccessTest extends BaseItemParserTest { .tenantId("3456") .publicURL(URI.create("https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456")) .region("az-3.region-a.geo-1") - .versionId("1.1").build()).build() - ).build(); + .versionId("1.1").build()).build(), + + Service.builder().name("Quantum Service").type("network").endpoints( + Endpoint.builder() + .tenantId("3456") + .publicURL(URI.create("https://csnode.jclouds.org:9696/v1.0/tenants/3456")) + .internalURL(URI.create("https://csnode.jclouds.org:9696/v1.0/tenants/3456")) + .adminURL(URI.create("https://csnode.jclouds.org:9696/v1.0")) + .region("region-a.geo-1") + .versionId("1.0").build() + ).build()) + + .build(); } } diff --git a/common/openstack/src/test/resources/keystoneAuthResponse.json b/common/openstack/src/test/resources/keystoneAuthResponse.json index a781a32a89..33b0ccd2c1 100644 --- a/common/openstack/src/test/resources/keystoneAuthResponse.json +++ b/common/openstack/src/test/resources/keystoneAuthResponse.json @@ -109,6 +109,20 @@ "versionList": "https:\/\/az-3.region-a.geo-1.compute.hpcloudsvc.com" } ] - } + }, + { + "type": "network", + "name": "Quantum Service", + "endpoints": [{ + "tenantId": "3456", + "adminURL": "https://csnode.jclouds.org:9696/v1.0", + "region": "region-a.geo-1", + "versionId": "1.0", + "publicURL": "https://csnode.jclouds.org:9696/v1.0/tenants/3456", + "internalURL": "https://csnode.jclouds.org:9696/v1.0/tenants/3456" + }], + "endpoints_links": [] + } ] +} } \ No newline at end of file From e5c7afa70c8433c3761b68762becc16b50b0d032 Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Fri, 1 Jun 2012 15:46:14 +0100 Subject: [PATCH 16/73] openstack-quantum: adding network service for openstack --- labs/openstack-quantum/pom.xml | 151 +++++++++++ .../quantum/v1_0/QuantumApiMetadata.java | 99 +++++++ .../quantum/v1_0/QuantumAsyncClient.java | 61 +++++ .../openstack/quantum/v1_0/QuantumClient.java | 63 +++++ .../v1_0/config/QuantumProperties.java | 28 ++ .../v1_0/config/QuantumRestClientModule.java | 82 ++++++ .../quantum/v1_0/domain/Attachment.java | 63 +++++ .../quantum/v1_0/domain/Network.java | 105 ++++++++ .../quantum/v1_0/domain/NetworkDetails.java | 112 ++++++++ .../openstack/quantum/v1_0/domain/Port.java | 107 ++++++++ .../quantum/v1_0/domain/PortDetails.java | 104 ++++++++ .../quantum/v1_0/domain/Reference.java | 111 ++++++++ .../v1_0/features/NetworkAsyncClient.java | 121 +++++++++ .../quantum/v1_0/features/NetworkClient.java | 81 ++++++ .../v1_0/features/PortAsyncClient.java | 155 +++++++++++ .../quantum/v1_0/features/PortClient.java | 98 +++++++ .../v1_0/handlers/QuantumErrorHandler.java | 65 +++++ .../services/org.jclouds.apis.ApiMetadata | 1 + .../quantum/v1_0/QuantumApiMetadataTest.java | 37 +++ .../features/NetworkClientExpectTest.java | 236 +++++++++++++++++ .../v1_0/features/NetworkClientLiveTest.java | 92 +++++++ .../v1_0/features/PortClientExpectTest.java | 246 ++++++++++++++++++ .../v1_0/features/PortClientLiveTest.java | 137 ++++++++++ .../internal/BaseQuantumClientExpectTest.java | 49 ++++ .../internal/BaseQuantumClientLiveTest.java | 74 ++++++ .../v1_0/internal/BaseQuantumExpectTest.java | 49 ++++ .../v1_0/parse/ParseAttachmentTest.java | 47 ++++ .../v1_0/parse/ParseNetworkDetailsTest.java | 51 ++++ .../quantum/v1_0/parse/ParseNetworkTest.java | 47 ++++ .../v1_0/parse/ParsePortDetailsTest.java | 49 ++++ .../quantum/v1_0/parse/ParsePortTest.java | 47 ++++ .../src/test/resources/attachment.json | 1 + .../src/test/resources/list_network_refs.json | 14 + .../src/test/resources/list_networks.json | 14 + .../src/test/resources/logback.xml | 51 ++++ .../src/test/resources/network.json | 1 + .../src/test/resources/network_details.json | 1 + .../src/test/resources/port.json | 1 + .../src/test/resources/port_details.json | 1 + labs/pom.xml | 1 + 40 files changed, 2853 insertions(+) create mode 100644 labs/openstack-quantum/pom.xml create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumProperties.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Attachment.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Network.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/NetworkDetails.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Port.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/PortDetails.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Reference.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java create mode 100644 labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/handlers/QuantumErrorHandler.java create mode 100644 labs/openstack-quantum/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadataTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientExpectTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientLiveTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumExpectTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseAttachmentTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkDetailsTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortDetailsTest.java create mode 100644 labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortTest.java create mode 100644 labs/openstack-quantum/src/test/resources/attachment.json create mode 100644 labs/openstack-quantum/src/test/resources/list_network_refs.json create mode 100644 labs/openstack-quantum/src/test/resources/list_networks.json create mode 100644 labs/openstack-quantum/src/test/resources/logback.xml create mode 100644 labs/openstack-quantum/src/test/resources/network.json create mode 100644 labs/openstack-quantum/src/test/resources/network_details.json create mode 100644 labs/openstack-quantum/src/test/resources/port.json create mode 100644 labs/openstack-quantum/src/test/resources/port_details.json diff --git a/labs/openstack-quantum/pom.xml b/labs/openstack-quantum/pom.xml new file mode 100644 index 0000000000..a37221da36 --- /dev/null +++ b/labs/openstack-quantum/pom.xml @@ -0,0 +1,151 @@ + + + + 4.0.0 + + org.jclouds + jclouds-project + 1.5.0-SNAPSHOT + ../../project/pom.xml + + org.jclouds.labs + openstack-quantum + jcloud openstack-quantum api + jclouds components to access an implementation of OpenStack Quantum + bundle + + + + http://localhost:5000 + + 1.0 + + FIXME_IDENTITY + FIXME_CREDENTIALS + passwordCredentials + FIXME_HTTPURL + FIXME_HTTPMD5 + + + + + org.jclouds.common + openstack-common + ${project.version} + + + org.jclouds + jclouds-blobstore + ${project.version} + + + org.jclouds + jclouds-core + ${project.version} + test-jar + test + + + org.jclouds.common + openstack-common + ${project.version} + test-jar + test + + + org.jclouds + jclouds-blobstore + ${project.version} + test-jar + test + + + org.jclouds.driver + jclouds-slf4j + ${project.version} + test + + + ch.qos.logback + logback-classic + 1.0.0 + test + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration + integration-test + + test + + + + ${test.openstack-quantum.endpoint} + ${test.openstack-quantum.api-version} + ${test.openstack-quantum.build-version} + ${test.openstack-quantum.identity} + ${test.openstack-quantum.credential} + ${test.jclouds.keystone.credential-type} + ${jclouds.blobstore.httpstream.url} + ${jclouds.blobstore.httpstream.md5} + + + + + + + + + + + + + + org.apache.felix + maven-bundle-plugin + + + ${project.artifactId} + org.jclouds.openstack.quantum.v1*;version="${project.version}" + + org.jclouds.blobstore.internal;version="${project.version}", + org.jclouds.rest.internal;version="${project.version}", + org.jclouds*;version="${project.version}", + * + + + + + + + + diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java new file mode 100644 index 0000000000..6511ee029e --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java @@ -0,0 +1,99 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0; + +import static org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties.SERVICE_TYPE; + +import java.net.URI; +import java.util.Properties; + +import org.jclouds.apis.ApiMetadata; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties; +import org.jclouds.openstack.quantum.v1_0.config.QuantumRestClientModule; +import org.jclouds.openstack.services.ServiceType; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.BaseRestApiMetadata; + +import com.google.common.collect.ImmutableSet; +import com.google.common.reflect.TypeToken; +import com.google.inject.Module; + +/** + * Implementation of {@link ApiMetadata} for Quantum 1.0 API + * + * @author Adam Lowe + */ +public class QuantumApiMetadata extends BaseRestApiMetadata { + /** The serialVersionUID */ + private static final long serialVersionUID = -7273686435105663195L; + + public static final TypeToken> CONTEXT_TOKEN = new TypeToken>() { + private static final long serialVersionUID = -3493117927790861884L; + }; + + @Override + public Builder toBuilder() { + return new Builder().fromApiMetadata(this); + } + + public QuantumApiMetadata() { + this(new Builder()); + } + + protected QuantumApiMetadata(Builder builder) { + super(builder); + } + + public static Properties defaultProperties() { + Properties properties = BaseRestApiMetadata.defaultProperties(); + properties.setProperty(SERVICE_TYPE, ServiceType.NETWORK); + // TODO: this doesn't actually do anything yet. + properties.setProperty(KeystoneProperties.VERSION, "2.0"); + return properties; + } + + public static class Builder extends BaseRestApiMetadata.Builder { + + protected Builder() { + super(QuantumClient.class, QuantumAsyncClient.class); + id("openstack-quantum") + .name("OpenStack Quantum API") + .identityName("tenantId:user") + .credentialName("password") + .documentation(URI.create("http://docs.openstack.org/api/openstack-network/1.0/content/")) + .version("1.0") + .defaultEndpoint("http://localhost:5000") + .defaultProperties(QuantumApiMetadata.defaultProperties()) + .defaultModules(ImmutableSet.>of(QuantumRestClientModule.class)); + } + + @Override + public QuantumApiMetadata build() { + return new QuantumApiMetadata(this); + } + + @Override + public Builder fromApiMetadata(ApiMetadata in) { + super.fromApiMetadata(in); + return this; + } + + } + +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java new file mode 100644 index 0000000000..53d85c9f37 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0; + +import java.util.Set; + +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.location.Region; +import org.jclouds.location.functions.RegionToEndpoint; +import org.jclouds.openstack.quantum.v1_0.features.NetworkAsyncClient; +import org.jclouds.openstack.quantum.v1_0.features.PortAsyncClient; +import org.jclouds.rest.annotations.Delegate; +import org.jclouds.rest.annotations.EndpointParam; + +import com.google.inject.Provides; + +/** + * Provides asynchronous access to Quantum via their REST API. + *

+ * + * @see QuantumClient + * @see api doc + * @author Adam Lowe + */ +public interface QuantumAsyncClient { + /** + * + * @return the Region codes configured + */ + @Provides + @Region + Set getConfiguredRegions(); + + /** + * Provides asynchronous access to Network features. + */ + @Delegate + NetworkAsyncClient getNetworkClientForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + + /** + * Provides asynchronous access to Port features. + */ + @Delegate + PortAsyncClient getPortClientForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java new file mode 100644 index 0000000000..8bd93615cb --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java @@ -0,0 +1,63 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.location.Region; +import org.jclouds.location.functions.RegionToEndpoint; +import org.jclouds.openstack.quantum.v1_0.features.NetworkClient; +import org.jclouds.openstack.quantum.v1_0.features.PortClient; +import org.jclouds.rest.annotations.Delegate; +import org.jclouds.rest.annotations.EndpointParam; + +import com.google.inject.Provides; + +/** + * Provides synchronous access to Quantum. + *

+ * + * @author Adam Lowe + * @see QuantumAsyncClient + * @see api doc + */ +@Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) +public interface QuantumClient { + /** + * @return the Region codes configured + */ + @Provides + @Region + Set getConfiguredRegions(); + + /** + * Provides synchronous access to Network features. + */ + @Delegate + NetworkClient getNetworkClientForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + + /** + * Provides synchronous access to Port features. + */ + @Delegate + PortClient getPortClientForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumProperties.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumProperties.java new file mode 100644 index 0000000000..2577b7c9a7 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumProperties.java @@ -0,0 +1,28 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.config; + +/** + * Configuration properties and constants used in openstack Quantum connections. + * + * @author Adam Lowe + */ +public class QuantumProperties { + +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java new file mode 100644 index 0000000000..4017df5257 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java @@ -0,0 +1,82 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.config; + +import java.util.Map; + +import org.jclouds.http.HttpErrorHandler; +import org.jclouds.http.annotation.ClientError; +import org.jclouds.http.annotation.Redirection; +import org.jclouds.http.annotation.ServerError; +import org.jclouds.json.config.GsonModule.DateAdapter; +import org.jclouds.json.config.GsonModule.Iso8601DateAdapter; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; +import org.jclouds.openstack.quantum.v1_0.QuantumAsyncClient; +import org.jclouds.openstack.quantum.v1_0.QuantumClient; +import org.jclouds.openstack.quantum.v1_0.features.NetworkAsyncClient; +import org.jclouds.openstack.quantum.v1_0.features.NetworkClient; +import org.jclouds.openstack.quantum.v1_0.features.PortAsyncClient; +import org.jclouds.openstack.quantum.v1_0.features.PortClient; +import org.jclouds.openstack.quantum.v1_0.handlers.QuantumErrorHandler; +import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.rest.config.RestClientModule; + +import com.google.common.collect.ImmutableMap; + +/** + * Configures the Quantum connection. + * + * @author Adam Lowe + */ +@ConfiguresRestClient +public class QuantumRestClientModule extends RestClientModule { + + public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder() + .put(NetworkClient.class, NetworkAsyncClient.class) + .put(PortClient.class, PortAsyncClient.class) + .build(); + + public QuantumRestClientModule() { + super(DELEGATE_MAP); + } + + @Override + protected void configure() { + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + super.configure(); + } + + @Override + protected void installLocations() { + // TODO: select this from KeystoneProperties.VERSION; note you select from + // a guice provided + // property, so it will have to come from somewhere else, maybe we move + // this to the the + // ContextBuilder + install(KeystoneAuthenticationModule.forRegions()); + super.installLocations(); + } + + @Override + protected void bindErrorHandlers() { + bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(QuantumErrorHandler.class); + bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(QuantumErrorHandler.class); + bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(QuantumErrorHandler.class); + } +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Attachment.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Attachment.java new file mode 100644 index 0000000000..9ff5920725 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Attachment.java @@ -0,0 +1,63 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.domain; + +/** + * A Quantum attachment + * + * @author Adam Lowe + * @see api doc + */ +public class Attachment extends Reference { + + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromAttachment(this); + } + + public static abstract class Builder> extends Reference.Builder { + protected abstract T self(); + + public Attachment build() { + return new Attachment(this); + } + + public T fromAttachment(Attachment in) { + return super.fromReference(in); + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } + + protected Attachment(Builder builder) { + super(builder); + } + + protected Attachment() { + // for GSON + } +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Network.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Network.java new file mode 100644 index 0000000000..fd3e3cf850 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Network.java @@ -0,0 +1,105 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.domain; + +import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * A Quantum network + * + * @author Adam Lowe + * @see api doc + */ +public class Network extends Reference { + + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromNetwork(this); + } + + public static abstract class Builder> extends Reference.Builder { + protected abstract T self(); + + private String name; + + /** + * @see Network#getName() + */ + public T name(String name) { + this.name = name; + return self(); + } + + public Network build() { + return new Network(this); + } + + public T fromNetwork(Network in) { + return super.fromReference(in).name(in.getName()); + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } + + private final String name; + + protected Network(Builder builder) { + super(builder); + this.name = checkNotNull(builder.name, "name"); + } + + protected Network() { + // for GSON + this.name = null; + } + + /** + */ + public String getName() { + return this.name; + } + + @Override + public int hashCode() { + return Objects.hashCode(super.hashCode(), name); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + Network that = Network.class.cast(obj); + return super.equals(that) && Objects.equal(this.name, that.name); + } + + protected ToStringHelper string() { + return super.string().add("name", name); + } +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/NetworkDetails.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/NetworkDetails.java new file mode 100644 index 0000000000..8d76a0b04e --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/NetworkDetails.java @@ -0,0 +1,112 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Collections; +import java.util.Set; + +import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; +import com.google.common.collect.ImmutableSet; + +/** + * Details of a Quantum network + * + * @author Adam Lowe + * @see api doc + */ +public class NetworkDetails extends Network { + + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromNetworkDetails(this); + } + + public static abstract class Builder> extends Network.Builder { + private Set ports = ImmutableSet.of(); + + /** + * @see NetworkDetails#getPorts() + */ + public T ports(Set ports) { + this.ports = ports; + return self(); + } + + public T ports(Port... in) { + return ports(ImmutableSet.copyOf(in)); + } + + public NetworkDetails build() { + return new NetworkDetails(this); + } + + public T fromNetworkDetails(NetworkDetails in) { + return super.fromNetwork(in).ports(in.getPorts()); + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } + + private final Set ports; + + protected NetworkDetails(Builder builder) { + super(builder); + this.ports = ImmutableSet.copyOf(checkNotNull(builder.ports, "ports")); + } + + protected NetworkDetails() { + // for GSON + this.ports = ImmutableSet.of(); + } + + /** + */ + public Set getPorts() { + return Collections.unmodifiableSet(this.ports); + } + + @Override + public int hashCode() { + return Objects.hashCode(ports); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + NetworkDetails that = NetworkDetails.class.cast(obj); + return super.equals(that) && Objects.equal(this.ports, that.ports); + } + + protected ToStringHelper string() { + return super.string().add("ports", ports); + } + +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Port.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Port.java new file mode 100644 index 0000000000..41b156620e --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Port.java @@ -0,0 +1,107 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; + +/** + * A Quantum port + * + * @author Adam Lowe + * @see api doc + */ +public class Port extends Reference { + + public static enum State { + ACTIVE, DOWN + } + + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromPort(this); + } + + public static abstract class Builder> extends Reference.Builder { + protected abstract T self(); + + private Port.State state; + + /** + * @see Port#getState() + */ + public T state(Port.State state) { + this.state = state; + return self(); + } + + public Port build() { + return new Port(this); + } + + public T fromPort(Port in) { + return fromReference(in).state(in.getState()); + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } + + private final Port.State state; + + protected Port(Builder builder) { + super(builder); + this.state = checkNotNull(builder.state, "state"); + } + + protected Port() { + // for GSON + this.state = null; + } + + public Port.State getState() { + return this.state; + } + + @Override + public int hashCode() { + return Objects.hashCode(super.hashCode(), state); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + Port that = Port.class.cast(obj); + return super.equals(that) && Objects.equal(this.state, that.state); + } + + protected ToStringHelper string() { + return super.string().add("state", state); + } +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/PortDetails.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/PortDetails.java new file mode 100644 index 0000000000..df5474f79b --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/PortDetails.java @@ -0,0 +1,104 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.domain; + +import org.jclouds.javax.annotation.Nullable; + +import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; + +/** + * Details of a Quantum Port + * + * @author Adam Lowe + * @see api doc + */ +public class PortDetails extends Port { + + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromPortDetails(this); + } + + public static abstract class Builder> extends Port.Builder { + private Attachment attachment; + + /** + * @see PortDetails#getAttachment() + */ + public T attachment(Attachment attachment) { + this.attachment = attachment; + return self(); + } + + public PortDetails build() { + return new PortDetails(this); + } + + public T fromPortDetails(PortDetails in) { + return super.fromPort(in).attachment(in.getAttachment()); + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } + + @Nullable + private final Attachment attachment; + + protected PortDetails(Builder builder) { + super(builder); + this.attachment = builder.attachment; + } + + protected PortDetails() { + // for GSON + this.attachment = null; + } + + @Nullable + public Attachment getAttachment() { + return this.attachment; + } + + @Override + public int hashCode() { + return Objects.hashCode(attachment); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + PortDetails that = PortDetails.class.cast(obj); + return super.equals(that) && Objects.equal(this.attachment, that.attachment); + } + + protected ToStringHelper string() { + return super.string().add("attachment", attachment); + } + +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Reference.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Reference.java new file mode 100644 index 0000000000..1f6e8a2af2 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/domain/Reference.java @@ -0,0 +1,111 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; + +/** + * A wrapper around an id in the quantum api + * + * @author Adam Lowe + * @see api doc + */ +public class Reference { + + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromReference(this); + } + + public static abstract class Builder> { + protected abstract T self(); + + private String id; + + /** + * @see org.jclouds.openstack.quantum.v1_0.domain.Reference#getId() + */ + public T id(String id) { + this.id = id; + return self(); + } + + public Reference build() { + return new Reference(this); + } + + public T fromReference(Reference in) { + return this.id(in.getId()); + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } + + private final String id; + + protected Reference(Builder builder) { + this.id = checkNotNull(builder.id, "id"); + } + + protected Reference() { + // for GSON + this.id = null; + } + + /** + */ + public String getId() { + return this.id; + } + + + @Override + public int hashCode() { + return Objects.hashCode(id); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + Reference that = Reference.class.cast(obj); + return Objects.equal(this.id, that.id); + } + + protected ToStringHelper string() { + return Objects.toStringHelper("").add("id", id); + } + + @Override + public String toString() { + return string().toString(); + } + +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java new file mode 100644 index 0000000000..fbefb75d3c --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java @@ -0,0 +1,121 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import java.util.Set; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.jclouds.openstack.filters.AuthenticateRequest; +import org.jclouds.openstack.quantum.v1_0.domain.Network; +import org.jclouds.openstack.quantum.v1_0.domain.NetworkDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.PayloadParam; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.SelectJson; +import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.annotations.WrapWith; +import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Network operations on the openstack quantum API. + * + * @author Adam Lowe + * @see org.jclouds.openstack.quantum.v1_0.features.NetworkClient + * @see api doc + */ +@SkipEncoding({'/', '='}) +@RequestFilters(AuthenticateRequest.class) +@Consumes(MediaType.APPLICATION_JSON) +@Path("/networks") +public interface NetworkAsyncClient { + + /** + * @see NetworkClient#listReferences + */ + @GET + @SelectJson("networks") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listReferences(); + + /** + * @see NetworkClient#list + */ + @GET + @SelectJson("networks") + @Path("/detail") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> list(); + + /** + * @see NetworkClient#show + */ + @GET + @SelectJson("network") + @Path("/{id}") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture show(@PathParam("id") String id); + + /** + * @see NetworkClient#showDetails + */ + @GET + @SelectJson("network") + @Path("/{id}/detail") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture showDetails(@PathParam("id") String id); + + /** + * @see NetworkClient#create + */ + @POST + @SelectJson("network") + @Produces(MediaType.APPLICATION_JSON) + @WrapWith("network") + ListenableFuture create(@PayloadParam("name") String name); + + /** + * @see NetworkClient#update + */ + @PUT + @Produces(MediaType.APPLICATION_JSON) + @Path("/{id}") + @WrapWith("network") + ListenableFuture update(@PathParam("id") String id, @PayloadParam("name") String name); + + /** + * @see NetworkClient#delete + */ + @DELETE + @Path("/{id}") + ListenableFuture delete(@PathParam("id") String id); + +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java new file mode 100644 index 0000000000..5647b33394 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.openstack.quantum.v1_0.domain.Network; +import org.jclouds.openstack.quantum.v1_0.domain.NetworkDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; + +/** + * Provides synchronous access to Network operations on the openstack quantum API. + *

+ * Each tenant can define one or more networks. A network is a virtual isolated layer-2 broadcast domain reserved to the + * tenant. A tenant can create several ports for a network, and plug virtual interfaces into these ports. + * + * @author Adam Lowe + * @see org.jclouds.openstack.quantum.v1_0.features.NetworkAsyncClient + * @see api doc + */ +@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) +public interface NetworkClient { + + /** + * Returns the list of all networks currently defined in Quantum for the current tenant. The list provides the unique + * identifier of each network configured for the tenant. + */ + Set listReferences(); + + /** + * Returns all networks currently defined in Quantum for the current tenant. + */ + Set list(); + + /** + * Returns the specific network. + */ + Network show(String id); + + /** + * Returns the details of the specific network. + */ + NetworkDetails showDetails(String id); + + /** + * Create a new network with the specified symbolic name + */ + Reference create(String name); + + /** + * Updates the symbolic name of a network + * + * @param id the id of the Network to modify + * @param name the new name for the Network + */ + Boolean update(String id, String name); + + /** + * Deletes the specified network + */ + Boolean delete(String id); +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java new file mode 100644 index 0000000000..6eab8cc10e --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java @@ -0,0 +1,155 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import java.util.Set; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.MediaType; + +import org.jclouds.openstack.filters.AuthenticateRequest; +import org.jclouds.openstack.quantum.v1_0.domain.Attachment; +import org.jclouds.openstack.quantum.v1_0.domain.Port; +import org.jclouds.openstack.quantum.v1_0.domain.PortDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.PayloadParam; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.SelectJson; +import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.annotations.WrapWith; +import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Network operations on the openstack quantum API. + * + * @author Adam Lowe + * @see PortClient + * @see api doc + */ +@SkipEncoding({'/', '='}) +@RequestFilters(AuthenticateRequest.class) +@Consumes(MediaType.APPLICATION_JSON) +@Path("/networks") +public interface PortAsyncClient { + + /** + * @see PortClient#listReferences + */ + @GET + @SelectJson("ports") + @Path("/{net}/ports") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listReferences(@PathParam("net") String networkId); + + /** + * @see PortClient#list + */ + @GET + @SelectJson("ports") + @Path("/{net}/ports/detail") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> list(@PathParam("net") String networkId); + + /** + * @see PortClient#show + */ + @GET + @SelectJson("port") + @Path("/{net}/ports/{id}") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture show(@PathParam("net") String networkId, @PathParam("id") String id); + + /** + * @see PortClient#showDetails + */ + @GET + @SelectJson("port") + @Consumes(MediaType.APPLICATION_JSON) + @Path("/{net}/ports/{id}/detail") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture showDetails(@PathParam("net") String networkId, @PathParam("id") String id); + + /** + * @see PortClient#create(String) + */ + @POST + @SelectJson("port") + @Path("/{net}/ports") + ListenableFuture create(@PathParam("net") String networkId); + + /** + * @see PortClient#create(String, org.jclouds.openstack.quantum.v1_0.domain.Port.State) + */ + @POST + @SelectJson("port") + @Path("/{net}/ports") + @WrapWith("port") + ListenableFuture create(@PathParam("net") String networkId, @PayloadParam("state") Port.State state); + + /** + * @see PortClient#update + */ + @PUT + @Path("/{net}/ports/{id}") + @WrapWith("port") + ListenableFuture update(@PathParam("net") String networkId, @PathParam("id") String id, @PayloadParam("state") Port.State state); + + /** + * @see PortClient#delete + */ + @DELETE + @Path("/{net}/ports/{id}") + ListenableFuture delete(@PathParam("net") String networkId, @PathParam("id") String id); + + /** + * @see PortClient#showAttachment + */ + @GET + @SelectJson("attachment") + @Path("/{net}/ports/{portId}/attachment") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture showAttachment(@PathParam("net") String networkId, @PathParam("portId") String portId); + + /** + * @see PortClient#plugAttachment + */ + @PUT + @Path("/{net}/ports/{portId}/attachment") + @WrapWith("attachment") + ListenableFuture plugAttachment(@PathParam("net") String networkId, @PathParam("portId") String portId, + @PayloadParam("id") String attachmentId); + + /** + * @see PortClient#unplugAttachment + */ + @DELETE + @Path("/{net}/ports/{portId}/attachment") + ListenableFuture unplugAttachment(@PathParam("net") String networkId, @PathParam("portId") String portId); + +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java new file mode 100644 index 0000000000..c500a97b13 --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java @@ -0,0 +1,98 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.openstack.quantum.v1_0.domain.Attachment; +import org.jclouds.openstack.quantum.v1_0.domain.Port; +import org.jclouds.openstack.quantum.v1_0.domain.PortDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; + +/** + * Provides synchronous access to Port operations on the openstack quantum API. + *

+ * A port represents a virtual switch port on a logical network switch where all the interfaces attached to a given network are connected. + *

+ * A port has an administrative state which is either 'DOWN' or 'ACTIVE'. Ports which are administratively down will not be able to receive/send traffic. + * + * @author Adam Lowe + * @see PortAsyncClient + * @see api doc + */ +@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) +public interface PortClient { + /** + * Returns the list of all ports currently defined in Quantum for the requested network + */ + Set listReferences(String networkId); + + /** + * Returns the set of ports currently defined in Quantum for the requested network. + */ + Set list(String networkId); + + /** + * Returns a specific port. + */ + Port show(String networkId, String id); + + /** + * Returns a specific port in detail. + */ + PortDetails showDetails(String networkId, String id); + + /** + * Create a new port on the specified network + */ + Reference create(String networkId); + + /** + * Create a new port on the specified network, with the requested state + */ + Reference create(String networkId, Port.State state); + + /** + * Updates the state of a port + */ + Boolean update(String networkId, String id, Port.State state); + + /** + * Deletes a port from a network + */ + Boolean delete(String networkId, String id); + + /** + * Returns the attachment for the specified port. + */ + Attachment showAttachment(String networkId, String portId); + + /** + * Plugs an attachment into the specified port + */ + Boolean plugAttachment(String networkId, String portId, String attachmentId); + + /** + * Unplugs the attachment currently plugged into the specified port + */ + Boolean unplugAttachment(String networkId, String portId); +} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/handlers/QuantumErrorHandler.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/handlers/QuantumErrorHandler.java new file mode 100644 index 0000000000..661bcd55eb --- /dev/null +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/handlers/QuantumErrorHandler.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.handlers; + +import static org.jclouds.http.HttpUtils.closeClientButKeepContentStream; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpErrorHandler; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.ResourceNotFoundException; + +/** + * This will parse and set an appropriate exception on the command object. + * + * @author Adam Lowe + * + */ +// TODO: is there error spec someplace? let's type errors, etc. +@Singleton +public class QuantumErrorHandler implements HttpErrorHandler { + public void handleError(HttpCommand command, HttpResponse response) { + // it is important to always read fully and close streams + byte[] data = closeClientButKeepContentStream(response); + String message = data != null ? new String(data) : null; + + Exception exception = message != null ? new HttpResponseException(command, response, message) + : new HttpResponseException(command, response); + message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), + response.getStatusLine()); + switch (response.getStatusCode()) { + case 400: + break; + case 401: + case 403: + exception = new AuthorizationException(message, exception); + break; + case 404: + if (!command.getCurrentRequest().getMethod().equals("DELETE")) { + exception = new ResourceNotFoundException(message, exception); + } + break; + } + command.setException(exception); + } +} diff --git a/labs/openstack-quantum/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata b/labs/openstack-quantum/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata new file mode 100644 index 0000000000..ebd176c892 --- /dev/null +++ b/labs/openstack-quantum/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata @@ -0,0 +1 @@ +org.jclouds.openstack.quantum.v1_0.QuantumApiMetadata diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadataTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadataTest.java new file mode 100644 index 0000000000..ce08db29fd --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadataTest.java @@ -0,0 +1,37 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0; + +import org.jclouds.View; +import org.jclouds.apis.internal.BaseApiMetadataTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; +import com.google.common.reflect.TypeToken; + +/** + * + * @author Adam Lowe + */ +@Test(groups = "unit", testName = "QuantumApiMetadataTest") +public class QuantumApiMetadataTest extends BaseApiMetadataTest { + public QuantumApiMetadataTest() { + super(new QuantumApiMetadata(), ImmutableSet.> of()); + } +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java new file mode 100644 index 0000000000..b89b3ffc7b --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java @@ -0,0 +1,236 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 1.1 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-1.1 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.Set; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.openstack.quantum.v1_0.domain.Network; +import org.jclouds.openstack.quantum.v1_0.domain.NetworkDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import org.jclouds.openstack.quantum.v1_0.internal.BaseQuantumClientExpectTest; +import org.jclouds.openstack.quantum.v1_0.parse.ParseNetworkDetailsTest; +import org.jclouds.openstack.quantum.v1_0.parse.ParseNetworkTest; +import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.ResourceNotFoundException; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * Tests parsing and Guice wiring of NetworkClient + * + * @author Adam Lowe + */ +@Test(groups="unit", testName = "NetworkClientExpectTest") +public class NetworkClientExpectTest extends BaseQuantumClientExpectTest { + + public void testListReferencesReturns2xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks").build(), + standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/list_network_refs.json", APPLICATION_JSON)).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + Set nets = client.listReferences(); + assertEquals(nets, listOfNetworkRefs()); + } + + public void testListReferencesReturns4xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks").build(), + standardResponseBuilder(404).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + assertTrue(client.listReferences().isEmpty()); + } + + public void testListReturns2xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/detail").build(), + standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/list_networks.json", APPLICATION_JSON)).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + Set nets = client.list(); + assertEquals(nets, listOfNetworks()); + } + + public void testListReturns4xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/detail").build(), + standardResponseBuilder(404).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + assertTrue(client.list().isEmpty()); + } + + public void testShowReturns2xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a").build(), + standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/network.json", APPLICATION_JSON)).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + Network net = client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + assertEquals(net, new ParseNetworkTest().expected()); + } + + public void testShowReturns4xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a").build(), + standardResponseBuilder(404).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + assertNull(client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); + } + + public void testShowDetailsReturns2xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/detail").build(), + standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/network_details.json", APPLICATION_JSON)).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + NetworkDetails net = client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + assertEquals(net, new ParseNetworkDetailsTest().expected()); + } + + public void testShowDetailsReturns4xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/detail").build(), + standardResponseBuilder(404).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + assertNull(client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); + } + + public void testCreateReturns2xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks").method("POST") + .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), + standardResponseBuilder(200).payload(payloadFromStringWithContentType("{\"network\":{\"id\":\"12345\"}}", APPLICATION_JSON)).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + Reference net = client.create("another-test"); + assertEquals(net, Reference.builder().id("12345").build()); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testCreateReturns4xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks").method("POST") + .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), + standardResponseBuilder(401).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + client.create("another-test"); + } + + public void testUpdateReturns2xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/12345").method("PUT") + .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), + standardResponseBuilder(200).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + assertTrue(client.update("12345", "another-test")); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void testUpdateReturns4xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/12345").method("PUT") + .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), + standardResponseBuilder(404).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + client.update("12345", "another-test"); + } + + public void testDeleteReturns2xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/12345").method("DELETE").build(), + standardResponseBuilder(200).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + assertTrue(client.delete("12345")); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testDeleteReturns4xx() { + NetworkClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/12345").method("DELETE").build(), + standardResponseBuilder(403).build()) + .getNetworkClientForRegion("region-a.geo-1"); + + client.delete("12345"); + } + + protected Set listOfNetworkRefs() { + return ImmutableSet.of( + Reference.builder().id("16dba3bc-f3fa-4775-afdc-237e12c72f6a").build(), + Reference.builder().id("1a104cf5-cb18-4d35-9407-2fd2646d9d0b").build(), + Reference.builder().id("31083ae2-420d-48b2-ac98-9f7a4fd8dbdc").build(), + Reference.builder().id("49c6d6fa-ff2a-459d-b975-75a8d31c9a89").build(), + Reference.builder().id("5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e").build(), + Reference.builder().id("5d51d012-3491-4db7-b1b5-6f254015015d").build(), + Reference.builder().id("5f9cf7dc-22ca-4097-8e49-1cc8b23faf17").build(), + Reference.builder().id("6319ecad-6bff-48b2-9b53-02ede8cb7588").build(), + Reference.builder().id("6ba4c788-661f-49ab-9bf8-5f10cbbb2f57").build(), + Reference.builder().id("74ed170b-5069-4353-ab38-9719766dc57e").build(), + Reference.builder().id("b71fcac1-e864-4031-8c5b-edbecd9ece36").build(), + Reference.builder().id("c7681895-d84d-4650-9ca0-82c72036b855").build() + ); + } + + protected Set listOfNetworks() { + return ImmutableSet.of( + Network.builder().name("jclouds-port-test").id("16dba3bc-f3fa-4775-afdc-237e12c72f6a").build(), + Network.builder().name("wibble").id("1a104cf5-cb18-4d35-9407-2fd2646d9d0b").build(), + Network.builder().name("jclouds-test").id("31083ae2-420d-48b2-ac98-9f7a4fd8dbdc").build(), + Network.builder().name("jclouds-test").id("49c6d6fa-ff2a-459d-b975-75a8d31c9a89").build(), + Network.builder().name("wibble").id("5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e").build(), + Network.builder().name("jclouds-port-test").id("5d51d012-3491-4db7-b1b5-6f254015015d").build(), + Network.builder().name("wibble").id("5f9cf7dc-22ca-4097-8e49-1cc8b23faf17").build(), + Network.builder().name("jclouds-test").id("6319ecad-6bff-48b2-9b53-02ede8cb7588").build(), + Network.builder().name("jclouds-port-test").id("6ba4c788-661f-49ab-9bf8-5f10cbbb2f57").build(), + Network.builder().name("jclouds-test").id("74ed170b-5069-4353-ab38-9719766dc57e").build(), + Network.builder().name("wibble").id("b71fcac1-e864-4031-8c5b-edbecd9ece36").build(), + Network.builder().name("jclouds-port-test").id("c7681895-d84d-4650-9ca0-82c72036b855").build() + ); + } + +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java new file mode 100644 index 0000000000..80baef53f3 --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java @@ -0,0 +1,92 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 1.1 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-1.1 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.util.Set; + +import org.jclouds.openstack.quantum.v1_0.domain.Network; +import org.jclouds.openstack.quantum.v1_0.domain.NetworkDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import org.jclouds.openstack.quantum.v1_0.internal.BaseQuantumClientLiveTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; + +/** + * Tests NetworkClient + * + * @author Adam Lowe + */ +@Test(groups = "live", testName = "NetworkClientLiveTest", singleThreaded = true) +public class NetworkClientLiveTest extends BaseQuantumClientLiveTest { + + public void testListNetworks() { + for (String regionId : quantumContext.getApi().getConfiguredRegions()) { + Set ids = quantumContext.getApi().getNetworkClientForRegion(regionId).listReferences(); + Set networks = quantumContext.getApi().getNetworkClientForRegion(regionId).list(); + assertNotNull(ids); + assertEquals(ids.size(), networks.size()); + for (Network network : networks) { + assertNotNull(network.getName()); + assertTrue(ids.contains(Reference.builder().id(network.getId()).build())); + } + } + } + + public void testCreateUpdateAndDeleteNetwork() { + for (String regionId : quantumContext.getApi().getConfiguredRegions()) { + NetworkClient client = quantumContext.getApi().getNetworkClientForRegion(regionId); + Reference net = client.create("jclouds-test"); + assertNotNull(net); + + Network network = client.show(net.getId()); + NetworkDetails details = client.showDetails(net.getId()); + + for(Network checkme : ImmutableList.of(network, details)) { + assertEquals(checkme.getId(), net.getId()); + assertEquals(checkme.getName(), "jclouds-test"); + } + + assertTrue(details.getPorts().isEmpty()); + + assertTrue(client.update(net.getId(), "jclouds-live-test")); + + // Grab the updated metadata + network = client.show(net.getId()); + details = client.showDetails(net.getId()); + + for(Network checkme : ImmutableList.of(network, details)) { + assertEquals(checkme.getId(), net.getId()); + assertEquals(checkme.getName(), "jclouds-live-test"); + } + + assertTrue(details.getPorts().isEmpty()); + + Reference net2 = client.create("jclouds-test2"); + assertNotNull(net2); + + assertTrue(client.delete(net.getId())); + assertTrue(client.delete(net2.getId())); + } + } +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java new file mode 100644 index 0000000000..662210daaa --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java @@ -0,0 +1,246 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 1.1 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-1.1 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.Set; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.openstack.quantum.v1_0.domain.Attachment; +import org.jclouds.openstack.quantum.v1_0.domain.Port; +import org.jclouds.openstack.quantum.v1_0.domain.PortDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import org.jclouds.openstack.quantum.v1_0.internal.BaseQuantumClientExpectTest; +import org.jclouds.openstack.quantum.v1_0.parse.ParsePortDetailsTest; +import org.jclouds.openstack.quantum.v1_0.parse.ParsePortTest; +import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.ResourceNotFoundException; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * Tests parsing and Guice wiring of PortClient + * + * @author Adam Lowe + */ +@Test(groups="unit", testName = "PortClientExpectTest") +public class PortClientExpectTest extends BaseQuantumClientExpectTest { + + public void testListReferencesReturns2xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports").build(), + standardResponseBuilder(200).payload(payloadFromStringWithContentType("{\"ports\": [{\"id\": \"a6058a59-fa8c-46cc-bac8-08904e6ff0a5\"}]}", APPLICATION_JSON)).build()) + .getPortClientForRegion("region-a.geo-1"); + + Set nets = client.listReferences("1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + assertEquals(nets, ImmutableSet.of(Reference.builder().id("a6058a59-fa8c-46cc-bac8-08904e6ff0a5").build())); + } + + public void testListReferencesReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports").build(), + standardResponseBuilder(404).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertTrue(client.listReferences("1a104cf5-cb18-4d35-9407-2fd2646d9d0b").isEmpty()); + } + + public void testListReturns2xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports/detail").build(), + standardResponseBuilder(200).payload(payloadFromStringWithContentType("{\"ports\": [{\"state\": \"DOWN\", \"id\": \"814ae4bb-33d9-425f-8ee2-13a5c90b1465\"}]}", APPLICATION_JSON)).build()) + .getPortClientForRegion("region-a.geo-1"); + + Set nets = client.list("1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + assertEquals(nets, ImmutableSet.of(Port.builder().state(Port.State.DOWN).id("814ae4bb-33d9-425f-8ee2-13a5c90b1465").build())); + } + + public void testListReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports/detail").build(), + standardResponseBuilder(404).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertTrue(client.list("1a104cf5-cb18-4d35-9407-2fd2646d9d0b").isEmpty()); + } + + public void testShowReturns2xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df").build(), + standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/port.json", APPLICATION_JSON)).build()) + .getPortClientForRegion("region-a.geo-1"); + + Port port = client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df"); + assertEquals(port, new ParsePortTest().expected()); + } + + public void testShowReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df").build(), + standardResponseBuilder(404).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertNull(client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df")); + } + + public void testShowDetailsReturns2xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df/detail").build(), + standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/port_details.json", APPLICATION_JSON)).build()) + .getPortClientForRegion("region-a.geo-1"); + + PortDetails net = client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df"); + assertEquals(net, new ParsePortDetailsTest().expected()); + } + + public void testShowDetailsReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df/detail").build(), + standardResponseBuilder(404).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertNull(client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df")); + } + + public void testCreateReturns2xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports").method("POST").build(), + standardResponseBuilder(200).payload(payloadFromStringWithContentType("{\"port\":{\"id\":\"12345\"}}", APPLICATION_JSON)).build()) + .getPortClientForRegion("region-a.geo-1"); + + Reference port = client.create("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + assertEquals(port, Reference.builder().id("12345").build()); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void testCreateReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports").method("POST").build(), + standardResponseBuilder(404).build()) + .getPortClientForRegion("region-a.geo-1"); + + client.create("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + } + + public void testUpdateReturns2xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777").method("PUT") + .payload(payloadFromStringWithContentType("{\"port\":{\"state\":\"ACTIVE\"}}", MediaType.APPLICATION_JSON)).build(), + standardResponseBuilder(200).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertTrue(client.update("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", Port.State.ACTIVE)); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testUpdateReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777").method("PUT") + .payload(payloadFromStringWithContentType("{\"port\":{\"state\":\"ACTIVE\"}}", MediaType.APPLICATION_JSON)).build(), + standardResponseBuilder(401).build()) + .getPortClientForRegion("region-a.geo-1"); + + client.update("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", Port.State.ACTIVE); + } + + public void testShowAttachment() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").build(), + standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/attachment.json", APPLICATION_JSON)).build()) + .getPortClientForRegion("region-a.geo-1"); + + Attachment attachment = client.showAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777"); + assertEquals(attachment, Attachment.builder().id("jclouds-live-test").build()); + } + + public void testShowAttachmentReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").build(), + standardResponseBuilder(404).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertNull(client.showAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777")); + } + + public void testPlugAttachment() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment") + .payload(payloadFromStringWithContentType("{\"attachment\":{\"id\":\"jclouds-live-test\"}}", MediaType.APPLICATION_JSON)) + .method("PUT").build(), + standardResponseBuilder(200).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertTrue(client.plugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", "jclouds-live-test")); + } + + @Test(expectedExceptions = AuthorizationException.class) + public void testPlugAttachmentReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment") + .payload(payloadFromStringWithContentType("{\"attachment\":{\"id\":\"jclouds-live-test\"}}", MediaType.APPLICATION_JSON)) + .method("PUT").build(), + standardResponseBuilder(403).build()) + .getPortClientForRegion("region-a.geo-1"); + + client.plugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", "jclouds-live-test"); + } + public void testUnplugAttachment() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").method("DELETE").build(), + standardResponseBuilder(200).build()) + .getPortClientForRegion("region-a.geo-1"); + + assertTrue(client.unplugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777")); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void testUnplugAttachmentReturns4xx() { + PortClient client = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").method("DELETE").build(), + standardResponseBuilder(404).build()) + .getPortClientForRegion("region-a.geo-1"); + + client.unplugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777"); + } + +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java new file mode 100644 index 0000000000..75f02de0dc --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java @@ -0,0 +1,137 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 1.1 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-1.1 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.features; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.util.Set; + +import org.jclouds.openstack.quantum.v1_0.domain.Attachment; +import org.jclouds.openstack.quantum.v1_0.domain.NetworkDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Port; +import org.jclouds.openstack.quantum.v1_0.domain.PortDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import org.jclouds.openstack.quantum.v1_0.internal.BaseQuantumClientLiveTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; + +/** + * Tests PortClient + * + * @author Adam Lowe + */ +@Test(groups = "live", testName = "PortClientLiveTest", singleThreaded = true) +public class PortClientLiveTest extends BaseQuantumClientLiveTest { + + public void testListPorts() { + for (String regionId : quantumContext.getApi().getConfiguredRegions()) { + NetworkClient netClient = quantumContext.getApi().getNetworkClientForRegion(regionId); + PortClient portClient = quantumContext.getApi().getPortClientForRegion(regionId); + Set nets = netClient.listReferences(); + for(Reference net : nets) { + Set portRefs = portClient.listReferences(net.getId()); + Set ports = portClient.list(net.getId()); + + assertEquals(portRefs.size(), ports.size()); + for (Port port : ports) { + assertTrue(portRefs.contains(Reference.builder().id(port.getId()).build())); + } + } + } + } + + public void testCreateUpdateAndDeletePort() { + for (String regionId : quantumContext.getApi().getConfiguredRegions()) { + NetworkClient netClient = quantumContext.getApi().getNetworkClientForRegion(regionId); + PortClient portClient = quantumContext.getApi().getPortClientForRegion(regionId); + Reference net = netClient.create("jclouds-port-test"); + assertNotNull(net); + + Reference portRef = portClient.create(net.getId()); + assertNotNull(portRef); + + Port port = portClient.show(net.getId(), portRef.getId()); + PortDetails portDetails = portClient.showDetails(net.getId(), portRef.getId()); + NetworkDetails networkDetails = netClient.showDetails(net.getId()); + + assertEquals(port.getState(), portDetails.getState()); + + for(Port checkme : ImmutableList.of(port, portDetails, Iterables.getOnlyElement(networkDetails.getPorts()))) { + assertEquals(checkme.getId(), portRef.getId()); + } + + assertTrue(portClient.update(net.getId(), portRef.getId(), Port.State.DOWN)); + + port = portClient.show(net.getId(), portRef.getId()); + portDetails = portClient.showDetails(net.getId(), portRef.getId()); + + for(Port checkme : ImmutableList.of(port, portDetails)) { + assertEquals(checkme.getId(), portRef.getId()); + assertEquals(checkme.getState(), Port.State.DOWN); + } + + assertTrue(portClient.plugAttachment(net.getId(), port.getId(), "jclouds-live-test")); + + Attachment attachment = portClient.showAttachment(net.getId(), port.getId()); + portDetails = portClient.showDetails(net.getId(), portRef.getId()); + + for(Attachment checkme : ImmutableList.of(attachment, portDetails.getAttachment())) { + assertNotNull(checkme); + assertEquals(checkme.getId(), "jclouds-live-test"); + } + + assertTrue(portClient.unplugAttachment(net.getId(), port.getId())); + + assertTrue(portClient.delete(net.getId(), portRef.getId())); + assertTrue(netClient.delete(net.getId())); + } + } + + @Test(enabled=false) // assuming attachmentId matters in the wild + public void testAttachAndDetachPort() { + for (String regionId : quantumContext.getApi().getConfiguredRegions()) { + NetworkClient netClient = quantumContext.getApi().getNetworkClientForRegion(regionId); + PortClient portClient = quantumContext.getApi().getPortClientForRegion(regionId); + Reference net = netClient.create("jclouds-attach-test"); + assertNotNull(net); + + Reference port = portClient.create(net.getId()); + assertNotNull(port); + + assertTrue(portClient.plugAttachment(net.getId(), port.getId(), "jclouds-live-test")); + + Attachment attachment = portClient.showAttachment(net.getId(), port.getId()); + PortDetails portDetails = portClient.showDetails(net.getId(), port.getId()); + + for(Attachment checkme : ImmutableList.of(attachment, portDetails.getAttachment())) { + assertNotNull(checkme); + assertEquals(checkme.getId(), "jclouds-live-test"); + } + + assertTrue(portClient.unplugAttachment(net.getId(), port.getId())); + + assertTrue(portClient.delete(net.getId(), port.getId())); + assertTrue(netClient.delete(net.getId())); + } + } +} \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientExpectTest.java new file mode 100644 index 0000000000..3204f17834 --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientExpectTest.java @@ -0,0 +1,49 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.internal; + +import java.net.URI; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.quantum.v1_0.QuantumClient; + +import com.google.common.collect.ImmutableMultimap; + +/** + * Base class for writing Quantum Rest Client Expect tests + * + * @author Adam Lowe + */ +public class BaseQuantumClientExpectTest extends BaseQuantumExpectTest { + protected String endpoint = "https://csnode.jclouds.org:9696/v1.0"; + + protected HttpRequest.Builder standardRequestBuilder(String endpoint) { + return HttpRequest.builder().method("GET") + .headers(ImmutableMultimap.of("Accept", MediaType.APPLICATION_JSON, "X-Auth-Token", authToken)) + .endpoint(URI.create(endpoint)); + } + + protected HttpResponse.Builder standardResponseBuilder(int status) { + return HttpResponse.builder().statusCode(status); + } + +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientLiveTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientLiveTest.java new file mode 100644 index 0000000000..02e8d5b2bd --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumClientLiveTest.java @@ -0,0 +1,74 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.internal; + +import java.util.Properties; + +import org.jclouds.apis.BaseContextLiveTest; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties; +import org.jclouds.openstack.quantum.v1_0.QuantumApiMetadata; +import org.jclouds.openstack.quantum.v1_0.QuantumAsyncClient; +import org.jclouds.openstack.quantum.v1_0.QuantumClient; +import org.jclouds.rest.RestContext; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +import com.google.common.reflect.TypeToken; + +/** + * Tests behavior of {@code QuantumClient} + * + * @author Adam Lowe + */ +@Test(groups = "live") +public class BaseQuantumClientLiveTest extends BaseContextLiveTest> { + + public BaseQuantumClientLiveTest() { + provider = "openstack-quantum"; + } + + protected RestContext quantumContext; + + @BeforeGroups(groups = { "integration", "live" }) + @Override + public void setupContext() { + super.setupContext(); + quantumContext = context; + } + + @Override + protected Properties setupProperties() { + Properties props = super.setupProperties(); + setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE); + return props; + } + + @AfterGroups(groups = "live") + protected void tearDown() { + if (quantumContext != null) + quantumContext.close(); + } + + @Override + protected TypeToken> contextType() { + return QuantumApiMetadata.CONTEXT_TOKEN; + } + +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumExpectTest.java new file mode 100644 index 0000000000..282fdc369f --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/internal/BaseQuantumExpectTest.java @@ -0,0 +1,49 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.internal; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.keystone.v2_0.internal.KeystoneFixture; +import org.jclouds.rest.internal.BaseRestClientExpectTest; + +/** + * Base class for writing Quantum Expect tests + * + * @author Adam Lowe + */ +public class BaseQuantumExpectTest extends BaseRestClientExpectTest { + protected HttpRequest keystoneAuthWithUsernameAndPassword; + protected HttpRequest keystoneAuthWithAccessKeyAndSecretKey; + protected String authToken; + protected HttpResponse responseWithKeystoneAccess; + + public BaseQuantumExpectTest() { + provider = "openstack-quantum"; + keystoneAuthWithUsernameAndPassword = KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPassword(identity, + credential); + keystoneAuthWithAccessKeyAndSecretKey = KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKey(identity, + credential); + + authToken = KeystoneFixture.INSTANCE.getAuthToken(); + responseWithKeystoneAccess = KeystoneFixture.INSTANCE.responseWithAccess(); + // now, createContext arg will need tenant prefix + identity = KeystoneFixture.INSTANCE.getTenantName() + ":" + identity; + } +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseAttachmentTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseAttachmentTest.java new file mode 100644 index 0000000000..68d240b744 --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseAttachmentTest.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.parse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.openstack.quantum.v1_0.domain.Attachment; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +/** + * + * @author Adam Lowe + */ +@Test(groups = "unit", testName = "ParseAttachmentTest") +public class ParseAttachmentTest extends BaseItemParserTest { + + @Override + public String resource() { + return "/attachment.json"; + } + + @Override + @SelectJson("attachment") + @Consumes(MediaType.APPLICATION_JSON) + public Attachment expected() { + return Attachment.builder().id("jclouds-live-test").build(); + } +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkDetailsTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkDetailsTest.java new file mode 100644 index 0000000000..bb2ecf703e --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkDetailsTest.java @@ -0,0 +1,51 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.parse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.openstack.quantum.v1_0.domain.NetworkDetails; +import org.jclouds.openstack.quantum.v1_0.domain.Port; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adam Lowe + */ +@Test(groups = "unit", testName = "ParseNetworkDetailsTest") +public class ParseNetworkDetailsTest extends BaseItemParserTest { + + @Override + public String resource() { + return "/network_details.json"; + } + + @Override + @SelectJson("network") + @Consumes(MediaType.APPLICATION_JSON) + public NetworkDetails expected() { + return NetworkDetails.builder().name("jclouds-port-test").id("25e3e0f8-f1f0-4850-97a3-8d5393c3385b") + .ports(ImmutableSet.of(Port.builder().state(Port.State.DOWN).id("908391f6-ef3c-4bc6-acec-46582f9b231d").build())).build(); + } +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkTest.java new file mode 100644 index 0000000000..3af65aac8f --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParseNetworkTest.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.parse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.openstack.quantum.v1_0.domain.Network; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +/** + * + * @author Adam Lowe + */ +@Test(groups = "unit", testName = "ParseNetworkTest") +public class ParseNetworkTest extends BaseItemParserTest { + + @Override + public String resource() { + return "/network.json"; + } + + @Override + @SelectJson("network") + @Consumes(MediaType.APPLICATION_JSON) + public Network expected() { + return Network.builder().name("jclouds-wibble").id("624312ff-d14b-4ba3-9834-1c78d23d574d").build(); + } +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortDetailsTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortDetailsTest.java new file mode 100644 index 0000000000..ac740d49e7 --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortDetailsTest.java @@ -0,0 +1,49 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.parse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.openstack.quantum.v1_0.domain.Attachment; +import org.jclouds.openstack.quantum.v1_0.domain.Port; +import org.jclouds.openstack.quantum.v1_0.domain.PortDetails; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +/** + * @author Adam Lowe + */ +@Test(groups = "unit", testName = "ParsePortDetailsTest") +public class ParsePortDetailsTest extends BaseItemParserTest { + + @Override + public String resource() { + return "/port_details.json"; + } + + @Override + @SelectJson("port") + @Consumes(MediaType.APPLICATION_JSON) + public PortDetails expected() { + return PortDetails.builder().id("0ccbe514-e36b-475b-91c9-208dfd96d3ac").state(Port.State.DOWN) + .attachment(Attachment.builder().id("jclouds-live-test").build()).build(); + } +} diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortTest.java new file mode 100644 index 0000000000..ffc5011fd1 --- /dev/null +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/parse/ParsePortTest.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.quantum.v1_0.parse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.openstack.quantum.v1_0.domain.Port; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +/** + * + * @author Adam Lowe + */ +@Test(groups = "unit", testName = "ParsePortTest") +public class ParsePortTest extends BaseItemParserTest { + + @Override + public String resource() { + return "/port.json"; + } + + @Override + @SelectJson("port") + @Consumes(MediaType.APPLICATION_JSON) + public Port expected() { + return Port.builder().id("646c123b-871a-4124-9fa2-a94f04a582df").state(Port.State.DOWN).build(); + } +} diff --git a/labs/openstack-quantum/src/test/resources/attachment.json b/labs/openstack-quantum/src/test/resources/attachment.json new file mode 100644 index 0000000000..e13505594c --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/attachment.json @@ -0,0 +1 @@ +{"attachment":{"id":"jclouds-live-test"}} \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/resources/list_network_refs.json b/labs/openstack-quantum/src/test/resources/list_network_refs.json new file mode 100644 index 0000000000..d6daf8d74d --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/list_network_refs.json @@ -0,0 +1,14 @@ +{"networks": [ + {"id": "16dba3bc-f3fa-4775-afdc-237e12c72f6a"}, + {"id": "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"}, + {"id": "31083ae2-420d-48b2-ac98-9f7a4fd8dbdc"}, + {"id": "49c6d6fa-ff2a-459d-b975-75a8d31c9a89"}, + {"id": "5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e"}, + {"id": "5d51d012-3491-4db7-b1b5-6f254015015d"}, + {"id": "5f9cf7dc-22ca-4097-8e49-1cc8b23faf17"}, + {"id": "6319ecad-6bff-48b2-9b53-02ede8cb7588"}, + {"id": "6ba4c788-661f-49ab-9bf8-5f10cbbb2f57"}, + {"id": "74ed170b-5069-4353-ab38-9719766dc57e"}, + {"id": "b71fcac1-e864-4031-8c5b-edbecd9ece36"}, + {"id": "c7681895-d84d-4650-9ca0-82c72036b855"} +]} \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/resources/list_networks.json b/labs/openstack-quantum/src/test/resources/list_networks.json new file mode 100644 index 0000000000..b5c78393ec --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/list_networks.json @@ -0,0 +1,14 @@ +{"networks": [ + {"name": "jclouds-port-test", "id": "16dba3bc-f3fa-4775-afdc-237e12c72f6a"}, + {"name": "wibble", "id": "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"}, + {"name": "jclouds-test", "id": "31083ae2-420d-48b2-ac98-9f7a4fd8dbdc"}, + {"name": "jclouds-test", "id": "49c6d6fa-ff2a-459d-b975-75a8d31c9a89"}, + {"name": "wibble", "id": "5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e"}, + {"name": "jclouds-port-test", "id": "5d51d012-3491-4db7-b1b5-6f254015015d"}, + {"name": "wibble", "id": "5f9cf7dc-22ca-4097-8e49-1cc8b23faf17"}, + {"name": "jclouds-test", "id": "6319ecad-6bff-48b2-9b53-02ede8cb7588"}, + {"name": "jclouds-port-test", "id": "6ba4c788-661f-49ab-9bf8-5f10cbbb2f57"}, + {"name": "jclouds-test", "id": "74ed170b-5069-4353-ab38-9719766dc57e"}, + {"name": "wibble", "id": "b71fcac1-e864-4031-8c5b-edbecd9ece36"}, + {"name": "jclouds-port-test", "id": "c7681895-d84d-4650-9ca0-82c72036b855"} +] \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/resources/logback.xml b/labs/openstack-quantum/src/test/resources/logback.xml new file mode 100644 index 0000000000..e4ba99b357 --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/logback.xml @@ -0,0 +1,51 @@ + + + + target/test-data/jclouds.log + + + %d %-5p [%c] [%thread] %m%n + + + + + target/test-data/jclouds-wire.log + + + %d %-5p [%c] [%thread] %m%n + + + + + target/test-data/jclouds-blobstore.log + + + %d %-5p [%c] [%thread] %m%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/labs/openstack-quantum/src/test/resources/network.json b/labs/openstack-quantum/src/test/resources/network.json new file mode 100644 index 0000000000..fec734d654 --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/network.json @@ -0,0 +1 @@ +{"network": {"name": "jclouds-wibble", "id": "624312ff-d14b-4ba3-9834-1c78d23d574d"}} \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/resources/network_details.json b/labs/openstack-quantum/src/test/resources/network_details.json new file mode 100644 index 0000000000..0ee7025da3 --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/network_details.json @@ -0,0 +1 @@ +{"network": {"ports": [{"state": "DOWN", "id": "908391f6-ef3c-4bc6-acec-46582f9b231d"}], "name": "jclouds-port-test", "id": "25e3e0f8-f1f0-4850-97a3-8d5393c3385b"}} \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/resources/port.json b/labs/openstack-quantum/src/test/resources/port.json new file mode 100644 index 0000000000..371fcb4697 --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/port.json @@ -0,0 +1 @@ +{"port": {"state": "DOWN", "id": "646c123b-871a-4124-9fa2-a94f04a582df"}} \ No newline at end of file diff --git a/labs/openstack-quantum/src/test/resources/port_details.json b/labs/openstack-quantum/src/test/resources/port_details.json new file mode 100644 index 0000000000..5481135bac --- /dev/null +++ b/labs/openstack-quantum/src/test/resources/port_details.json @@ -0,0 +1 @@ +{"port": {"state": "DOWN", "id": "0ccbe514-e36b-475b-91c9-208dfd96d3ac", "attachment": {"id": "jclouds-live-test"}}} \ No newline at end of file diff --git a/labs/pom.xml b/labs/pom.xml index 521a07e677..a976fc93d1 100644 --- a/labs/pom.xml +++ b/labs/pom.xml @@ -47,5 +47,6 @@ openstack-glance joyent-sdc openstack-keystone + openstack-quantum From c47017e640f19623dfd810461997cf088fe3369d Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Fri, 1 Jun 2012 16:06:15 +0100 Subject: [PATCH 17/73] openstack-quantum: correcting bundle configuration --- labs/openstack-quantum/pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/labs/openstack-quantum/pom.xml b/labs/openstack-quantum/pom.xml index a37221da36..f105267988 100644 --- a/labs/openstack-quantum/pom.xml +++ b/labs/openstack-quantum/pom.xml @@ -135,9 +135,8 @@ ${project.artifactId} - org.jclouds.openstack.quantum.v1*;version="${project.version}" + org.jclouds.openstack.quantum.v1_0*;version="${project.version}" - org.jclouds.blobstore.internal;version="${project.version}", org.jclouds.rest.internal;version="${project.version}", org.jclouds*;version="${project.version}", * From 6d74805dd9091155edda27739517c0409923d410 Mon Sep 17 00:00:00 2001 From: vijaykiran Date: Fri, 1 Jun 2012 22:16:04 +0200 Subject: [PATCH 18/73] Issue-953 Make sure that port is set when modifying headers --- .../jclouds/s3/binders/BindAsHostPrefixIfConfigured.java | 6 +++++- .../org/jclouds/http/handlers/RedirectionRetryHandler.java | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java b/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java index d5675e8dba..321910f564 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java +++ b/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java @@ -65,7 +65,11 @@ public class BindAsHostPrefixIfConfigured implements Binder { public R bindToRequest(R request, Object payload) { if (isVhostStyle) { request = bindAsHostPrefix.bindToRequest(request, payload); - return ModifyRequest.replaceHeader(request, HttpHeaders.HOST, request.getEndpoint().getHost()); + String host = request.getEndpoint().getHost(); + if (request.getEndpoint().getPort() != -1) { + host += ":" + request.getEndpoint().getPort(); + } + return ModifyRequest.replaceHeader(request, HttpHeaders.HOST, host); } else { UriBuilder builder = uriBuilderProvider.get().uri(request.getEndpoint()); StringBuilder path = new StringBuilder(Strings2.urlEncode(request.getEndpoint().getPath(), S3AsyncClient.class diff --git a/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java b/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java index 1966bc3a80..566e7092ef 100644 --- a/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java +++ b/core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java @@ -85,8 +85,12 @@ public class RedirectionRetryHandler implements HttpRetryHandler { } if (currentRequest.getFirstHeaderOrNull(HOST) != null && redirectionUrl.getHost() != null) { + String host = redirectionUrl.getHost(); + if (redirectionUrl.getPort() != -1) { + host += ":" + redirectionUrl.getPort(); + } command.setCurrentRequest(ModifyRequest.replaceHeader(currentRequest, HOST, - singletonList(redirectionUrl.getHost())).toBuilder().endpoint(redirectionUrl).build()); + singletonList(host)).toBuilder().endpoint(redirectionUrl).build()); } else { command.setCurrentRequest(currentRequest.toBuilder().endpoint(redirectionUrl).build()); } From 4008407de3d93af75d4e572d968b2be7905af355 Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Fri, 1 Jun 2012 22:41:45 +0100 Subject: [PATCH 19/73] Adding support for @Path and @PathParam to delegate methods to RestAnnotationProcessor --- .../internal/RestAnnotationProcessor.java | 6 ++-- .../internal/RestAnnotationProcessorTest.java | 32 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java index a0268d6b9a..101d863ba0 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -409,7 +409,9 @@ public class RestAnnotationProcessor { } this.caller = caller; try { - callerEndpoint = getEndpointFor(caller.getMethod(), caller.getArgs(), injector); + UriBuilder builder = uriBuilderProvider.get().uri(getEndpointFor(caller.getMethod(), caller.getArgs(), injector)); + Multimap tokenValues = addPathAndGetTokens(caller.getMethod().getDeclaringClass(), caller.getMethod(), caller.getArgs(), builder); + callerEndpoint = builder.buildFromEncodedMap(Maps2.convertUnsafe(tokenValues)); } catch (IllegalStateException e) { } catch (ExecutionException e) { Throwables.propagate(e); @@ -785,7 +787,7 @@ public class RestAnnotationProcessor { } public static URI addHostIfMissing(URI original, URI withHost) { - checkNotNull(withHost, "URI witHost cannot be null"); + checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) diff --git a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java index cd979810a5..996a6c2163 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -223,6 +223,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Delegate public Optional getOptionalCallee(@EndpointParam URI endpoint); + + @Delegate + @Path("/testing/testing/{wibble}") + public Callee getCalleeWithPath(@EndpointParam URI endpoint, @PathParam("wibble") String wibble); } @Timeout(duration = 10, timeUnit = TimeUnit.NANOSECONDS) @@ -253,6 +257,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Delegate public Optional getOptionalCallee(@EndpointParam URI endpoint); + + @Delegate + @Path("/testing/testing/{wibble}") + public AsyncCallee getCalleeWithPath(@EndpointParam URI endpoint, @PathParam("wibble") String wibble); } public void testAsyncDelegateIsLazyLoadedAndRequestIncludesVersionAndPath() throws InterruptedException, @@ -330,6 +338,30 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } + public void testAsyncDelegateWithPathParamIsLazyLoadedAndRequestIncludesEndpointVersionAndPath() throws InterruptedException, + ExecutionException { + Injector child = injectorForCaller(new HttpCommandExecutorService() { + + @Override + public Future submit(HttpCommand command) { + assertEquals(command.getCurrentRequest().getRequestLine(), "GET http://howdyboys/testing/testing/thepathparam/client/1/foo HTTP/1.1"); + return Futures.immediateFuture(HttpResponse.builder().build()); + } + + }); + + try { + child.getInstance(AsyncCallee.class); + assert false : "Callee shouldn't be bound yet"; + } catch (ConfigurationException e) { + + } + + child.getInstance(AsyncCaller.class).getCalleeWithPath(URI.create("http://howdyboys"), "thepathparam").onePath("foo").get(); + + assertEquals(child.getInstance(AsyncCaller.class).getURI(), URI.create("http://localhost:1111")); + } + public void testAsyncDelegateIsLazyLoadedAndRequestIncludesEndpointVersionAndPathOptionalPresent() throws InterruptedException, ExecutionException { Injector child = injectorForCaller(new HttpCommandExecutorService() { From c9de23a272f3bc52b435c5bcafab4f87f8c93e1b Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Fri, 1 Jun 2012 22:50:48 +0100 Subject: [PATCH 20/73] openstack-quantum: addressing review comments - adjusting method names and using @Path and @PathParam on delegate method to simplify PortClient --- labs/openstack-quantum/pom.xml | 13 +--- .../quantum/v1_0/QuantumAsyncClient.java | 7 +- .../openstack/quantum/v1_0/QuantumClient.java | 7 +- .../v1_0/features/NetworkAsyncClient.java | 12 ++-- .../quantum/v1_0/features/NetworkClient.java | 6 +- .../v1_0/features/PortAsyncClient.java | 53 +++++++------- .../quantum/v1_0/features/PortClient.java | 22 +++--- .../features/NetworkClientExpectTest.java | 12 ++-- .../v1_0/features/NetworkClientLiveTest.java | 10 +-- .../v1_0/features/PortClientExpectTest.java | 72 +++++++++---------- .../v1_0/features/PortClientLiveTest.java | 49 ++++++------- 11 files changed, 130 insertions(+), 133 deletions(-) diff --git a/labs/openstack-quantum/pom.xml b/labs/openstack-quantum/pom.xml index f105267988..39b4ff1922 100644 --- a/labs/openstack-quantum/pom.xml +++ b/labs/openstack-quantum/pom.xml @@ -42,8 +42,6 @@ FIXME_IDENTITY FIXME_CREDENTIALS passwordCredentials - FIXME_HTTPURL - FIXME_HTTPMD5 @@ -54,7 +52,7 @@ org.jclouds - jclouds-blobstore + jclouds-core ${project.version} @@ -71,13 +69,6 @@ test-jar test - - org.jclouds - jclouds-blobstore - ${project.version} - test-jar - test - org.jclouds.driver jclouds-slf4j @@ -115,8 +106,6 @@ ${test.openstack-quantum.identity} ${test.openstack-quantum.credential} ${test.jclouds.keystone.credential-type} - ${jclouds.blobstore.httpstream.url} - ${jclouds.blobstore.httpstream.md5} diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java index 53d85c9f37..98ffeb386c 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncClient.java @@ -20,6 +20,9 @@ package org.jclouds.openstack.quantum.v1_0; import java.util.Set; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.Region; import org.jclouds.location.functions.RegionToEndpoint; @@ -57,5 +60,7 @@ public interface QuantumAsyncClient { * Provides asynchronous access to Port features. */ @Delegate - PortAsyncClient getPortClientForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + @Path("/networks/{net}") + PortAsyncClient getPortClientForRegionAndNetwork(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, + @PathParam("net") String networkId); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java index 8bd93615cb..d670036eb8 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumClient.java @@ -21,6 +21,9 @@ package org.jclouds.openstack.quantum.v1_0; import java.util.Set; import java.util.concurrent.TimeUnit; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + import org.jclouds.concurrent.Timeout; import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.Region; @@ -59,5 +62,7 @@ public interface QuantumClient { * Provides synchronous access to Port features. */ @Delegate - PortClient getPortClientForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + @Path("/networks/{net}") + PortClient getPortClientForRegionAndNetwork(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, + @PathParam("net") String networkId); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java index fbefb75d3c..b0d114e0c8 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncClient.java @@ -76,22 +76,22 @@ public interface NetworkAsyncClient { ListenableFuture> list(); /** - * @see NetworkClient#show + * @see NetworkClient#get */ @GET @SelectJson("network") @Path("/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture show(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see NetworkClient#showDetails + * @see NetworkClient#getDetails */ @GET @SelectJson("network") @Path("/{id}/detail") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture showDetails(@PathParam("id") String id); + ListenableFuture getDetails(@PathParam("id") String id); /** * @see NetworkClient#create @@ -103,13 +103,13 @@ public interface NetworkAsyncClient { ListenableFuture create(@PayloadParam("name") String name); /** - * @see NetworkClient#update + * @see NetworkClient#rename */ @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @WrapWith("network") - ListenableFuture update(@PathParam("id") String id, @PayloadParam("name") String name); + ListenableFuture rename(@PathParam("id") String id, @PayloadParam("name") String name); /** * @see NetworkClient#delete diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java index 5647b33394..7ea23268a0 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java @@ -54,12 +54,12 @@ public interface NetworkClient { /** * Returns the specific network. */ - Network show(String id); + Network get(String id); /** * Returns the details of the specific network. */ - NetworkDetails showDetails(String id); + NetworkDetails getDetails(String id); /** * Create a new network with the specified symbolic name @@ -72,7 +72,7 @@ public interface NetworkClient { * @param id the id of the Network to modify * @param name the new name for the Network */ - Boolean update(String id, String name); + Boolean rename(String id, String name); /** * Deletes the specified network diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java index 6eab8cc10e..9535bc6bf5 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncClient.java @@ -55,7 +55,7 @@ import com.google.common.util.concurrent.ListenableFuture; @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) @Consumes(MediaType.APPLICATION_JSON) -@Path("/networks") +@Path("/ports") public interface PortAsyncClient { /** @@ -63,93 +63,90 @@ public interface PortAsyncClient { */ @GET @SelectJson("ports") - @Path("/{net}/ports") @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listReferences(@PathParam("net") String networkId); + ListenableFuture> listReferences(); /** * @see PortClient#list */ @GET @SelectJson("ports") - @Path("/{net}/ports/detail") + @Path("/detail") @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> list(@PathParam("net") String networkId); + ListenableFuture> list(); /** - * @see PortClient#show + * @see PortClient#get */ @GET @SelectJson("port") - @Path("/{net}/ports/{id}") + @Path("/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture show(@PathParam("net") String networkId, @PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see PortClient#showDetails + * @see PortClient#getDetails */ @GET @SelectJson("port") @Consumes(MediaType.APPLICATION_JSON) - @Path("/{net}/ports/{id}/detail") + @Path("/{id}/detail") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture showDetails(@PathParam("net") String networkId, @PathParam("id") String id); + ListenableFuture getDetails(@PathParam("id") String id); /** - * @see PortClient#create(String) + * @see PortClient#create() */ @POST @SelectJson("port") - @Path("/{net}/ports") - ListenableFuture create(@PathParam("net") String networkId); + ListenableFuture create(); /** - * @see PortClient#create(String, org.jclouds.openstack.quantum.v1_0.domain.Port.State) + * @see PortClient#create(org.jclouds.openstack.quantum.v1_0.domain.Port.State) */ @POST @SelectJson("port") - @Path("/{net}/ports") @WrapWith("port") - ListenableFuture create(@PathParam("net") String networkId, @PayloadParam("state") Port.State state); + ListenableFuture create(@PayloadParam("state") Port.State state); /** - * @see PortClient#update + * @see PortClient#updateState */ @PUT - @Path("/{net}/ports/{id}") + @Path("/{id}") @WrapWith("port") - ListenableFuture update(@PathParam("net") String networkId, @PathParam("id") String id, @PayloadParam("state") Port.State state); + ListenableFuture updateState(@PathParam("id") String id, @PayloadParam("state") Port.State state); /** * @see PortClient#delete */ @DELETE - @Path("/{net}/ports/{id}") - ListenableFuture delete(@PathParam("net") String networkId, @PathParam("id") String id); + @Path("/{id}") + ListenableFuture delete(@PathParam("id") String id); /** * @see PortClient#showAttachment */ @GET @SelectJson("attachment") - @Path("/{net}/ports/{portId}/attachment") + @Path("/{id}/attachment") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture showAttachment(@PathParam("net") String networkId, @PathParam("portId") String portId); + ListenableFuture showAttachment(@PathParam("id") String portId); /** * @see PortClient#plugAttachment */ @PUT - @Path("/{net}/ports/{portId}/attachment") + @Path("/{id}/attachment") @WrapWith("attachment") - ListenableFuture plugAttachment(@PathParam("net") String networkId, @PathParam("portId") String portId, + ListenableFuture plugAttachment(@PathParam("id") String portId, @PayloadParam("id") String attachmentId); /** * @see PortClient#unplugAttachment */ @DELETE - @Path("/{net}/ports/{portId}/attachment") - ListenableFuture unplugAttachment(@PathParam("net") String networkId, @PathParam("portId") String portId); + @Path("{id}/attachment") + ListenableFuture unplugAttachment(@PathParam("id") String portId); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java index c500a97b13..155e19f2f4 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java @@ -44,55 +44,55 @@ public interface PortClient { /** * Returns the list of all ports currently defined in Quantum for the requested network */ - Set listReferences(String networkId); + Set listReferences(); /** * Returns the set of ports currently defined in Quantum for the requested network. */ - Set list(String networkId); + Set list(); /** * Returns a specific port. */ - Port show(String networkId, String id); + Port get(String id); /** * Returns a specific port in detail. */ - PortDetails showDetails(String networkId, String id); + PortDetails getDetails(String id); /** * Create a new port on the specified network */ - Reference create(String networkId); + Reference create(); /** * Create a new port on the specified network, with the requested state */ - Reference create(String networkId, Port.State state); + Reference create(Port.State state); /** * Updates the state of a port */ - Boolean update(String networkId, String id, Port.State state); + Boolean updateState(String id, Port.State state); /** * Deletes a port from a network */ - Boolean delete(String networkId, String id); + Boolean delete(String id); /** * Returns the attachment for the specified port. */ - Attachment showAttachment(String networkId, String portId); + Attachment showAttachment(String portId); /** * Plugs an attachment into the specified port */ - Boolean plugAttachment(String networkId, String portId, String attachmentId); + Boolean plugAttachment(String portId, String attachmentId); /** * Unplugs the attachment currently plugged into the specified port */ - Boolean unplugAttachment(String networkId, String portId); + Boolean unplugAttachment(String portId); } diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java index b89b3ffc7b..0fc695e5f7 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientExpectTest.java @@ -96,7 +96,7 @@ public class NetworkClientExpectTest extends BaseQuantumClientExpectTest { standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/network.json", APPLICATION_JSON)).build()) .getNetworkClientForRegion("region-a.geo-1"); - Network net = client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + Network net = client.get("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertEquals(net, new ParseNetworkTest().expected()); } @@ -107,7 +107,7 @@ public class NetworkClientExpectTest extends BaseQuantumClientExpectTest { standardResponseBuilder(404).build()) .getNetworkClientForRegion("region-a.geo-1"); - assertNull(client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); + assertNull(client.get("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); } public void testShowDetailsReturns2xx() { @@ -117,7 +117,7 @@ public class NetworkClientExpectTest extends BaseQuantumClientExpectTest { standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/network_details.json", APPLICATION_JSON)).build()) .getNetworkClientForRegion("region-a.geo-1"); - NetworkDetails net = client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + NetworkDetails net = client.getDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertEquals(net, new ParseNetworkDetailsTest().expected()); } @@ -128,7 +128,7 @@ public class NetworkClientExpectTest extends BaseQuantumClientExpectTest { standardResponseBuilder(404).build()) .getNetworkClientForRegion("region-a.geo-1"); - assertNull(client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); + assertNull(client.getDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); } public void testCreateReturns2xx() { @@ -163,7 +163,7 @@ public class NetworkClientExpectTest extends BaseQuantumClientExpectTest { standardResponseBuilder(200).build()) .getNetworkClientForRegion("region-a.geo-1"); - assertTrue(client.update("12345", "another-test")); + assertTrue(client.rename("12345", "another-test")); } @Test(expectedExceptions = ResourceNotFoundException.class) @@ -175,7 +175,7 @@ public class NetworkClientExpectTest extends BaseQuantumClientExpectTest { standardResponseBuilder(404).build()) .getNetworkClientForRegion("region-a.geo-1"); - client.update("12345", "another-test"); + client.rename("12345", "another-test"); } public void testDeleteReturns2xx() { diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java index 80baef53f3..d807888dd8 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClientLiveTest.java @@ -59,8 +59,8 @@ public class NetworkClientLiveTest extends BaseQuantumClientLiveTest { Reference net = client.create("jclouds-test"); assertNotNull(net); - Network network = client.show(net.getId()); - NetworkDetails details = client.showDetails(net.getId()); + Network network = client.get(net.getId()); + NetworkDetails details = client.getDetails(net.getId()); for(Network checkme : ImmutableList.of(network, details)) { assertEquals(checkme.getId(), net.getId()); @@ -69,11 +69,11 @@ public class NetworkClientLiveTest extends BaseQuantumClientLiveTest { assertTrue(details.getPorts().isEmpty()); - assertTrue(client.update(net.getId(), "jclouds-live-test")); + assertTrue(client.rename(net.getId(), "jclouds-live-test")); // Grab the updated metadata - network = client.show(net.getId()); - details = client.showDetails(net.getId()); + network = client.get(net.getId()); + details = client.getDetails(net.getId()); for(Network checkme : ImmutableList.of(network, details)) { assertEquals(checkme.getId(), net.getId()); diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java index 662210daaa..80434441ec 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientExpectTest.java @@ -53,9 +53,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports").build(), standardResponseBuilder(200).payload(payloadFromStringWithContentType("{\"ports\": [{\"id\": \"a6058a59-fa8c-46cc-bac8-08904e6ff0a5\"}]}", APPLICATION_JSON)).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); - Set nets = client.listReferences("1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + Set nets = client.listReferences(); assertEquals(nets, ImmutableSet.of(Reference.builder().id("a6058a59-fa8c-46cc-bac8-08904e6ff0a5").build())); } @@ -64,9 +64,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports").build(), standardResponseBuilder(404).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); - assertTrue(client.listReferences("1a104cf5-cb18-4d35-9407-2fd2646d9d0b").isEmpty()); + assertTrue(client.listReferences().isEmpty()); } public void testListReturns2xx() { @@ -74,9 +74,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports/detail").build(), standardResponseBuilder(200).payload(payloadFromStringWithContentType("{\"ports\": [{\"state\": \"DOWN\", \"id\": \"814ae4bb-33d9-425f-8ee2-13a5c90b1465\"}]}", APPLICATION_JSON)).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); - Set nets = client.list("1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + Set nets = client.list(); assertEquals(nets, ImmutableSet.of(Port.builder().state(Port.State.DOWN).id("814ae4bb-33d9-425f-8ee2-13a5c90b1465").build())); } @@ -85,9 +85,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports/detail").build(), standardResponseBuilder(404).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); - assertTrue(client.list("1a104cf5-cb18-4d35-9407-2fd2646d9d0b").isEmpty()); + assertTrue(client.list().isEmpty()); } public void testShowReturns2xx() { @@ -95,9 +95,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df").build(), standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/port.json", APPLICATION_JSON)).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - Port port = client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df"); + Port port = client.get("646c123b-871a-4124-9fa2-a94f04a582df"); assertEquals(port, new ParsePortTest().expected()); } @@ -106,9 +106,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df").build(), standardResponseBuilder(404).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - assertNull(client.show("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df")); + assertNull(client.get("646c123b-871a-4124-9fa2-a94f04a582df")); } public void testShowDetailsReturns2xx() { @@ -116,9 +116,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df/detail").build(), standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/port_details.json", APPLICATION_JSON)).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - PortDetails net = client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df"); + PortDetails net = client.getDetails("646c123b-871a-4124-9fa2-a94f04a582df"); assertEquals(net, new ParsePortDetailsTest().expected()); } @@ -127,9 +127,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df/detail").build(), standardResponseBuilder(404).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - assertNull(client.showDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "646c123b-871a-4124-9fa2-a94f04a582df")); + assertNull(client.getDetails("646c123b-871a-4124-9fa2-a94f04a582df")); } public void testCreateReturns2xx() { @@ -137,9 +137,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports").method("POST").build(), standardResponseBuilder(200).payload(payloadFromStringWithContentType("{\"port\":{\"id\":\"12345\"}}", APPLICATION_JSON)).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - Reference port = client.create("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + Reference port = client.create(); assertEquals(port, Reference.builder().id("12345").build()); } @@ -149,9 +149,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports").method("POST").build(), standardResponseBuilder(404).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - client.create("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + client.create(); } public void testUpdateReturns2xx() { @@ -160,9 +160,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777").method("PUT") .payload(payloadFromStringWithContentType("{\"port\":{\"state\":\"ACTIVE\"}}", MediaType.APPLICATION_JSON)).build(), standardResponseBuilder(200).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - assertTrue(client.update("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", Port.State.ACTIVE)); + assertTrue(client.updateState("77777", Port.State.ACTIVE)); } @Test(expectedExceptions = AuthorizationException.class) @@ -172,9 +172,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777").method("PUT") .payload(payloadFromStringWithContentType("{\"port\":{\"state\":\"ACTIVE\"}}", MediaType.APPLICATION_JSON)).build(), standardResponseBuilder(401).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - client.update("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", Port.State.ACTIVE); + client.updateState("77777", Port.State.ACTIVE); } public void testShowAttachment() { @@ -182,9 +182,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").build(), standardResponseBuilder(200).payload(payloadFromResourceWithContentType("/attachment.json", APPLICATION_JSON)).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - Attachment attachment = client.showAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777"); + Attachment attachment = client.showAttachment("77777"); assertEquals(attachment, Attachment.builder().id("jclouds-live-test").build()); } @@ -193,9 +193,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").build(), standardResponseBuilder(404).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - assertNull(client.showAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777")); + assertNull(client.showAttachment("77777")); } public void testPlugAttachment() { @@ -205,9 +205,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { .payload(payloadFromStringWithContentType("{\"attachment\":{\"id\":\"jclouds-live-test\"}}", MediaType.APPLICATION_JSON)) .method("PUT").build(), standardResponseBuilder(200).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - assertTrue(client.plugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", "jclouds-live-test")); + assertTrue(client.plugAttachment("77777", "jclouds-live-test")); } @Test(expectedExceptions = AuthorizationException.class) @@ -218,18 +218,18 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { .payload(payloadFromStringWithContentType("{\"attachment\":{\"id\":\"jclouds-live-test\"}}", MediaType.APPLICATION_JSON)) .method("PUT").build(), standardResponseBuilder(403).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - client.plugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777", "jclouds-live-test"); + client.plugAttachment("77777", "jclouds-live-test"); } public void testUnplugAttachment() { PortClient client = requestsSendResponses( keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").method("DELETE").build(), standardResponseBuilder(200).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - assertTrue(client.unplugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777")); + assertTrue(client.unplugAttachment("77777")); } @Test(expectedExceptions = ResourceNotFoundException.class) @@ -238,9 +238,9 @@ public class PortClientExpectTest extends BaseQuantumClientExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, standardRequestBuilder(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").method("DELETE").build(), standardResponseBuilder(404).build()) - .getPortClientForRegion("region-a.geo-1"); + .getPortClientForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); - client.unplugAttachment("16dba3bc-f3fa-4775-afdc-237e12c72f6a", "77777"); + client.unplugAttachment("77777"); } } diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java index 75f02de0dc..dfab804255 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortClientLiveTest.java @@ -46,11 +46,11 @@ public class PortClientLiveTest extends BaseQuantumClientLiveTest { public void testListPorts() { for (String regionId : quantumContext.getApi().getConfiguredRegions()) { NetworkClient netClient = quantumContext.getApi().getNetworkClientForRegion(regionId); - PortClient portClient = quantumContext.getApi().getPortClientForRegion(regionId); Set nets = netClient.listReferences(); for(Reference net : nets) { - Set portRefs = portClient.listReferences(net.getId()); - Set ports = portClient.list(net.getId()); + PortClient portClient = quantumContext.getApi().getPortClientForRegionAndNetwork(regionId, net.getId()); + Set portRefs = portClient.listReferences(); + Set ports = portClient.list(); assertEquals(portRefs.size(), ports.size()); for (Port port : ports) { @@ -63,16 +63,16 @@ public class PortClientLiveTest extends BaseQuantumClientLiveTest { public void testCreateUpdateAndDeletePort() { for (String regionId : quantumContext.getApi().getConfiguredRegions()) { NetworkClient netClient = quantumContext.getApi().getNetworkClientForRegion(regionId); - PortClient portClient = quantumContext.getApi().getPortClientForRegion(regionId); Reference net = netClient.create("jclouds-port-test"); assertNotNull(net); - - Reference portRef = portClient.create(net.getId()); + PortClient portClient = quantumContext.getApi().getPortClientForRegionAndNetwork(regionId, net.getId()); + + Reference portRef = portClient.create(); assertNotNull(portRef); - Port port = portClient.show(net.getId(), portRef.getId()); - PortDetails portDetails = portClient.showDetails(net.getId(), portRef.getId()); - NetworkDetails networkDetails = netClient.showDetails(net.getId()); + Port port = portClient.get(portRef.getId()); + PortDetails portDetails = portClient.getDetails(portRef.getId()); + NetworkDetails networkDetails = netClient.getDetails(net.getId()); assertEquals(port.getState(), portDetails.getState()); @@ -80,29 +80,29 @@ public class PortClientLiveTest extends BaseQuantumClientLiveTest { assertEquals(checkme.getId(), portRef.getId()); } - assertTrue(portClient.update(net.getId(), portRef.getId(), Port.State.DOWN)); + assertTrue(portClient.updateState(portRef.getId(), Port.State.DOWN)); - port = portClient.show(net.getId(), portRef.getId()); - portDetails = portClient.showDetails(net.getId(), portRef.getId()); + port = portClient.get(portRef.getId()); + portDetails = portClient.getDetails(portRef.getId()); for(Port checkme : ImmutableList.of(port, portDetails)) { assertEquals(checkme.getId(), portRef.getId()); assertEquals(checkme.getState(), Port.State.DOWN); } - assertTrue(portClient.plugAttachment(net.getId(), port.getId(), "jclouds-live-test")); + assertTrue(portClient.plugAttachment(port.getId(), "jclouds-live-test")); - Attachment attachment = portClient.showAttachment(net.getId(), port.getId()); - portDetails = portClient.showDetails(net.getId(), portRef.getId()); + Attachment attachment = portClient.showAttachment(port.getId()); + portDetails = portClient.getDetails(portRef.getId()); for(Attachment checkme : ImmutableList.of(attachment, portDetails.getAttachment())) { assertNotNull(checkme); assertEquals(checkme.getId(), "jclouds-live-test"); } - assertTrue(portClient.unplugAttachment(net.getId(), port.getId())); + assertTrue(portClient.unplugAttachment(port.getId())); - assertTrue(portClient.delete(net.getId(), portRef.getId())); + assertTrue(portClient.delete(portRef.getId())); assertTrue(netClient.delete(net.getId())); } } @@ -111,26 +111,27 @@ public class PortClientLiveTest extends BaseQuantumClientLiveTest { public void testAttachAndDetachPort() { for (String regionId : quantumContext.getApi().getConfiguredRegions()) { NetworkClient netClient = quantumContext.getApi().getNetworkClientForRegion(regionId); - PortClient portClient = quantumContext.getApi().getPortClientForRegion(regionId); Reference net = netClient.create("jclouds-attach-test"); assertNotNull(net); - Reference port = portClient.create(net.getId()); + PortClient portClient = quantumContext.getApi().getPortClientForRegionAndNetwork(regionId, net.getId()); + + Reference port = portClient.create(); assertNotNull(port); - assertTrue(portClient.plugAttachment(net.getId(), port.getId(), "jclouds-live-test")); + assertTrue(portClient.plugAttachment(port.getId(), "jclouds-live-test")); - Attachment attachment = portClient.showAttachment(net.getId(), port.getId()); - PortDetails portDetails = portClient.showDetails(net.getId(), port.getId()); + Attachment attachment = portClient.showAttachment(port.getId()); + PortDetails portDetails = portClient.getDetails(port.getId()); for(Attachment checkme : ImmutableList.of(attachment, portDetails.getAttachment())) { assertNotNull(checkme); assertEquals(checkme.getId(), "jclouds-live-test"); } - assertTrue(portClient.unplugAttachment(net.getId(), port.getId())); + assertTrue(portClient.unplugAttachment(port.getId())); - assertTrue(portClient.delete(net.getId(), port.getId())); + assertTrue(portClient.delete(port.getId())); assertTrue(netClient.delete(net.getId())); } } From e5127ffd9a8c0821788e59b79fcb48f44519596f Mon Sep 17 00:00:00 2001 From: Adam Lowe Date: Fri, 1 Jun 2012 23:35:46 +0100 Subject: [PATCH 21/73] openstack-quantum: addressing review comments --- .../openstack/quantum/v1_0/features/NetworkClient.java | 6 +++--- .../openstack/quantum/v1_0/features/PortClient.java | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java index 7ea23268a0..70c93a136f 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkClient.java @@ -67,15 +67,15 @@ public interface NetworkClient { Reference create(String name); /** - * Updates the symbolic name of a network + * Adjusts the symbolic name of a network * * @param id the id of the Network to modify * @param name the new name for the Network */ - Boolean rename(String id, String name); + boolean rename(String id, String name); /** * Deletes the specified network */ - Boolean delete(String id); + boolean delete(String id); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java index 155e19f2f4..9666da697c 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortClient.java @@ -74,12 +74,12 @@ public interface PortClient { /** * Updates the state of a port */ - Boolean updateState(String id, Port.State state); + boolean updateState(String id, Port.State state); /** * Deletes a port from a network */ - Boolean delete(String id); + boolean delete(String id); /** * Returns the attachment for the specified port. @@ -89,10 +89,10 @@ public interface PortClient { /** * Plugs an attachment into the specified port */ - Boolean plugAttachment(String portId, String attachmentId); + boolean plugAttachment(String portId, String attachmentId); /** * Unplugs the attachment currently plugged into the specified port */ - Boolean unplugAttachment(String portId); + boolean unplugAttachment(String portId); } From 160cd273e271edbdd34d237cd279311a1201a2e2 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Fri, 1 Jun 2012 12:58:05 -0700 Subject: [PATCH 22/73] group name in test was too long, making dns exceptions --- .../internal/BaseComputeServiceLiveTest.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java index e24ff2cf35..3fc40b22f8 100644 --- a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java @@ -419,30 +419,31 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte @Test(enabled = true, dependsOnMethods = "testCompareSizes") public void testConcurrentUseOfComputeServiceToCreateNodes() throws Exception { - final long timeoutMs = 20*60*1000; + final long timeoutMs = 20 * 60 * 1000; List groups = new ArrayList(); List> futures = new ArrayList>(); ListeningExecutorService executor = MoreExecutors.listeningDecorator(context.utils().userExecutor()); - + try { for (int i = 0; i < 2; i++) { final int groupNum = i; - final String group = "groupconcurrent"+groupNum; + final String group = "twin" + groupNum; groups.add(group); - + ListenableFuture future = executor.submit(new Callable() { public NodeMetadata call() throws Exception { - NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, - inboundPorts(22, 8080).blockOnPort(22, 300+groupNum))); - getAnonymousLogger().info("Started node "+node.getId()); + NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, inboundPorts(22, 8080) + .blockOnPort(22, 300 + groupNum))); + getAnonymousLogger().info("Started node " + node.getId()); return node; - }}); + } + }); futures.add(future); } - + ListenableFuture> compoundFuture = Futures.allAsList(futures); compoundFuture.get(timeoutMs, TimeUnit.MILLISECONDS); - + } finally { for (String group : groups) { client.destroyNodesMatching(inGroup(group)); From f122aeadd8b4a71d24211d136a7d43a2c1b48e30 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Fri, 1 Jun 2012 12:58:44 -0700 Subject: [PATCH 23/73] fixed cloudservers expectations --- .../compute/CloudServersUSTemplateBuilderLiveTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/providers/cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersUSTemplateBuilderLiveTest.java b/providers/cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersUSTemplateBuilderLiveTest.java index 2604748a71..76e471b044 100644 --- a/providers/cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersUSTemplateBuilderLiveTest.java +++ b/providers/cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersUSTemplateBuilderLiveTest.java @@ -52,12 +52,12 @@ public class CloudServersUSTemplateBuilderLiveTest extends BaseTemplateBuilderLi public boolean apply(OsFamilyVersion64Bit input) { switch (input.family) { case UBUNTU: - return (input.version.equals("") || input.version.equals("10.04") || input.version.startsWith("11")) + return (input.version.equals("") || input.version.matches("1[012].04") || input.version.startsWith("11")) && input.is64Bit; case DEBIAN: return input.is64Bit && !input.version.equals("5.0"); case CENTOS: - return (input.version.equals("") || input.version.equals("5.6") || input.version.equals("6.0")) + return (input.version.equals("") || input.version.matches("5.[60]") || input.version.equals("6.0")) && input.is64Bit; case WINDOWS: return input.version.equals("2008 SP2") || input.version.equals("") @@ -74,7 +74,7 @@ public class CloudServersUSTemplateBuilderLiveTest extends BaseTemplateBuilderLi public void testTemplateBuilder() { Template defaultTemplate = this.view.getComputeService().templateBuilder().build(); assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); - assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "11.10"); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "12.04"); assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(defaultTemplate.getLocation().getId(), provider); assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); From 6141cdfca51ce11b9d122eaca2c14d03195baba1 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Fri, 1 Jun 2012 12:59:01 -0700 Subject: [PATCH 24/73] added missing ssh config for terremark tests --- .../jclouds/trmk/vcloud_0_8/TerremarkClientLiveTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/TerremarkClientLiveTest.java b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/TerremarkClientLiveTest.java index 8cd5467115..c1b460f8d0 100644 --- a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/TerremarkClientLiveTest.java +++ b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/TerremarkClientLiveTest.java @@ -49,6 +49,7 @@ import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.RestContext; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient.Factory; +import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.ssh.SshException; import org.jclouds.trmk.vcloud_0_8.domain.Catalog; import org.jclouds.trmk.vcloud_0_8.domain.CatalogItem; @@ -81,6 +82,7 @@ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.net.HostAndPort; import com.google.inject.Injector; +import com.google.inject.Module; @Test(groups = "live", singleThreaded = true) public abstract class TerremarkClientLiveTest extends BaseComputeServiceContextLiveTest { @@ -804,4 +806,10 @@ public abstract class TerremarkClientLiveTest Date: Fri, 1 Jun 2012 15:07:19 -0700 Subject: [PATCH 25/73] fixed auth test --- .../compute/internal/BaseComputeServiceLiveTest.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java index 3fc40b22f8..3212e32ec6 100644 --- a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java @@ -53,6 +53,7 @@ import java.util.Collection; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.Map.Entry; @@ -170,15 +171,16 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte client = view.getComputeService(); } - // wait up to 5 seconds for an auth exception @Test(enabled = true, expectedExceptions = AuthorizationException.class) public void testCorrectAuthException() throws Exception { ComputeServiceContext context = null; try { + Properties overrides = setupProperties(); + overrides.setProperty(provider + ".identity", "MOMMA"); + overrides.setProperty(provider + ".credential", "MIA"); context = newBuilder() - .credentials("MOMMA", "MIA") .modules(ImmutableSet.of(getLoggingModule(), credentialStoreModule)) - .overrides(setupProperties()).build(ComputeServiceContext.class); + .overrides(overrides).build(ComputeServiceContext.class); context.getComputeService().listNodes(); } catch (AuthorizationException e) { throw e; From b0014ec70b2c3ab2a616280748240aa3f7700638 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Fri, 1 Jun 2012 19:24:23 -0700 Subject: [PATCH 26/73] Issue 950:cloudstack Template.status is an opaque string --- .../jclouds/cloudstack/domain/Template.java | 69 +++++++++++++++++-- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java index 27c33c1220..2a455212da 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java @@ -31,6 +31,63 @@ import com.google.gson.annotations.SerializedName; * @author Adrian Cole */ public class Template implements Comparable