http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/handlers/OAuthTokenBinder.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/handlers/OAuthTokenBinder.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/handlers/OAuthTokenBinder.java deleted file mode 100644 index 1030804..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/handlers/OAuthTokenBinder.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.oauth.v2.handlers; - -import org.jclouds.http.HttpRequest; -import org.jclouds.oauth.v2.domain.TokenRequest; -import org.jclouds.oauth.v2.domain.TokenRequestFormat; -import org.jclouds.rest.Binder; - -import javax.inject.Inject; -import javax.inject.Singleton; - -/** - * Generic implementation of a token binder. Uses a provided {@link TokenRequestFormat} to actually bind tokens to - * requests. - */ -@Singleton -public class OAuthTokenBinder implements Binder { - - private final TokenRequestFormat tokenRequestFormat; - - @Inject - OAuthTokenBinder(TokenRequestFormat tokenRequestFormat) { - this.tokenRequestFormat = tokenRequestFormat; - } - - @Override - public <R extends HttpRequest> R bindToRequest(R request, Object input) { - return tokenRequestFormat.formatRequest(request, (TokenRequest) input); - } -}
http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/ClaimSetTypeAdapter.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/ClaimSetTypeAdapter.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/ClaimSetTypeAdapter.java deleted file mode 100644 index 62b3a26..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/ClaimSetTypeAdapter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.oauth.v2.json; - -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import org.jclouds.oauth.v2.domain.ClaimSet; - -import java.io.IOException; -import java.util.Map; - -/** - * JSON TypeAdapter for the ClaimSet type. Pull the claims maps to the root level and adds two properties for the - * expiration time and issuing time. - */ -public class ClaimSetTypeAdapter extends TypeAdapter<ClaimSet> { - - @Override - public void write(JsonWriter out, ClaimSet value) throws IOException { - out.beginObject(); - for (Map.Entry<String, String> entry : value.entrySet()) { - out.name(entry.getKey()); - out.value(entry.getValue()); - } - out.name("exp"); - out.value(value.getExpirationTime()); - out.name("iat"); - out.value(value.getEmissionTime()); - out.endObject(); - } - - @Override - public ClaimSet read(JsonReader in) throws IOException { - ClaimSet.Builder builder = new ClaimSet.Builder(); - in.beginObject(); - while (in.hasNext()) { - String claimName = in.nextName(); - String claimValue = in.nextString(); - builder.addClaim(claimName, claimValue); - } - in.endObject(); - return builder.build(); - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/HeaderTypeAdapter.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/HeaderTypeAdapter.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/HeaderTypeAdapter.java deleted file mode 100644 index f911a54..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/HeaderTypeAdapter.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.oauth.v2.json; - -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import org.jclouds.oauth.v2.domain.Header; - -import java.io.IOException; - -/** - * JSON TypeAdapter for the Header type. Simply transforms the field names. - */ -public class HeaderTypeAdapter extends TypeAdapter<Header> { - - @Override - public void write(JsonWriter out, Header value) throws IOException { - out.beginObject(); - out.name("alg"); - out.value(value.getSignerAlgorithm()); - out.name("typ"); - out.value(value.getType()); - out.endObject(); - } - - @Override - public Header read(JsonReader in) throws IOException { - Header.Builder builder = new Header.Builder(); - in.beginObject(); - in.nextName(); - builder.signerAlgorithm(in.nextString()); - in.nextName(); - builder.type(in.nextString()); - in.endObject(); - return builder.build(); - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/JWTTokenRequestFormat.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/JWTTokenRequestFormat.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/JWTTokenRequestFormat.java deleted file mode 100644 index 265cb26..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/java/org/jclouds/oauth/v2/json/JWTTokenRequestFormat.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.oauth.v2.json; - -import static com.google.common.base.Charsets.UTF_8; -import static com.google.common.base.Joiner.on; -import static com.google.common.io.BaseEncoding.base64Url; -import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; - -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.http.HttpRequest; -import org.jclouds.io.Payload; -import org.jclouds.json.Json; -import org.jclouds.oauth.v2.domain.TokenRequest; -import org.jclouds.oauth.v2.domain.TokenRequestFormat; - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableSet; - -/** - * Formats a token request into JWT format namely: - * - transforms the token request to json - * - creates the base64 header.claimset portions of the payload. - * - uses the provided signer function to create a signature - * - creates the full url encoded payload as described in: - * https://developers.google.com/accounts/docs/OAuth2ServiceAccount - * <p/> - */ -@Singleton -public class JWTTokenRequestFormat implements TokenRequestFormat { - - private static final String ASSERTION_FORM_PARAM = "assertion"; - private static final String GRANT_TYPE_FORM_PARAM = "grant_type"; - private static final String GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer"; - - private final Function<byte[], byte[]> signer; - private final Json json; - - @Inject - public JWTTokenRequestFormat(Function<byte[], byte[]> signer, Json json) { - this.signer = signer; - this.json = json; - } - - @SuppressWarnings("unchecked") - @Override - public <R extends HttpRequest> R formatRequest(R request, TokenRequest tokenRequest) { - - String encodedHeader = json.toJson(tokenRequest.getHeader()); - String encodedClaimSet = json.toJson(tokenRequest.getClaimSet()); - - encodedHeader = base64Url().omitPadding().encode(encodedHeader.getBytes(UTF_8)); - encodedClaimSet = base64Url().omitPadding().encode(encodedClaimSet.getBytes(UTF_8)); - - byte[] signature = signer.apply(on(".").join(encodedHeader, encodedClaimSet).getBytes(UTF_8)); - String encodedSignature = signature != null ? base64Url().omitPadding().encode(signature) : ""; - - // the final assertion in base 64 encoded {header}.{claimSet}.{signature} format - String assertion = on(".").join(encodedHeader, encodedClaimSet, encodedSignature); - Payload payload = newUrlEncodedFormPayload(ImmutableMultimap.<String, String> builder() - .put(GRANT_TYPE_FORM_PARAM, GRANT_TYPE_JWT_BEARER) - .put(ASSERTION_FORM_PARAM, assertion).build()); - - return (R) request.toBuilder().payload(payload).build(); - } - - @Override - public String getTypeName() { - return "JWT"; - } - - @Override - public Set<String> requiredClaims() { - // exp and ist (expiration and emission times) are assumed mandatory already - return ImmutableSet.of("iss", "scope", "aud"); - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata deleted file mode 100644 index ab2c67d..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata +++ /dev/null @@ -1,19 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF 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. -# - -org.jclouds.googlecomputeengine.GoogleComputeEngineApiMetadata -org.jclouds.oauth.v2.OAuthApiMetadata http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineApiMetadataTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineApiMetadataTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineApiMetadataTest.java deleted file mode 100644 index 5cb8a99..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineApiMetadataTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine; - -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; - -/** - * Tests that GoogleComputeApiMetadata is properly registered in ServiceLoader - * <p/> - * <pre> - * META-INF/services/org.jclouds.apis.ApiMetadata - * </pre> - */ -@Test(groups = "unit", testName = "GoogleComputeApiMetadataTest") -public class GoogleComputeEngineApiMetadataTest extends BaseApiMetadataTest { - public GoogleComputeEngineApiMetadataTest() { - super(new GoogleComputeEngineApiMetadata(), ImmutableSet.<TypeToken<? extends View>>of()); - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineAuthenticatedRestContextLiveTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineAuthenticatedRestContextLiveTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineAuthenticatedRestContextLiveTest.java deleted file mode 100644 index 8961bb5..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineAuthenticatedRestContextLiveTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine; - -import org.jclouds.oauth.v2.internal.BaseOAuthAuthenticatedApiLiveTest; -import org.testng.annotations.Test; - -@Test(groups = "live") -public class GoogleComputeEngineAuthenticatedRestContextLiveTest extends BaseOAuthAuthenticatedApiLiveTest<GoogleComputeEngineApi> { - - public GoogleComputeEngineAuthenticatedRestContextLiveTest() { - provider = "google-compute-engine"; - } - - @Override - public String getScopes() { - return GoogleComputeEngineConstants.COMPUTE_SCOPE; - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/PageSystemExpectTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/PageSystemExpectTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/PageSystemExpectTest.java deleted file mode 100644 index 8fa44b9..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/PageSystemExpectTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine; - -import static org.jclouds.googlecomputeengine.GoogleComputeEngineConstants.COMPUTE_READONLY_SCOPE; -import static org.testng.Assert.assertSame; - -import org.jclouds.collect.IterableWithMarker; -import org.jclouds.collect.PagedIterable; -import org.jclouds.googlecomputeengine.domain.Image; -import org.jclouds.googlecomputeengine.features.ImageApi; -import org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiExpectTest; -import org.jclouds.googlecomputeengine.options.ListOptions; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpResponse; -import org.testng.annotations.Test; - -/** - * A test specifically for the paging system. The code used is common to all list() methods so we're using Images - * but it could be anything else. - */ -@Test(groups = "unit") -public class PageSystemExpectTest extends BaseGoogleComputeEngineApiExpectTest { - - public void testGetSinglePage() { - HttpRequest list = HttpRequest - .builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/images") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpResponse operationResponse = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/image_list_single_page.json")).build(); - - ImageApi imageApi = requestsSendResponses(requestForScopes(COMPUTE_READONLY_SCOPE), - TOKEN_RESPONSE, list, operationResponse).getImageApiForProject("myproject"); - - PagedIterable<Image> images = imageApi.list(); - - // expect one page - assertSame(images.size(), 1); - // with three images - assertSame(images.concat().size(), 3); - } - - public void testGetMultiplePages() { - HttpRequest list1 = HttpRequest - .builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/images?maxResults=3") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpRequest list2 = HttpRequest - .builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/images?pageToken" + - "=CgVJTUFHRRIbZ29vZ2xlLmNlbnRvcy02LTItdjIwMTIwNjIx&maxResults=3") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpRequest list3 = HttpRequest - .builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/images?pageToken" + - "=CgVJTUFHRRIbZ29vZ2xlLmdjZWwtMTAtMDQtdjIwMTIxMTA2&maxResults=3") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpResponse list1response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/image_list_multiple_page_1.json")).build(); - - HttpResponse list2Response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/image_list_multiple_page_2.json")).build(); - - HttpResponse list3Response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/image_list_single_page.json")).build(); - - - ImageApi imageApi = orderedRequestsSendResponses(requestForScopes(COMPUTE_READONLY_SCOPE), - TOKEN_RESPONSE, list1, list1response, list2, list2Response, list3, list3Response) - .getImageApiForProject("myproject"); - - PagedIterable<Image> images = imageApi.list(new ListOptions.Builder().maxResults(3)); - - int imageCounter = 0; - for (IterableWithMarker<Image> page : images) { - for (Image image : page) { - imageCounter++; - } - } - assertSame(imageCounter, 9); - } - -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceExpectTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceExpectTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceExpectTest.java deleted file mode 100644 index 885289f..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceExpectTest.java +++ /dev/null @@ -1,574 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine.compute; - -import static com.google.common.collect.Iterables.getOnlyElement; -import static org.jclouds.googlecomputeengine.GoogleComputeEngineConstants.COMPUTE_READONLY_SCOPE; -import static org.jclouds.googlecomputeengine.GoogleComputeEngineConstants.COMPUTE_SCOPE; -import static org.jclouds.googlecomputeengine.GoogleComputeEngineConstants.GCE_BOOT_DISK_SUFFIX; -import static org.jclouds.googlecomputeengine.features.GlobalOperationApiExpectTest.GET_GLOBAL_OPERATION_REQUEST; -import static org.jclouds.googlecomputeengine.features.GlobalOperationApiExpectTest.GET_GLOBAL_OPERATION_RESPONSE; -import static org.jclouds.googlecomputeengine.features.ImageApiExpectTest.LIST_DEBIAN_IMAGES_REQUEST; -import static org.jclouds.googlecomputeengine.features.ImageApiExpectTest.LIST_DEBIAN_IMAGES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.ImageApiExpectTest.LIST_CENTOS_IMAGES_REQUEST; -import static org.jclouds.googlecomputeengine.features.ImageApiExpectTest.LIST_CENTOS_IMAGES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.ImageApiExpectTest.LIST_PROJECT_IMAGES_REQUEST; -import static org.jclouds.googlecomputeengine.features.ImageApiExpectTest.LIST_PROJECT_IMAGES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.InstanceApiExpectTest.LIST_CENTRAL1B_INSTANCES_REQUEST; -import static org.jclouds.googlecomputeengine.features.InstanceApiExpectTest.LIST_CENTRAL1B_INSTANCES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.InstanceApiExpectTest.LIST_INSTANCES_REQUEST; -import static org.jclouds.googlecomputeengine.features.InstanceApiExpectTest.LIST_INSTANCES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.MachineTypeApiExpectTest.LIST_CENTRAL1B_MACHINE_TYPES_REQUEST; -import static org.jclouds.googlecomputeengine.features.MachineTypeApiExpectTest.LIST_CENTRAL1B_MACHINE_TYPES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.MachineTypeApiExpectTest.LIST_MACHINE_TYPES_REQUEST; -import static org.jclouds.googlecomputeengine.features.MachineTypeApiExpectTest.LIST_MACHINE_TYPES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.NetworkApiExpectTest.GET_NETWORK_REQUEST; -import static org.jclouds.googlecomputeengine.features.ProjectApiExpectTest.GET_PROJECT_REQUEST; -import static org.jclouds.googlecomputeengine.features.ProjectApiExpectTest.GET_PROJECT_RESPONSE; -import static org.jclouds.googlecomputeengine.features.ZoneApiExpectTest.LIST_ZONES_REQ; -import static org.jclouds.googlecomputeengine.features.ZoneApiExpectTest.LIST_ZONES_RESPONSE; -import static org.jclouds.googlecomputeengine.features.ZoneApiExpectTest.LIST_ZONES_SHORT_RESPONSE; -import static org.jclouds.googlecomputeengine.features.ZoneOperationApiExpectTest.GET_ZONE_OPERATION_REQUEST; -import static org.jclouds.googlecomputeengine.features.ZoneOperationApiExpectTest.GET_ZONE_OPERATION_RESPONSE; -import static org.jclouds.util.Strings2.toStringAndClose; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import javax.ws.rs.core.MediaType; - -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.RunNodesException; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.Template; -import org.jclouds.domain.Location; -import org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions; -import org.jclouds.googlecomputeengine.domain.Instance; -import org.jclouds.googlecomputeengine.features.InstanceApiExpectTest; -import org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineServiceExpectTest; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpResponse; -import org.jclouds.util.Strings2; -import org.testng.annotations.Test; - -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - - -@Test(groups = "unit") -public class GoogleComputeEngineServiceExpectTest extends BaseGoogleComputeEngineServiceExpectTest { - - - private HttpRequest INSERT_NETWORK_REQUEST = HttpRequest - .builder() - .method("POST") - .endpoint("https://www.googleapis.com/compute/v1/projects/myproject/global/networks") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN) - .payload(payloadFromStringWithContentType("{\"name\":\"jclouds-test\",\"IPv4Range\":\"10.0.0.0/8\"}", - MediaType.APPLICATION_JSON)) - .build(); - - private HttpRequest INSERT_FIREWALL_REQUEST = HttpRequest - .builder() - .method("POST") - .endpoint("https://www.googleapis.com/compute/v1/projects/myproject/global/firewalls") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN) - .payload(payloadFromStringWithContentType("{\"name\":\"jclouds-test\",\"network\":\"https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/networks/jclouds-test\"," + - "\"sourceRanges\":[\"10.0.0.0/8\",\"0.0.0.0/0\"],\"sourceTags\":[\"aTag\"],\"allowed\":[{\"IPProtocol\":\"tcp\"," + - "\"ports\":[\"22\"]}," + - "{\"IPProtocol\":\"udp\",\"ports\":[\"22\"]}]}", - MediaType.APPLICATION_JSON)) - .build(); - - private HttpResponse GET_NETWORK_RESPONSE = HttpResponse.builder().statusCode(200) - .payload(payloadFromStringWithContentType("{\n" + - " \"kind\": \"compute#network\",\n" + - " \"id\": \"13024414170909937976\",\n" + - " \"creationTimestamp\": \"2012-10-24T20:13:19.967\",\n" + - " \"selfLink\": \"https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/networks/jclouds-test\",\n" + - " \"name\": \"jclouds-test\",\n" + - " \"description\": \"test network\",\n" + - " \"IPv4Range\": \"10.0.0.0/8\",\n" + - " \"gatewayIPv4\": \"10.0.0.1\"\n" + - "}", MediaType.APPLICATION_JSON)).build(); - - private HttpResponse SUCESSFULL_OPERATION_RESPONSE = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/operation.json")).build(); - - private HttpRequest SET_TAGS_REQUEST = HttpRequest.builder() - .method("POST") - .endpoint("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances/test-1/setTags") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN) - .payload(payloadFromStringWithContentType("{\"items\":[\"aTag\"],\"fingerprint\":\"abcd\"}", - MediaType.APPLICATION_JSON)) - .build(); - - private HttpResponse SET_TAGS_RESPONSE = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/operation.json")).build(); - - private HttpResponse getInstanceResponseForInstanceAndNetworkAndStatus(String instanceName, String networkName, - String status) throws - IOException { - return HttpResponse.builder().statusCode(200) - .payload(payloadFromStringWithContentType( - replaceInstanceNameNetworkAndStatusOnResource("/instance_get.json", - instanceName, networkName, status), - "application/json")).build(); - } - - private HttpResponse getListInstancesResponseForSingleInstanceAndNetworkAndStatus(String instanceName, - String networkName, - String status) { - return HttpResponse.builder().statusCode(200) - .payload(payloadFromStringWithContentType( - replaceInstanceNameNetworkAndStatusOnResource("/instance_list.json", - instanceName, networkName, status), - "application/json")).build(); - } - - private HttpResponse getDiskResponseForInstance(String instanceName) { - return HttpResponse.builder().statusCode(200) - .payload(payloadFromStringWithContentType( - replaceDiskNameOnResource("/disk_get.json", instanceName + "-" + GCE_BOOT_DISK_SUFFIX), - "application/json")).build(); - } - - private String replaceDiskNameOnResource(String resourceName, String diskName) { - try { - return Strings2.toStringAndClose(this.getClass().getResourceAsStream(resourceName)) - .replace("testimage1", diskName); - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - - private String replaceInstanceNameNetworkAndStatusOnResource(String resourceName, String instanceName, - String networkName, String status) { - try { - return Strings2.toStringAndClose(this.getClass().getResourceAsStream(resourceName)).replace("test-0", - instanceName).replace("default", networkName).replace("RUNNING", status); - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - - private HttpRequest createDiskRequestForInstance(String instanceName) { - return HttpRequest - .builder() - .method("POST") - .endpoint("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/disks" - + "?sourceImage=https%3A//www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN) - .payload(payloadFromStringWithContentType("{\"name\":\"" + instanceName + "-" + GCE_BOOT_DISK_SUFFIX + "\"," - + "\"sizeGb\":10}", - MediaType.APPLICATION_JSON)).build(); - } - - private HttpRequest getDiskRequestForInstance(String instanceName) { - return HttpRequest - .builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/zones/us-central1-a/disks/" - + instanceName + "-" + GCE_BOOT_DISK_SUFFIX) - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - } - - - - private HttpRequest createInstanceRequestForInstance(String instanceName, String groupName, - String networkName, String publicKey) { - return HttpRequest - .builder() - .method("POST") - .endpoint("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN) - .payload(payloadFromStringWithContentType("{\"name\":\"" + instanceName + "\"," + - "\"machineType\":\"https://www.googleapis" + - ".com/compute/v1/projects/myproject/zones/us-central1-a/machineTypes/f1-micro\"," + - "\"serviceAccounts\":[]," + - "\"networkInterfaces\":[{\"network\":\"https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/networks/" + networkName + "\"," + - "\"accessConfigs\":[{\"type\":\"ONE_TO_ONE_NAT\"}]}]," + - "\"disks\":[{\"mode\":\"READ_WRITE\",\"source\":\"https://www.googleapis.com/" + - "compute/v1/projects/myproject/zones/us-central1-a/disks/" + instanceName + - "-" + GCE_BOOT_DISK_SUFFIX + "\",\"deleteOnTerminate\":true,\"boot\":true,\"type\":\"PERSISTENT\"}]," + - "\"metadata\":{\"kind\":\"compute#metadata\",\"items\":[{\"key\":\"sshKeys\"," + - "\"value\":\"jclouds:" + - publicKey + " jclouds@localhost\"},{\"key\":\"jclouds-group\"," + - "\"value\":\"" + groupName + "\"},{\"key\":\"jclouds-image\",\"value\":\"https://www.googleapis" + - ".com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\"}," + - "{\"key\":\"jclouds-delete-boot-disk\",\"value\":\"true\"}]}}", - MediaType.APPLICATION_JSON)).build(); - } - - private HttpRequest getInstanceRequestForInstance(String instanceName) { - return HttpRequest - .builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/zones/us-central1-a/instances/" + instanceName) - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - } - - - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); - overrides.put("google-compute-engine.identity", "myproject"); - try { - overrides.put("google-compute-engine.credential", toStringAndClose(getClass().getResourceAsStream("/testpk.pem"))); - } catch (IOException e) { - Throwables.propagate(e); - } - return overrides; - } - - @Test(enabled = false) - public void testThrowsAuthorizationException() throws Exception { - - Properties properties = new Properties(); - properties.setProperty("oauth.identity", "MOMMA"); - properties.setProperty("oauth.credential", "MiA"); - - ComputeService client = requestsSendResponses(ImmutableMap.<HttpRequest, HttpResponse>of(), createModule(), - properties); - Template template = client.templateBuilder().build(); - Template toMatch = client.templateBuilder().imageId(template.getImage().getId()).build(); - assertEquals(toMatch.getImage(), template.getImage()); - } - - @Test - public void testTemplateMatch() throws Exception { - ImmutableMap<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap. - <HttpRequest, HttpResponse>builder() - .put(requestForScopes(COMPUTE_READONLY_SCOPE), TOKEN_RESPONSE) - .put(GET_PROJECT_REQUEST, GET_PROJECT_RESPONSE) - .put(LIST_ZONES_REQ, LIST_ZONES_RESPONSE) - .put(LIST_PROJECT_IMAGES_REQUEST, LIST_PROJECT_IMAGES_RESPONSE) - .put(LIST_DEBIAN_IMAGES_REQUEST, LIST_DEBIAN_IMAGES_RESPONSE) - .put(LIST_CENTOS_IMAGES_REQUEST, LIST_CENTOS_IMAGES_RESPONSE) - .put(LIST_MACHINE_TYPES_REQUEST, LIST_MACHINE_TYPES_RESPONSE) - .put(LIST_CENTRAL1B_MACHINE_TYPES_REQUEST, LIST_CENTRAL1B_MACHINE_TYPES_RESPONSE) - .build(); - - ComputeService client = requestsSendResponses(requestResponseMap); - Template template = client.templateBuilder().build(); - Hardware defaultSize = client.templateBuilder().build().getHardware(); - - Hardware smallest = client.templateBuilder().smallest().build().getHardware(); - assertEquals(defaultSize, smallest); - - Hardware fastest = client.templateBuilder().fastest().build().getHardware(); - assertNotNull(fastest); - - assertEquals(client.listHardwareProfiles().size(), 5); - - Template toMatch = client.templateBuilder() - .imageId(template.getImage().getId()) - .build(); - assertEquals(toMatch.getImage(), template.getImage()); - } - - @Test - public void testNetworksAndFirewallDeletedWhenAllGroupNodesAreTerminated() throws IOException { - - HttpRequest deleteNodeRequest = HttpRequest.builder() - .method("DELETE") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/zones/us-central1-a/instances/test-delete-networks") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpRequest deleteFirewallRequest = HttpRequest.builder() - .method("DELETE") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/firewalls/jclouds-test-delete") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpRequest getNetworkRequest = HttpRequest.builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/networks/jclouds-test-delete") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpResponse getNetworkResponse = HttpResponse.builder().statusCode(200) - .payload(staticPayloadFromResource("/GoogleComputeEngineServiceExpectTest/network_get.json")).build(); - - HttpRequest listFirewallsRequest = HttpRequest.builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/firewalls") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpResponse listFirewallsResponse = HttpResponse.builder().statusCode(200) - .payload(staticPayloadFromResource("/GoogleComputeEngineServiceExpectTest/firewall_list.json")).build(); - - HttpRequest deleteNetworkReqquest = HttpRequest.builder() - .method("DELETE") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/networks/jclouds-test-delete") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpRequest deleteDiskRequest = HttpRequest.builder() - .method("DELETE") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/zones/us-central1-a/disks/test") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - List<HttpRequest> orderedRequests = ImmutableList.<HttpRequest>builder() - .add(requestForScopes(COMPUTE_READONLY_SCOPE)) - .add(GET_PROJECT_REQUEST) - .add(getInstanceRequestForInstance("test-delete-networks")) - .add(LIST_ZONES_REQ) - .add(LIST_MACHINE_TYPES_REQUEST) - .add(LIST_PROJECT_IMAGES_REQUEST) - .add(LIST_DEBIAN_IMAGES_REQUEST) - .add(LIST_CENTOS_IMAGES_REQUEST) - .add(getInstanceRequestForInstance("test-delete-networks")) - .add(requestForScopes(COMPUTE_SCOPE)) - .add(deleteNodeRequest) - .add(GET_ZONE_OPERATION_REQUEST) - .add(deleteDiskRequest) - .add(GET_ZONE_OPERATION_REQUEST) - .add(getInstanceRequestForInstance("test-delete-networks")) - .add(LIST_INSTANCES_REQUEST) - .add(getNetworkRequest) - .add(listFirewallsRequest) - .add(deleteFirewallRequest) - .add(GET_GLOBAL_OPERATION_REQUEST) - .add(deleteNetworkReqquest) - .add(GET_GLOBAL_OPERATION_REQUEST) - .build(); - - - List<HttpResponse> orderedResponses = ImmutableList.<HttpResponse>builder() - .add(TOKEN_RESPONSE) - .add(GET_PROJECT_RESPONSE) - .add(getInstanceResponseForInstanceAndNetworkAndStatus("test-delete-networks", "test-network", Instance - .Status.RUNNING.name())) - .add(LIST_ZONES_SHORT_RESPONSE) - .add(LIST_MACHINE_TYPES_RESPONSE) - .add(LIST_PROJECT_IMAGES_RESPONSE) - .add(LIST_DEBIAN_IMAGES_RESPONSE) - .add(LIST_CENTOS_IMAGES_RESPONSE) - .add(getInstanceResponseForInstanceAndNetworkAndStatus("test-delete-networks", "test-network", Instance - .Status.RUNNING.name())) - .add(TOKEN_RESPONSE) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_ZONE_OPERATION_RESPONSE) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_ZONE_OPERATION_RESPONSE) - .add(getInstanceResponseForInstanceAndNetworkAndStatus("test-delete-networks", "test-network", Instance - .Status.TERMINATED.name())) - .add(getListInstancesResponseForSingleInstanceAndNetworkAndStatus("test-delete-networks", - "test-network", Instance - .Status.TERMINATED.name())) - .add(getNetworkResponse) - .add(listFirewallsResponse) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_GLOBAL_OPERATION_RESPONSE) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_GLOBAL_OPERATION_RESPONSE) - .build(); - - ComputeService client = orderedRequestsSendResponses(orderedRequests, orderedResponses); - client.destroyNode("us-central1-a/test-delete-networks"); - - } - - public void testListLocationsWhenResponseIs2xx() throws Exception { - - ImmutableMap<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap. - <HttpRequest, HttpResponse>builder() - .put(requestForScopes(COMPUTE_READONLY_SCOPE), TOKEN_RESPONSE) - .put(GET_PROJECT_REQUEST, GET_PROJECT_RESPONSE) - .put(LIST_ZONES_REQ, LIST_ZONES_RESPONSE) - .put(LIST_INSTANCES_REQUEST, LIST_INSTANCES_RESPONSE) - .put(LIST_CENTRAL1B_INSTANCES_REQUEST, LIST_CENTRAL1B_INSTANCES_RESPONSE) - .put(LIST_PROJECT_IMAGES_REQUEST, LIST_PROJECT_IMAGES_RESPONSE) - .put(LIST_DEBIAN_IMAGES_REQUEST, LIST_DEBIAN_IMAGES_RESPONSE) - .put(LIST_CENTOS_IMAGES_REQUEST, LIST_CENTOS_IMAGES_RESPONSE) - .put(LIST_MACHINE_TYPES_REQUEST, LIST_MACHINE_TYPES_RESPONSE) - .put(LIST_CENTRAL1B_MACHINE_TYPES_REQUEST, LIST_CENTRAL1B_MACHINE_TYPES_RESPONSE) - .build(); - - ComputeService apiWhenServersExist = requestsSendResponses(requestResponseMap); - - Set<? extends Location> locations = apiWhenServersExist.listAssignableLocations(); - - assertNotNull(locations); - assertEquals(locations.size(), 2); - assertEquals(locations.iterator().next().getId(), "us-central1-a"); - - assertNotNull(apiWhenServersExist.listNodes()); - assertEquals(apiWhenServersExist.listNodes().size(), 1); - assertEquals(apiWhenServersExist.listNodes().iterator().next().getId(), "us-central1-a/test-0"); - assertEquals(apiWhenServersExist.listNodes().iterator().next().getName(), "test-0"); - } - - @Test(dependsOnMethods = "testListLocationsWhenResponseIs2xx") - public void testCreateNodeWhenNetworkNorFirewallExistDoesNotExist() throws RunNodesException, IOException { - - - String payload = Strings2.toStringAndClose(InstanceApiExpectTest.class.getResourceAsStream("/instance_get.json")); - payload = payload.replace("test-0", "test-1"); - - HttpResponse getInstanceResponse = HttpResponse.builder().statusCode(200) - .payload(payloadFromStringWithContentType(payload, "application/json")).build(); - - HttpRequest getFirewallRequest = HttpRequest - .builder() - .method("GET") - .endpoint("https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/firewalls/jclouds-test-port-22") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN).build(); - - HttpRequest insertFirewallRequest = HttpRequest - .builder() - .method("POST") - .endpoint("https://www.googleapis.com/compute/v1/projects/myproject/global/firewalls") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN) - .payload(payloadFromStringWithContentType("{\"name\":\"jclouds-test-port-22\",\"network\":\"https://www.googleapis" + - ".com/compute/v1/projects/myproject/global/networks/jclouds-test\"," + - "\"sourceRanges\":[\"10.0.0.0/8\",\"0.0.0.0/0\"],\"sourceTags\":[\"aTag\"],\"targetTags\":[\"jclouds-test-port-22\"],\"allowed\":[{\"IPProtocol\":\"tcp\"," + - "\"ports\":[\"22\"]}," + - "{\"IPProtocol\":\"udp\",\"ports\":[\"22\"]}]}", - MediaType.APPLICATION_JSON)) - .build(); - - HttpRequest setTagsRequest = HttpRequest - .builder() - .method("POST") - .endpoint("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances/test-1/setTags") - .addHeader("Accept", "application/json") - .addHeader("Authorization", "Bearer " + TOKEN) - .payload(payloadFromStringWithContentType("{\"items\":[\"jclouds-test-port-22\"],\"fingerprint\":\"abcd\"}", - MediaType.APPLICATION_JSON)) - .build(); - - List<HttpRequest> orderedRequests = ImmutableList.<HttpRequest>builder() - .add(requestForScopes(COMPUTE_READONLY_SCOPE)) - .add(GET_PROJECT_REQUEST) - .add(LIST_ZONES_REQ) - .add(LIST_PROJECT_IMAGES_REQUEST) - .add(LIST_DEBIAN_IMAGES_REQUEST) - .add(LIST_CENTOS_IMAGES_REQUEST) - .add(LIST_ZONES_REQ) - .add(LIST_MACHINE_TYPES_REQUEST) - .add(GET_NETWORK_REQUEST) - .add(GET_NETWORK_REQUEST) - .add(requestForScopes(COMPUTE_SCOPE)) - .add(INSERT_NETWORK_REQUEST) - .add(GET_GLOBAL_OPERATION_REQUEST) - .add(GET_NETWORK_REQUEST) - .add(getFirewallRequest) - .add(insertFirewallRequest) - .add(GET_GLOBAL_OPERATION_REQUEST) - .add(LIST_INSTANCES_REQUEST) - .add(LIST_MACHINE_TYPES_REQUEST) - .add(LIST_PROJECT_IMAGES_REQUEST) - .add(LIST_DEBIAN_IMAGES_REQUEST) - .add(LIST_CENTOS_IMAGES_REQUEST) - .add(createDiskRequestForInstance("test-1")) - .add(GET_ZONE_OPERATION_REQUEST) - .add(getDiskRequestForInstance("test-1")) - .add(createInstanceRequestForInstance("test-1", "test", "jclouds-test", openSshKey)) - .add(GET_ZONE_OPERATION_REQUEST) - .add(getInstanceRequestForInstance("test-1")) - .add(SET_TAGS_REQUEST) - .add(GET_ZONE_OPERATION_REQUEST) - .add(getInstanceRequestForInstance("test-1")) - .add(setTagsRequest) - .add(LIST_PROJECT_IMAGES_REQUEST) - .add(LIST_DEBIAN_IMAGES_REQUEST) - .add(LIST_CENTOS_IMAGES_REQUEST) - .add(setTagsRequest) - .build(); - - List<HttpResponse> orderedResponses = ImmutableList.<HttpResponse>builder() - .add(TOKEN_RESPONSE) - .add(GET_PROJECT_RESPONSE) - .add(LIST_ZONES_SHORT_RESPONSE) - .add(LIST_PROJECT_IMAGES_RESPONSE) - .add(LIST_DEBIAN_IMAGES_RESPONSE) - .add(LIST_CENTOS_IMAGES_RESPONSE) - .add(LIST_ZONES_SHORT_RESPONSE) - .add(LIST_MACHINE_TYPES_RESPONSE) - .add(HttpResponse.builder().statusCode(404).build()) - .add(HttpResponse.builder().statusCode(404).build()) - .add(TOKEN_RESPONSE) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_GLOBAL_OPERATION_RESPONSE) - .add(GET_NETWORK_RESPONSE) - .add(HttpResponse.builder().statusCode(404).build()) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_GLOBAL_OPERATION_RESPONSE) - .add(LIST_INSTANCES_RESPONSE) - .add(LIST_MACHINE_TYPES_RESPONSE) - .add(LIST_PROJECT_IMAGES_RESPONSE) - .add(LIST_DEBIAN_IMAGES_RESPONSE) - .add(LIST_CENTOS_IMAGES_RESPONSE) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_ZONE_OPERATION_RESPONSE) - .add(getDiskResponseForInstance("test-1")) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(GET_ZONE_OPERATION_RESPONSE) - .add(getInstanceResponse) - .add(SET_TAGS_RESPONSE) - .add(GET_ZONE_OPERATION_RESPONSE) - .add(getInstanceResponse) - .add(SUCESSFULL_OPERATION_RESPONSE) - .add(LIST_PROJECT_IMAGES_RESPONSE) - .add(LIST_DEBIAN_IMAGES_RESPONSE) - .add(LIST_CENTOS_IMAGES_RESPONSE) - .add(SUCESSFULL_OPERATION_RESPONSE) - .build(); - - - ComputeService computeService = orderedRequestsSendResponses(orderedRequests, orderedResponses); - - GoogleComputeEngineTemplateOptions options = computeService.templateOptions().as(GoogleComputeEngineTemplateOptions.class); - options.tags(ImmutableSet.of("aTag")); - NodeMetadata node = getOnlyElement(computeService.createNodesInGroup("test", 1, options)); - assertEquals(node.getImageId(), "debian-7-wheezy-v20140718"); - } -} - http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceLiveTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceLiveTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceLiveTest.java deleted file mode 100644 index 2011d2d..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceLiveTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine.compute; - -import static com.google.common.collect.Iterables.contains; -import static org.jclouds.oauth.v2.OAuthTestUtils.setCredential; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import java.util.Properties; -import java.util.Set; - -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.internal.BaseComputeServiceLiveTest; -import org.jclouds.googlecomputeengine.GoogleComputeEngineApi; -import org.jclouds.googlecomputeengine.config.UserProject; -import org.jclouds.googlecomputeengine.domain.MachineType; -import org.jclouds.oauth.v2.config.CredentialType; -import org.jclouds.oauth.v2.config.OAuthProperties; -import org.jclouds.sshj.config.SshjSshClientModule; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Key; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; - -@Test(groups = "live", singleThreaded = true) -public class GoogleComputeEngineServiceLiveTest extends BaseComputeServiceLiveTest { - - protected static final String DEFAULT_ZONE_NAME = "us-central1-a"; - - public GoogleComputeEngineServiceLiveTest() { - provider = "google-compute-engine"; - } - - @Override - protected Properties setupProperties() { - Properties props = super.setupProperties(); - if (!System.getProperty(OAuthProperties.CREDENTIAL_TYPE, "") - .equalsIgnoreCase(CredentialType.BEARER_TOKEN_CREDENTIALS.toString())) { - setCredential(props, provider + ".credential"); - } - return props; - } - - public void testListHardwareProfiles() throws Exception { - GoogleComputeEngineApi api = client.getContext().unwrapApi(GoogleComputeEngineApi.class); - Supplier<String> userProject = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<String>>() { - }, UserProject.class)); - ImmutableSet.Builder<String> deprecatedMachineTypes = ImmutableSet.builder(); - for (MachineType machine : api.getMachineTypeApiForProject(userProject.get()) - .listInZone(DEFAULT_ZONE_NAME).concat()) { - if (machine.getDeprecated().isPresent()) { - deprecatedMachineTypes.add(machine.getId()); - } - } - ImmutableSet<String> deprecatedMachineTypeIds = deprecatedMachineTypes.build(); - Set<? extends Hardware> hardwareProfiles = client.listHardwareProfiles(); - System.out.println(hardwareProfiles.size()); - for (Hardware hardwareProfile : hardwareProfiles) { - System.out.println(hardwareProfile); - assertFalse(contains(deprecatedMachineTypeIds, hardwareProfile.getId())); - } - } - - /** - * Nodes may have additional metadata entries (particularly they may have an "sshKeys" entry) - */ - protected void checkUserMetadataInNodeEquals(NodeMetadata node, ImmutableMap<String, String> userMetadata) { - assertTrue(node.getUserMetadata().keySet().containsAll(userMetadata.keySet())); - } - - // do not run until the auth exception problem is figured out. - @Test(enabled = false) - @Override - public void testCorrectAuthException() throws Exception { - } - - // reboot is not supported by GCE - @Test(enabled = true, dependsOnMethods = "testGet") - public void testReboot() throws Exception { - } - - // suspend/Resume is not supported by GCE - @Test(enabled = true, dependsOnMethods = "testReboot") - public void testSuspendResume() throws Exception { - } - - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - public void testListNodesByIds() throws Exception { - super.testGetNodesWithDetails(); - } - - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - @Override - public void testGetNodesWithDetails() throws Exception { - super.testGetNodesWithDetails(); - } - - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - @Override - public void testListNodes() throws Exception { - super.testListNodes(); - } - - @Test(enabled = true, dependsOnMethods = {"testListNodes", "testGetNodesWithDetails", "testListNodesByIds"}) - @Override - public void testDestroyNodes() { - super.testDestroyNodes(); - } - - @Override - protected Module getSshModule() { - return new SshjSshClientModule(); - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/extensions/GoogleComputeEngineSecurityGroupExtensionLiveTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/extensions/GoogleComputeEngineSecurityGroupExtensionLiveTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/extensions/GoogleComputeEngineSecurityGroupExtensionLiveTest.java deleted file mode 100644 index 588ef51..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/extensions/GoogleComputeEngineSecurityGroupExtensionLiveTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine.compute.extensions; - -import org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest; -import org.testng.annotations.Test; - -@Test(groups = "live", singleThreaded = true, testName = "GoogleComputeEngineSecurityGroupExtensionLiveTest") -public class GoogleComputeEngineSecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest { - - public GoogleComputeEngineSecurityGroupExtensionLiveTest() { - provider = "google-compute-engine"; - } -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/FirewallToIpPermissionTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/FirewallToIpPermissionTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/FirewallToIpPermissionTest.java deleted file mode 100644 index 62f9260..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/FirewallToIpPermissionTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine.compute.functions; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.net.URI; -import java.util.Date; - -import org.jclouds.googlecomputeengine.domain.Firewall; -import org.jclouds.net.domain.IpPermission; -import org.jclouds.net.domain.IpProtocol; -import org.testng.annotations.Test; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; - -public class FirewallToIpPermissionTest { - - @Test - public void testApply() { - - Firewall fw = fwForTest(); - - FirewallToIpPermission converter = new FirewallToIpPermission(); - - Iterable<IpPermission> perms = converter.apply(fw); - - assertEquals(Iterables.size(perms), 3, "There should be three IpPermissions but there is only " + Iterables.size(perms)); - - assertTrue(Iterables.any(perms, Predicates.and(hasProtocol(IpProtocol.TCP), - hasStartAndEndPort(1, 10))), "No permission found for TCP, ports 1-10"); - assertTrue(Iterables.any(perms, Predicates.and(hasProtocol(IpProtocol.TCP), - hasStartAndEndPort(33, 33))), "No permission found for TCP, port 33"); - assertTrue(Iterables.any(perms, hasProtocol(IpProtocol.ICMP)), - "No permission found for ICMP"); - } - - public static Firewall fwForTest() { - Firewall.Builder builder = Firewall.builder(); - - builder.addSourceRange("0.0.0.0/0"); - builder.addAllowed(Firewall.Rule.builder().IpProtocol(IpProtocol.TCP) - .addPortRange(1, 10).build()); - builder.addAllowed(Firewall.Rule.builder().IpProtocol(IpProtocol.TCP) - .addPort(33).build()); - builder.addAllowed(Firewall.Rule.builder().IpProtocol(IpProtocol.ICMP).build()); - builder.id("abcd"); - builder.selfLink(URI.create("https://www.googleapis.com/compute/v1/projects/myproject/global/firewalls/jclouds-test")); - builder.network(URI.create("https://www.googleapis.com/compute/v1/projects/myproject/global/networks/jclouds-test")); - builder.creationTimestamp(new Date()); - builder.name("jclouds-test"); - - return builder.build(); - } - - public static Predicate<IpPermission> hasProtocol(final IpProtocol protocol) { - return new Predicate<IpPermission>() { - - @Override - public boolean apply(IpPermission perm) { - return protocol.equals(perm.getIpProtocol()); - } - }; - } - - public static Predicate<IpPermission> hasStartAndEndPort(final int startPort, final int endPort) { - return new Predicate<IpPermission>() { - - @Override - public boolean apply(IpPermission perm) { - return startPort == perm.getFromPort() && endPort == perm.getToPort(); - } - }; - } - -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/GoogleComputeEngineImageToImageTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/GoogleComputeEngineImageToImageTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/GoogleComputeEngineImageToImageTest.java deleted file mode 100644 index 3bdd87e..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/GoogleComputeEngineImageToImageTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine.compute.functions; - -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.googlecomputeengine.domain.Image; -import org.testng.annotations.Test; - -import java.net.URI; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; - -@Test(groups = "unit") -public class GoogleComputeEngineImageToImageTest { - - Image.Builder imageBuilder = Image.builder() - .id("1234") - .selfLink(URI.create("http://test.com")) - .sourceType("RAW") - .description("") - .rawDisk(Image.RawDisk.builder().source("").containerType("TAR").build()); - - // This unit tests is failing randomly with the following error: - // java.lang.AssertionError: expected [linux] but found [ubuntu] - // Therefore commented to avoid the build failure - -// public void testArbitratyImageName() { -// GoogleComputeEngineImageToImage imageToImage = new GoogleComputeEngineImageToImage(); -// Image image = imageBuilder.name("arbitratyname").build(); -// org.jclouds.compute.domain.Image transformed = imageToImage.apply(image); -// assertEquals(transformed.getName(), image.getName()); -// assertEquals(transformed.getId(), image.getName()); -// assertEquals(transformed.getProviderId(), image.getId()); -// assertSame(transformed.getOperatingSystem().getFamily(), OsFamily.LINUX); -// } - - public void testWellFormedImageName() { - GoogleComputeEngineImageToImage imageToImage = new GoogleComputeEngineImageToImage(); - Image image = imageBuilder.name("ubuntu-12-04-v123123").build(); - org.jclouds.compute.domain.Image transformed = imageToImage.apply(image); - assertEquals(transformed.getName(), image.getName()); - assertEquals(transformed.getId(), image.getName()); - assertEquals(transformed.getProviderId(), image.getId()); - assertSame(transformed.getOperatingSystem().getFamily(), OsFamily.UBUNTU); - assertEquals(transformed.getOperatingSystem().getVersion(), "12.04"); - } - - -} http://git-wip-us.apache.org/repos/asf/stratos/blob/897edde8/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/InstanceInZoneToNodeMetadataTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/InstanceInZoneToNodeMetadataTest.java b/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/InstanceInZoneToNodeMetadataTest.java deleted file mode 100644 index 040f118..0000000 --- a/dependencies/jclouds/apis/gce/1.8.1-stratos/src/test/java/org/jclouds/googlecomputeengine/compute/functions/InstanceInZoneToNodeMetadataTest.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF 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.googlecomputeengine.compute.functions; - -import static org.easymock.EasyMock.createMock; -import static org.testng.Assert.assertEquals; -import static org.jclouds.compute.domain.Image.Status.AVAILABLE; - -import java.net.URI; -import java.util.Map; -import java.util.Set; - -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.ImageBuilder; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Processor; -import org.jclouds.compute.domain.Volume.Type; -import org.jclouds.compute.domain.VolumeBuilder; -import org.jclouds.compute.functions.GroupNamingConvention; -import org.jclouds.date.internal.SimpleDateFormatDateService; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationBuilder; -import org.jclouds.domain.LocationScope; -import org.jclouds.googlecomputeengine.GoogleComputeEngineApi; -import org.jclouds.googlecomputeengine.domain.Instance; -import org.jclouds.googlecomputeengine.domain.InstanceInZone; -import org.jclouds.googlecomputeengine.domain.Metadata; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; - -@Test(groups = "unit", testName = "InstanceInZoneToNodeMetadataTest") -public class InstanceInZoneToNodeMetadataTest { - - /** - * GroupNamingConvention that always returns the same name provided in the constructor. - * The predicates returned always evaluate to true. - * - */ - class FixedGroupNamingConvention implements GroupNamingConvention { - private final String name; - - public FixedGroupNamingConvention(final String name) { - this.name = name; - } - - @Override - public String sharedNameForGroup(final String group) { - return name; - } - - @Override - public String uniqueNameForGroup(final String group) { - return name; - } - - @Override - public String groupInUniqueNameOrNull(final String encoded) { - return name; - } - - @Override - public String groupInSharedNameOrNull(final String encoded) { - return name; - } - - @Override - public Predicate<String> containsGroup(final String group) { - return new Predicate<String>() { - @Override - public boolean apply(final String input) { - return true; - } - }; - } - - @Override - public Predicate<String> containsAnyGroup() { - return new Predicate<String>() { - @Override - public boolean apply(final String input) { - return true; - } - }; - } - - @Override - public String extractGroup(final String encoded) { - return name; - } - } - - private Instance instance; - - private Set<Hardware> hardwares; - - private Set<Image> images; - - private Set<Location> locations; - - private InstanceInZoneToNodeMetadata groupGroupNodeParser; - private InstanceInZoneToNodeMetadata groupNullNodeParser; - - @BeforeMethod - public final void setup() { - instance = Instance.builder() - .id("13051190678907570425") - .creationTimestamp(new SimpleDateFormatDateService().iso8601DateParse("2012-11-25T23:48:20.758")) - .selfLink(URI.create("https://www.googleapis" - + ".com/compute/v1/projects/myproject/zones/us-central1-a/instances/test-0")) - .description("desc") - .name("test-0") - .machineType(URI.create("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/" - + "machineTypes/n1-standard-1")) - .status(Instance.Status.RUNNING) - .zone(URI.create("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a")) - .addNetworkInterface( - Instance.NetworkInterface.builder() - .name("nic0") - .networkIP("10.240.121.115") - .network(URI.create("https://www.googleapis" - + ".com/compute/v1/projects/myproject/global/networks/default")) - .build()) - .addDisk( - Instance.PersistentAttachedDisk.builder() - .index(0) - .mode(Instance.PersistentAttachedDisk.Mode.READ_WRITE) - .deviceName("test") - .source(URI.create("https://www.googleapis" - + ".com/compute/v1/projects/myproject/zones/us-central1-a/disks/test")) - .boot(true) - .build()) - .tags(Instance.Tags.builder().fingerprint("abcd").addItem("aTag").addItem("Group-port-42").build()) - .metadata(Metadata.builder() - .items(ImmutableMap.of("aKey", "aValue", - "jclouds-image", - "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718", - "jclouds-delete-boot-disk", "true")) - .fingerprint("efgh") - .build()) - .addServiceAccount(Instance.ServiceAccount.builder().email("default").addScopes("myscope").build()) - .build(); - - images = ImmutableSet.of(new ImageBuilder() - .id("1") - .uri(URI.create("https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718")) - .providerId("1") - .name("mock image") - .status(AVAILABLE) - .operatingSystem( - OperatingSystem.builder().name("Ubuntu 14.04 x86_64").description("Ubuntu").family(OsFamily.UBUNTU) - .version("10.04").arch("x86_64").is64Bit(true).build()).build()); - - hardwares = ImmutableSet.of(new HardwareBuilder().id("my_id") - .uri(URI.create("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/machineTypes/" - + "n1-standard-1")) - .providerId("1") - .name("mock hardware").processor(new Processor(1.0, 1.0)).ram(2048) - .volume(new VolumeBuilder().size(20f).type(Type.LOCAL).build()).build()); - - locations = ImmutableSet.of(new LocationBuilder() - .id("id") - .description("https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a") - .scope(LocationScope.REGION) - .parent( - new LocationBuilder().id("0").description("mock parent location").scope(LocationScope.PROVIDER) - .build()).build()); - - groupGroupNodeParser = createNodeParser(hardwares, images, locations, "Group"); - groupNullNodeParser = createNodeParser(hardwares, images, locations, null); - } - - private InstanceInZoneToNodeMetadata createNodeParser(final Set<Hardware> hardware, final Set<Image> images, - final Set<Location> locations, final String groupName) { - Supplier<Map<URI, ? extends Location>> locationSupplier = new Supplier<Map<URI, ? extends Location>>() { - @Override - public Map<URI, ? extends Location> get() { - return Maps.uniqueIndex(locations, new Function<Location, URI>() { - @Override - public URI apply(final Location input) { - return URI.create(input.getDescription()); - } - }); - } - }; - - Supplier<Map<URI, ? extends Hardware>> hardwareSupplier = new Supplier<Map<URI, ? extends Hardware>>() { - @Override - public Map<URI, ? extends Hardware> get() { - return Maps.uniqueIndex(hardware, new Function<Hardware, URI>() { - @Override - public URI apply(final Hardware input) { - return input.getUri(); - } - }); - } - }; - - Supplier<Map<URI, ? extends Image>> imageSupplier = new Supplier<Map<URI, ? extends Image>>() { - @Override - public Map<URI, ? extends Image> get() { - return Maps.uniqueIndex(images, new Function<Image, URI>() { - @Override - public URI apply(final Image input) { - return input.getUri(); - } - }); - } - }; - - Supplier<String> userProjectSupplier = new Supplier<String>() { - @Override - public String get() { - return "userProject"; - } - }; - - GroupNamingConvention.Factory namingConventionFactory = - new GroupNamingConvention.Factory() { - @Override - public GroupNamingConvention createWithoutPrefix() { - return new FixedGroupNamingConvention(groupName); - } - - @Override - public GroupNamingConvention create() { - return new FixedGroupNamingConvention(groupName); - } - }; - - return new InstanceInZoneToNodeMetadata( - ImmutableMap.<Instance.Status, NodeMetadata.Status>builder() - .put(Instance.Status.RUNNING, NodeMetadata.Status.PENDING).build(), - namingConventionFactory, - imageSupplier, - hardwareSupplier, - locationSupplier, - new FirewallTagNamingConvention.Factory(namingConventionFactory), - createMock(GoogleComputeEngineApi.class), - userProjectSupplier); - } - - @Test - public final void testTagFilteringWorks() { - InstanceInZone instanceInZone = new InstanceInZone(instance, "zoneId"); - NodeMetadata nodeMetadata = groupGroupNodeParser.apply(instanceInZone); - assertEquals(nodeMetadata.getId(), "id/test-0"); - assertEquals(nodeMetadata.getTags(), ImmutableSet.<String>of( - "aTag" // "aTag" kept as a non firewall tag. - // "Group-port-42" filtered out as a firewall tag. - )); - } - - @Test - public final void testInstanceWithGroupNull() { - InstanceInZone instanceInZone = new InstanceInZone(instance, "zoneId"); - NodeMetadata nodeMetadata = groupNullNodeParser.apply(instanceInZone); - assertEquals(nodeMetadata.getId(), "id/test-0"); - assertEquals(nodeMetadata.getTags(), ImmutableSet.<String>of("aTag", "Group-port-42")); - } -}
