Merge branch 'master' of git://github.com/jclouds/jclouds

This commit is contained in:
vijaykiran 2011-10-24 01:09:08 +02:00
commit 66499ad663
85 changed files with 3255 additions and 1025 deletions

View File

@ -22,12 +22,15 @@ import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import javax.inject.Named;
import org.jclouds.Constants;
import org.jclouds.aws.domain.Region;
import org.jclouds.aws.filters.FormSigner;
import org.jclouds.cloudwatch.config.CloudWatchRestClientModule;
import org.jclouds.cloudwatch.xml.GetMetricStatisticsResponseHandler;
@ -42,6 +45,7 @@ import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
@ -50,7 +54,8 @@ import com.google.inject.TypeLiteral;
*
* @author Adrian Cole
*/
// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire
// NOTE:without testName, this will not call @Before* and fail w/NPE during
// surefire
@Test(groups = "unit", testName = "CloudWatchAsyncClientTest")
public class CloudWatchAsyncClientTest extends RestClientTest<CloudWatchAsyncClient> {
@ -95,6 +100,19 @@ public class CloudWatchAsyncClientTest extends RestClientTest<CloudWatchAsyncCli
super.configure();
}
protected void bindRegionsToProvider() {
bindRegionsToProvider(Regions.class);
}
static class Regions implements javax.inject.Provider<Map<String, URI>> {
@Override
public Map<String, URI> get() {
return ImmutableMap.<String, URI> of(Region.EU_WEST_1, URI.create("https://ec2.eu-west-1.amazonaws.com"),
Region.US_EAST_1, URI.create("https://ec2.us-east-1.amazonaws.com"), Region.US_WEST_1,
URI.create("https://ec2.us-west-1.amazonaws.com"));
}
}
@Override
protected String provideTimeStamp(final DateService dateService,
@Named(Constants.PROPERTY_SESSION_INTERVAL) int expiration) {

View File

@ -26,7 +26,7 @@ import org.jclouds.compute.config.BindComputeSuppliersByClass;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Location;
import org.jclouds.location.suppliers.OnlyLocationOrFirstZoneOrRegionMatchingRegionId;
import org.jclouds.location.suppliers.OnlyLocationOrFirstRegionOptionallyMatchingRegionId;
import org.jclouds.location.suppliers.ZoneToRegionToProviderOrJustProvider;
import com.google.common.base.Supplier;
@ -46,7 +46,7 @@ public class EC2BindComputeSuppliersByClass extends BindComputeSuppliersByClass
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return OnlyLocationOrFirstZoneOrRegionMatchingRegionId.class;
return OnlyLocationOrFirstRegionOptionallyMatchingRegionId.class;
}
@Override

View File

@ -273,8 +273,8 @@ public abstract class CommonSwiftClientLiveTest<C extends CommonSwiftClient> ext
}
protected void testGetObjectContentType(SwiftObject getBlob) {
assert getBlob.getPayload().getContentMetadata().getContentType().startsWith("text/plain") : getBlob.getPayload()
.getContentMetadata().getContentType();
String contentType = getBlob.getPayload().getContentMetadata().getContentType();
assert contentType.startsWith("text/plain") || "application/x-www-form-urlencoded".equals(contentType): contentType;
}
private SwiftObject newSwiftObject(String data, String key) throws IOException {

View File

@ -22,6 +22,8 @@ import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertEquals;
/**
*
* @author James Murty
@ -36,11 +38,12 @@ public class SwiftBlobIntegrationLiveTest extends BaseBlobIntegrationTest {
// not supported in swift
}
// not supported in swift
@Override
protected void checkContentDisposition(Blob blob, String contentDisposition) {
assert blob.getPayload().getContentMetadata().getContentDisposition() == null;
assert blob.getMetadata().getContentMetadata().getContentDisposition() == null;
// This works for Swift Server 1.4.4/SWauth 1.0.3 but was null in previous versions.
// TODO: Better testing for the different versions.
super.checkContentDisposition(blob,contentDisposition);
}
// not supported in swift

View File

@ -55,7 +55,7 @@ public class OrgAndVDCToLocationSupplier extends JustProvider {
OrgAndVDCToLocationSupplier(@Iso3166 Set<String> isoCodes, @Provider String providerName, @Provider URI endpoint,
@org.jclouds.vcloud.endpoints.Org Supplier<Map<String, ReferenceType>> orgNameToResource,
Supplier<Map<String, ? extends Org>> orgNameToVDCResource, @Iso3166 Map<String, Set<String>> isoCodesById) {
super(isoCodes, providerName, endpoint);
super(providerName, endpoint, isoCodes);
this.orgNameToResource = checkNotNull(orgNameToResource, "orgNameToResource");
this.orgNameToVDCResource = checkNotNull(orgNameToVDCResource, "orgNameToVDCResource");
this.isoCodesById = checkNotNull(isoCodesById, "isoCodesById");

View File

@ -55,7 +55,7 @@ public class OrgAndVDCToLocationSupplier extends JustProvider {
OrgAndVDCToLocationSupplier(@Iso3166 Set<String> isoCodes, @Provider String providerName, @Provider URI endpoint,
@org.jclouds.trmk.vcloud_0_8.endpoints.Org Supplier<Map<String, ReferenceType>> orgNameToResource,
Supplier<Map<String, ? extends Org>> orgNameToVDCResource, @Iso3166 Map<String, Set<String>> isoCodesById) {
super(isoCodes, providerName, endpoint);
super(providerName, endpoint, isoCodes);
this.orgNameToResource = checkNotNull(orgNameToResource, "orgNameToResource");
this.orgNameToVDCResource = checkNotNull(orgNameToVDCResource, "orgNameToVDCResource");
this.isoCodesById = checkNotNull(isoCodesById, "isoCodesById");

View File

@ -231,8 +231,15 @@ public class ComputeServiceUtils {
@Override
public boolean apply(String input) {
if ("".equals(input))
return false;
return in.indexOf(input) != -1;
}
@Override
public String toString() {
return String.format("containsSubString(%s)", in);
}
}
}

View File

@ -19,15 +19,22 @@
package org.jclouds.compute.util;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
import static org.jclouds.compute.util.ComputeServiceUtils.parseVersionOrReturnEmptyString;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import java.util.Map;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.http.HttpRequest;
import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
import com.google.inject.Guice;
/**
* Test the compute utils.
@ -37,33 +44,47 @@ import com.google.common.collect.ImmutableMultimap;
*/
@Test(groups = "unit")
public class ComputeServiceUtilsTest {
Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class));
@Test
public void testParseTagFromName() {
public void testParseGroupFromName() {
assertEquals(parseGroupFromName("gogrid--849"), "gogrid-");
}
@Test
public void testParseVersionOrReturnEmptyStringUbuntu1004() {
assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, "Ubuntu 10.04", map), "10.04");
}
@Test
public void testParseVersionOrReturnEmptyStringUbuntu1104() {
assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, "ubuntu 11.04 server (i386)", map), "11.04");
}
@Test
public void testExecHttpResponse() {
HttpRequest request = new HttpRequest("GET", URI.create("https://adriancolehappy.s3.amazonaws.com/java/install"),
ImmutableMultimap.of("Host", "adriancolehappy.s3.amazonaws.com", "Date",
"Sun, 12 Sep 2010 08:25:19 GMT", "Authorization", "AWS 0ASHDJAS82:JASHFDA="));
ImmutableMultimap.of("Host", "adriancolehappy.s3.amazonaws.com", "Date", "Sun, 12 Sep 2010 08:25:19 GMT",
"Authorization", "AWS 0ASHDJAS82:JASHFDA="));
assertEquals(
ComputeServiceUtils.execHttpResponse(request).render(OsFamily.UNIX),
"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https://adriancolehappy.s3.amazonaws.com/java/install |(bash)\n");
ComputeServiceUtils.execHttpResponse(request).render(org.jclouds.scriptbuilder.domain.OsFamily.UNIX),
"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https://adriancolehappy.s3.amazonaws.com/java/install |(bash)\n");
}
@Test
public void testTarxzpHttpResponse() {
HttpRequest request = new HttpRequest("GET", URI.create("https://adriancolehappy.s3.amazonaws.com/java/install"),
ImmutableMultimap.of("Host", "adriancolehappy.s3.amazonaws.com", "Date",
"Sun, 12 Sep 2010 08:25:19 GMT", "Authorization", "AWS 0ASHDJAS82:JASHFDA="));
ImmutableMultimap.of("Host", "adriancolehappy.s3.amazonaws.com", "Date", "Sun, 12 Sep 2010 08:25:19 GMT",
"Authorization", "AWS 0ASHDJAS82:JASHFDA="));
assertEquals(
ComputeServiceUtils.extractTargzIntoDirectory(request, "/stage/").render(OsFamily.UNIX),
"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https://adriancolehappy.s3.amazonaws.com/java/install |(mkdir -p /stage/ &&cd /stage/ &&tar -xpzf -)\n");
ComputeServiceUtils.extractTargzIntoDirectory(request, "/stage/").render(
org.jclouds.scriptbuilder.domain.OsFamily.UNIX),
"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https://adriancolehappy.s3.amazonaws.com/java/install |(mkdir -p /stage/ &&cd /stage/ &&tar -xpzf -)\n");
}
}

View File

@ -21,7 +21,7 @@ package org.jclouds.location.config;
import java.util.Set;
import org.jclouds.domain.Location;
import org.jclouds.location.suppliers.OnlyLocationOrFirstZoneOrRegionMatchingRegionId;
import org.jclouds.location.suppliers.OnlyLocationOrFirstRegionOptionallyMatchingRegionId;
import org.jclouds.location.suppliers.RegionToProviderOrJustProvider;
import com.google.common.base.Supplier;
@ -39,7 +39,7 @@ public class RegionsLocationModule extends LocationModule {
bind(new TypeLiteral<Supplier<Set<? extends Location>>>() {
}).to(RegionToProviderOrJustProvider.class);
bind(new TypeLiteral<Supplier<Location>>() {
}).to(OnlyLocationOrFirstZoneOrRegionMatchingRegionId.class);
}).to(OnlyLocationOrFirstRegionOptionallyMatchingRegionId.class);
super.configure();
}

View File

@ -20,23 +20,22 @@ package org.jclouds.location.functions;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.net.URI;
import java.util.Map;
import org.jclouds.javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.location.Provider;
import org.jclouds.location.Region;
import com.google.common.base.Function;
/**
* If a mapping of regions to endpoints exists, return a uri corresponding to the name of the region
* (passed argument). Otherwise, return the default location.
* Return a uri corresponding to the name of the region (passed argument).
* Otherwise, return the default location.
*
* @author Adrian Cole
*/
@ -47,20 +46,20 @@ public class RegionToEndpointOrProviderIfNull implements Function<Object, URI> {
private final Map<String, URI> regionToEndpoint;
@Inject
public RegionToEndpointOrProviderIfNull(@Provider URI defaultUri, @Provider String defaultProvider,
@Nullable @Region Map<String, URI> regionToEndpoint) {
this.defaultUri = checkNotNull(defaultUri, "defaultUri");
public RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider URI defaultUri,
@Region Map<String, URI> regionToEndpoint) {
this.defaultProvider = checkNotNull(defaultProvider, "defaultProvider");
this.regionToEndpoint = regionToEndpoint;
this.defaultUri = checkNotNull(defaultUri, "defaultUri");
this.regionToEndpoint = checkNotNull(regionToEndpoint, "regionToEndpoint");
checkArgument(regionToEndpoint.size() > 0, "no region name to endpoint mappings configured!");
}
@Override
public URI apply(@Nullable Object from) {
if (from == null || from.equals(defaultProvider))
return defaultUri;
checkState(from.equals(defaultProvider) || regionToEndpoint != null, "requested location " + from
+ ", but only the default location " + defaultProvider + " is configured");
checkArgument(from.equals(defaultProvider) || (regionToEndpoint != null && regionToEndpoint.containsKey(from)),
checkArgument(from instanceof String, "region is a String argument");
checkArgument(regionToEndpoint.containsKey(from),
"requested location %s, which is not in the configured locations: %s", from, regionToEndpoint);
return regionToEndpoint.get(from);
}

View File

@ -0,0 +1,41 @@
/**
* 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.location.functions;
import org.jclouds.domain.Location;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*
*/
public enum ToIdAndScope implements Function<Location, String> {
INSTANCE;
@Override
public String apply(Location input) {
return input.getId() + ":" + input.getScope();
}
@Override
public String toString() {
return "toIdAndScope()";
}
}

View File

@ -19,14 +19,15 @@
package org.jclouds.location.functions;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.Map;
import org.jclouds.javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.location.Zone;
import com.google.common.base.Function;
@ -42,12 +43,13 @@ public class ZoneToEndpoint implements Function<Object, URI> {
@Inject
public ZoneToEndpoint(@Zone Map<String, URI> zoneToEndpoint) {
this.zoneToEndpoint = zoneToEndpoint;
this.zoneToEndpoint = checkNotNull(zoneToEndpoint, "zoneToEndpoint");
checkArgument(zoneToEndpoint.size() > 0, "no zone name to endpoint mappings configured!");
}
@Override
public URI apply(@Nullable Object from) {
checkArgument(from != null, "you must specify a zone");
checkArgument(from != null && from instanceof String, "you must specify a zone, as a String argument");
return zoneToEndpoint.get(from);
}
}

View File

@ -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.location.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Singleton;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import com.google.common.base.Predicate;
/**
*
* @author Adrian Cole
*/
public class LocationPredicates {
public static Predicate<Location> isZone() {
return IsZone.INSTANCE;
}
@Singleton
static enum IsZone implements Predicate<Location> {
INSTANCE;
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.ZONE;
}
@Override
public String toString() {
return "isZone()";
}
}
public static Predicate<Location> isRegion() {
return IsRegion.INSTANCE;
}
static enum IsRegion implements Predicate<Location> {
INSTANCE;
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.REGION;
}
@Override
public String toString() {
return "isRegion()";
}
}
public static Predicate<Location> isZoneOrRegionWhereRegionIdEquals(String region) {
return new IsZoneOrRegionWhereRegionIdEquals(region);
}
static class IsZoneOrRegionWhereRegionIdEquals implements Predicate<Location> {
private final String region;
IsZoneOrRegionWhereRegionIdEquals(String region) {
this.region = checkNotNull(region, "region");
}
@Override
public boolean apply(Location input) {
switch (input.getScope()) {
case ZONE:
return input.getParent().getId().equals(region);
case REGION:
return input.getId().equals(region);
default:
return false;
}
}
@Override
public String toString() {
return "isRegionAndIdEqualsOrIsZoneParentIdEquals(" + region + ")";
}
}
}

View File

@ -46,7 +46,7 @@ public class JustProvider implements Supplier<Set<? extends Location>> {
private final Set<String> isoCodes;
@Inject
public JustProvider(@Iso3166 Set<String> isoCodes, @Provider String providerName, @Provider URI endpoint) {
public JustProvider(@Provider String providerName, @Provider URI endpoint, @Iso3166 Set<String> isoCodes) {
this.providerName = checkNotNull(providerName, "providerName");
this.endpoint = checkNotNull(endpoint, "endpoint");
this.isoCodes = checkNotNull(isoCodes, "isoCodes");
@ -54,8 +54,8 @@ public class JustProvider implements Supplier<Set<? extends Location>> {
@Override
public Set<? extends Location> get() {
return ImmutableSet.of(new LocationBuilder().scope(LocationScope.PROVIDER).id(providerName).description(
endpoint.toASCIIString()).iso3166Codes(isoCodes).build());
return ImmutableSet.of(new LocationBuilder().scope(LocationScope.PROVIDER).id(providerName)
.description(endpoint.toASCIIString()).iso3166Codes(isoCodes).build());
}
}

View File

@ -20,10 +20,15 @@ package org.jclouds.location.suppliers;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.location.predicates.LocationPredicates.isRegion;
import static org.jclouds.location.predicates.LocationPredicates.isZone;
import static org.jclouds.location.predicates.LocationPredicates.isZoneOrRegionWhereRegionIdEquals;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
@ -31,53 +36,27 @@ import org.jclouds.collect.Memoized;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.location.Region;
import org.jclouds.location.functions.ToIdAndScope;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
import com.google.inject.Key;
/**
* @author Adrian Cole
*/
@Singleton
public class OnlyLocationOrFirstZoneOrRegionMatchingRegionId implements Supplier<Location> {
@Singleton
public static final class IsRegionAndIdEqualsOrIsZoneParentIdEquals implements Predicate<Location> {
public class OnlyLocationOrFirstRegionOptionallyMatchingRegionId implements Supplier<Location> {
private final String region;
@Inject
IsRegionAndIdEqualsOrIsZoneParentIdEquals(@Region String region) {
this.region = checkNotNull(region, "region");
}
@Override
public boolean apply(Location input) {
switch (input.getScope()) {
case ZONE:
return input.getParent().getId().equals(region);
case REGION:
return input.getId().equals(region);
default:
return false;
}
}
@Override
public String toString() {
return "isRegionAndIdEqualsOrIsZoneParentIdEquals(" + region + ")";
}
}
private final Injector injector;
private final Predicate<Location> locationPredicate;
private final Supplier<Set<? extends Location>> locationsSupplier;
@Inject
OnlyLocationOrFirstZoneOrRegionMatchingRegionId(Injector injector,
@Memoized Supplier<Set<? extends Location>> locationsSupplier) {
this.injector = checkNotNull(injector, "injector");
OnlyLocationOrFirstRegionOptionallyMatchingRegionId(@Nullable @Region String region,
@Memoized Supplier<Set<? extends Location>> locationsSupplier) {
this.locationPredicate = region == null ? Predicates.<Location>or(isZone(), isRegion())
: isZoneOrRegionWhereRegionIdEquals(region);
this.locationsSupplier = checkNotNull(locationsSupplier, "locationsSupplier");
}
@ -87,16 +66,12 @@ public class OnlyLocationOrFirstZoneOrRegionMatchingRegionId implements Supplier
Set<? extends Location> locations = locationsSupplier.get();
if (locationsSupplier.get().size() == 1)
return getOnlyElement(locationsSupplier.get());
IsRegionAndIdEqualsOrIsZoneParentIdEquals matcher = null;
try {
String region = injector.getInstance(Key.get(String.class, Region.class));
if (region == null)
return Iterables.get(locationsSupplier.get(), 0);
matcher = injector.getInstance(IsRegionAndIdEqualsOrIsZoneParentIdEquals.class);
Location toReturn = Iterables.find(locations, matcher);
Location toReturn = Iterables.find(locations, locationPredicate);
return toReturn.getScope() == LocationScope.REGION ? toReturn : toReturn.getParent();
} catch (NoSuchElementException e) {
throw new IllegalStateException(String.format("region %s not found in %s", matcher, locations));
throw new NoSuchElementException(String.format("couldn't find region matching %s in %s", locationPredicate,
transform(locations, ToIdAndScope.INSTANCE)));
}
}
}

View File

@ -21,7 +21,10 @@ package org.jclouds.location.suppliers;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.location.predicates.LocationPredicates.isZone;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.inject.Inject;
@ -29,9 +32,8 @@ import javax.inject.Singleton;
import org.jclouds.collect.Memoized;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.location.functions.ToIdAndScope;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
/**
@ -41,33 +43,25 @@ import com.google.common.base.Supplier;
*/
@Singleton
public class OnlyLocationOrFirstZone implements Supplier<Location> {
@Singleton
public static final class IsZone implements Predicate<Location> {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.ZONE;
}
@Override
public String toString() {
return "isZone()";
}
}
private final Supplier<Set<? extends Location>> locationsSupplier;
private final IsZone isZone;
@Inject
OnlyLocationOrFirstZone(@Memoized Supplier<Set<? extends Location>> locationsSupplier, IsZone isZone) {
OnlyLocationOrFirstZone(@Memoized Supplier<Set<? extends Location>> locationsSupplier) {
this.locationsSupplier = checkNotNull(locationsSupplier, "locationsSupplierSupplier");
this.isZone = checkNotNull(isZone, "isZone");
}
@Override
public Location get() {
if (locationsSupplier.get().size() == 1)
return getOnlyElement(locationsSupplier.get());
return find(locationsSupplier.get(), isZone);
Set<? extends Location> locations = locationsSupplier.get();
if (locations.size() == 1)
return getOnlyElement(locations);
try {
return find(locations, isZone());
} catch (NoSuchElementException e) {
throw new NoSuchElementException("none to of the locations are scope ZONE: "
+ transform(locations, ToIdAndScope.INSTANCE));
}
}
}

View File

@ -50,7 +50,7 @@ public class RegionToProviderOrJustProvider extends JustProvider {
@Inject
public RegionToProviderOrJustProvider(@Iso3166 Set<String> isoCodes, @Provider String providerName,
@Provider URI endpoint, @Region Set<String> regions, @Iso3166 Map<String, Set<String>> isoCodesById) {
super(isoCodes, providerName, endpoint);
super(providerName, endpoint, isoCodes);
this.regions = checkNotNull(regions, "regions");
this.isoCodesById = checkNotNull(isoCodesById, "isoCodesById");
}

View File

@ -44,7 +44,7 @@ public class BindAsHostPrefix implements Binder {
@Inject
public BindAsHostPrefix(Provider<UriBuilder> uriBuilderProvider) {
this.uriBuilderProvider = uriBuilderProvider;
this.uriBuilderProvider = checkNotNull(uriBuilderProvider, "uriBuilderProvider");
}
@Override

View File

@ -20,6 +20,7 @@ package org.jclouds.rest.binders;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.http.utils.ModifyRequest.replaceMatrixParam;
import java.util.Map;
import java.util.Map.Entry;
@ -29,7 +30,6 @@ import javax.inject.Provider;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.utils.ModifyRequest;
import org.jclouds.rest.Binder;
/**
@ -42,16 +42,16 @@ public class BindMapToMatrixParams implements Binder {
@Inject
BindMapToMatrixParams(Provider<UriBuilder> builder) {
this.builder = builder;
this.builder = checkNotNull(builder, "builder");
}
@SuppressWarnings("unchecked") @Override
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
checkArgument(checkNotNull(input, "input") instanceof Map,
"this binder is only valid for Maps!");
checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Maps!");
Map<String, String> map = (Map<String, String>) input;
for (Entry<String, String> entry : map.entrySet()) {
request = ModifyRequest.replaceMatrixParam(request, entry.getKey(), entry.getValue(), builder.get());
request = replaceMatrixParam(request, entry.getKey(), entry.getValue(), builder.get());
}
return request;
}

View File

@ -18,6 +18,10 @@
*/
package org.jclouds.rest.binders;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.io.Payloads.newStringPayload;
import java.net.URI;
import java.util.Map;
@ -27,7 +31,6 @@ import javax.inject.Singleton;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
import org.jclouds.io.Payloads;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.annotations.Payload;
import org.jclouds.rest.internal.GeneratedHttpRequest;
@ -42,22 +45,25 @@ public class BindMapToStringPayload implements MapBinder {
@Inject
public BindMapToStringPayload(Provider<UriBuilder> uriBuilders) {
this.uriBuilders = uriBuilders;
this.uriBuilders = checkNotNull(uriBuilders, "uriBuilders");
}
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
GeneratedHttpRequest<?> r = GeneratedHttpRequest.class.cast(request);
checkNotNull(postParams, "postParams");
GeneratedHttpRequest<?> r = GeneratedHttpRequest.class.cast(checkNotNull(request, "request"));
checkArgument(r.getJavaMethod().isAnnotationPresent(Payload.class),
"method %s must have @Payload annotation to use this binder", r.getJavaMethod());
String payload = r.getJavaMethod().getAnnotation(Payload.class).value();
if (postParams.size() > 0) {
UriBuilder builder = uriBuilders.get();
builder.uri(URI.create("http://test/"));
builder.uri(URI.create("http://fake/"));
builder.path(payload);
URI fake = builder.buildFromMap(postParams);
payload = fake.getPath().substring(1);
}
return (R) request.toBuilder().payload(Payloads.newStringPayload(payload)).build();
return (R) request.toBuilder().payload(newStringPayload(payload)).build();
}
@Override

View File

@ -0,0 +1,70 @@
/**
* 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.location.functions;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.net.URI;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
/**
* Tests behavior of {@code RegionToEndpointOrProviderIfNull}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "RegionToEndpointOrProviderIfNullTest")
public class RegionToEndpointOrProviderIfNullTest {
@Test
public void testWhenFindsRegion() throws SecurityException, NoSuchMethodException {
RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", URI.create("http://leader"),
ImmutableMap.of("1", URI.create("http://1")));
assertEquals(fn.apply("1"), URI.create("http://1"));
}
public void testNullReturnsProvider() {
RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", URI.create("http://leader"),
ImmutableMap.of("1", URI.create("http://1")));
assertEquals(fn.apply("leader"), URI.create("http://leader"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeString() {
RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", URI.create("http://leader"),
ImmutableMap.of("1", URI.create("http://1")));
fn.apply(new File("foo"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeInRegionMapIfSpecified() {
RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", URI.create("http://leader"),
ImmutableMap.of("1", URI.create("http://1")));
fn.apply("2");
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustHaveEndpoints() {
new RegionToEndpointOrProviderIfNull("leader", URI.create("http://leader"), ImmutableMap.<String, URI> of());
}
}

View File

@ -0,0 +1,60 @@
/**
* 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.location.functions;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.net.URI;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
/**
* Tests behavior of {@code ZoneToEndpoint}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ZoneToEndpointTest")
public class ZoneToEndpointTest {
@Test
public void testCorrect() throws SecurityException, NoSuchMethodException {
ZoneToEndpoint fn = new ZoneToEndpoint(ImmutableMap.of("1", URI.create("http://1")));
assertEquals(fn.apply("1"), URI.create("http://1"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeString() {
ZoneToEndpoint fn = new ZoneToEndpoint(ImmutableMap.of("1", URI.create("http://1")));
fn.apply(new File("foo"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustHaveEndpoints() {
new ZoneToEndpoint(ImmutableMap.<String, URI> of());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullIsIllegal() {
ZoneToEndpoint fn = new ZoneToEndpoint(ImmutableMap.of("1", URI.create("http://1")));
fn.apply(null);
}
}

View File

@ -0,0 +1,48 @@
/**
* 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.location.suppliers;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code JustProvider}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "JustProviderTest")
public class JustProviderTest {
@Test
public void test() throws SecurityException, NoSuchMethodException {
JustProvider fn = new JustProvider("servo", URI.create("http://servo"), ImmutableSet.of("US"));
assertEquals(
fn.get(),
ImmutableSet.of(new LocationBuilder().scope(LocationScope.PROVIDER).id("servo").description("http://servo")
.iso3166Codes(ImmutableSet.of("US")).build()));
}
}

View File

@ -0,0 +1,94 @@
/**
* 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.location.suppliers;
import static org.testng.Assert.assertEquals;
import java.util.NoSuchElementException;
import java.util.Set;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.testng.annotations.Test;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code OnlyLocationOrFirstRegionOptionallyMatchingRegionId}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "OnlyLocationOrFirstRegionOptionallyMatchingRegionIdTest")
public class OnlyLocationOrFirstRegionOptionallyMatchingRegionIdTest {
Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id("servo").description("http://servo")
.build();
Location region = new LocationBuilder().scope(LocationScope.REGION).id("servo-r1").description("http://r1.servo")
.parent(provider).build();
Location region2 = new LocationBuilder().scope(LocationScope.REGION).id("servo-r2").description("http://r2.servo")
.parent(provider).build();
Location zone = new LocationBuilder().scope(LocationScope.ZONE).id("servo-z").description("http://z.r.servo")
.parent(region).build();
@Test
public void testDidntMatchRegionIdThrowsNSEEWithReasonableMessage() {
Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(provider, region, region2, zone));
OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(
"foo", supplier);
try {
fn.get();
assert false;
} catch (NoSuchElementException e) {
assertEquals(
e.getMessage(),
"couldn't find region matching isRegionAndIdEqualsOrIsZoneParentIdEquals(foo) in [servo:PROVIDER, servo-r1:REGION, servo-r2:REGION, servo-z:ZONE]");
}
}
@Test
public void testNoRegionUsesProvider() {
Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(provider));
OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(
null, supplier);
assertEquals(fn.get(), provider);
}
@Test
public void testFirstRegion() {
Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(provider, region, region2, zone));
OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(
null, supplier);
assertEquals(fn.get(), region);
}
@Test
public void testFindRegion() {
Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(provider, region, region2, zone));
OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(
region2.getId(), supplier);
assertEquals(fn.get(), region2);
}
}

View File

@ -0,0 +1,78 @@
/**
* 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.location.suppliers;
import static org.testng.Assert.assertEquals;
import java.util.NoSuchElementException;
import java.util.Set;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.testng.annotations.Test;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code OnlyLocationOrFirstZone}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "OnlyLocationOrFirstZoneTest")
public class OnlyLocationOrFirstZoneTest {
Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id("servo").description("http://servo")
.build();
Location region = new LocationBuilder().scope(LocationScope.REGION).id("servo-r").description("http://r.servo")
.parent(provider).build();
Location zone = new LocationBuilder().scope(LocationScope.ZONE).id("servo-z").description("http://z.r.servo")
.parent(region).build();
@Test
public void testDidntFindZoneThrowsNSEEWithReasonableMessage() {
Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(provider, region));
OnlyLocationOrFirstZone fn = new OnlyLocationOrFirstZone(supplier);
try {
fn.get();
assert false;
} catch (NoSuchElementException e) {
assertEquals(e.getMessage(), "none to of the locations are scope ZONE: [servo:PROVIDER, servo-r:REGION]");
}
}
@Test
public void testNoZoneUsesProvider() {
Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(provider));
OnlyLocationOrFirstZone fn = new OnlyLocationOrFirstZone(supplier);
assertEquals(fn.get(), provider);
}
@Test
public void testFirstZone() {
Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(provider, region, zone));
OnlyLocationOrFirstZone fn = new OnlyLocationOrFirstZone(supplier);
assertEquals(fn.get(), zone);
}
}

View File

@ -19,9 +19,10 @@
package org.jclouds.rest;
import static com.google.common.base.Throwables.propagate;
import static com.google.inject.util.Types.newParameterizedType;
import static org.easymock.classextension.EasyMock.createMock;
import static org.jclouds.http.HttpUtils.sortAndConcatHeadersIntoString;
import static org.eclipse.jetty.http.HttpHeaders.TRANSFER_ENCODING;
import static org.jclouds.http.HttpUtils.sortAndConcatHeadersIntoString;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
@ -29,8 +30,6 @@ import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.Constants;
import org.jclouds.concurrent.MoreExecutors;
import org.jclouds.concurrent.config.ConfiguresExecutorService;
@ -41,6 +40,7 @@ import org.jclouds.http.TransformingHttpCommandExecutorService;
import org.jclouds.http.config.ConfiguresHttpCommandExecutorService;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.io.MutableContentMetadata;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.Strings2;
@ -48,6 +48,7 @@ import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;
/**
@ -157,4 +158,10 @@ public abstract class BaseRestClientTest {
parserClass);
}
@SuppressWarnings("unchecked")
protected <T> RestAnnotationProcessor<T> factory(Class<T> clazz) {
return ((RestAnnotationProcessor<T>) injector.getInstance(Key.get(newParameterizedType(
RestAnnotationProcessor.class, clazz))));
}
}

View File

@ -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.rest.binders;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
import org.testng.annotations.Test;
import com.google.inject.util.Providers;
import com.sun.jersey.api.uri.UriBuilderImpl;
/**
* Tests behavior of {@code BindAsHostPrefix}
*
* @author Adrian Cole
*/
// NOTE:without testName, this will not call @Before* and fail w/NPE during
// surefire
@Test(groups = "unit", testName = "BindAsHostPrefixTest")
public class BindAsHostPrefixIfConfiguredTest {
public void testPrefixValid() {
BindAsHostPrefix binder = new BindAsHostPrefix(Providers.<UriBuilder> of(new UriBuilderImpl()));
HttpRequest request = binder.bindToRequest(new HttpRequest("GET", URI.create("https://s3.amazonaws.com")),
"bucket");
assertEquals(request.getRequestLine(), "GET https://bucket.s3.amazonaws.com HTTP/1.1");
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testPrefixInvalidHostname() {
BindAsHostPrefix binder = new BindAsHostPrefix(Providers.<UriBuilder> of(new UriBuilderImpl()));
binder.bindToRequest(new HttpRequest("GET", URI.create("https://s3.amazonaws.com")), "b_ucket");
}
}

View File

@ -23,7 +23,6 @@ import static org.testng.Assert.assertEquals;
import java.io.File;
import java.net.URI;
import javax.inject.Provider;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.UriBuilder;
@ -31,6 +30,7 @@ import org.jclouds.http.HttpRequest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.util.Providers;
import com.sun.jersey.api.uri.UriBuilderImpl;
/**
@ -45,14 +45,7 @@ public class BindMapToMatrixParamsTest {
public void testCorrect() throws SecurityException, NoSuchMethodException {
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
BindMapToMatrixParams binder = new BindMapToMatrixParams(new Provider<UriBuilder>() {
@Override
public UriBuilder get() {
return new UriBuilderImpl();
}
});
BindMapToMatrixParams binder = new BindMapToMatrixParams(Providers.<UriBuilder> of(new UriBuilderImpl()));
assertEquals(binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")), HttpRequest
.builder().method("GET").endpoint(URI.create("http://momma/;imageName=foo;serverId=2")).build());
@ -61,14 +54,14 @@ public class BindMapToMatrixParamsTest {
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeMap() {
BindMapToMatrixParams binder = new BindMapToMatrixParams(null);
BindMapToMatrixParams binder = new BindMapToMatrixParams(Providers.<UriBuilder> of(new UriBuilderImpl()));
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.bindToRequest(request, new File("foo"));
}
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })
@Test(expectedExceptions = NullPointerException.class)
public void testNullIsBad() {
BindMapToMatrixParams binder = new BindMapToMatrixParams(null);
BindMapToMatrixParams binder = new BindMapToMatrixParams(Providers.<UriBuilder> of(new UriBuilderImpl()));
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
binder.bindToRequest(request, null);
}

View File

@ -0,0 +1,94 @@
/**
* 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.rest.binders;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.util.Providers;
import com.sun.jersey.api.uri.UriBuilderImpl;
/**
* Tests behavior of {@code BindMapToStringPayload}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class BindMapToStringPayloadTest {
static interface TestPayload {
@org.jclouds.rest.annotations.Payload("name {fooble}")
void testPayload(@PathParam("foo") String path);
void noPayload(String path);
}
@Test
public void testCorrect() throws SecurityException, NoSuchMethodException {
Method testPayload = TestPayload.class.getMethod("testPayload", String.class);
GeneratedHttpRequest<TestPayload> request = GeneratedHttpRequest.<TestPayload> builder()
.declaring(TestPayload.class).javaMethod(testPayload).args(ImmutableList.<Object> of("robot"))
.method(HttpMethod.POST).endpoint(URI.create("http://localhost")).build();
GeneratedHttpRequest<TestPayload> newRequest = binder()
.bindToRequest(request, ImmutableMap.of("fooble", "robot"));
assertEquals(newRequest.getRequestLine(), request.getRequestLine());
assertEquals(newRequest.getPayload().getRawContent(), "name robot");
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustHavePayloadAnnotation() throws SecurityException, NoSuchMethodException {
Method noPayload = TestPayload.class.getMethod("noPayload", String.class);
GeneratedHttpRequest<TestPayload> request = GeneratedHttpRequest.<TestPayload> builder()
.declaring(TestPayload.class).javaMethod(noPayload).args(ImmutableList.<Object> of("robot"))
.method(HttpMethod.POST).endpoint(URI.create("http://localhost")).build();
binder().bindToRequest(request, ImmutableMap.of("fooble", "robot"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeMap() {
BindMapToStringPayload binder = binder();
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.bindToRequest(request, new File("foo"));
}
@Test(expectedExceptions = NullPointerException.class)
public void testNullIsBad() {
BindMapToStringPayload binder = binder();
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
binder.bindToRequest(request, null);
}
public BindMapToStringPayload binder() {
return new BindMapToStringPayload(Providers.<UriBuilder> of(new UriBuilderImpl()));
}
}

View File

@ -0,0 +1,71 @@
/**
* 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.rest.binders;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.net.URI;
import org.jclouds.http.HttpRequest;
import org.jclouds.json.Json;
import org.jclouds.json.internal.GsonWrapper;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
/**
* Tests behavior of {@code BindToJsonPayload}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "BindToJsonPayloadTest")
public class BindToJsonPayloadTest {
Json json = new GsonWrapper(new Gson());
@Test
public void testMap() throws SecurityException, NoSuchMethodException {
BindToJsonPayload binder = new BindToJsonPayload(json);
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
request = binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2"));
assertEquals(request.getPayload().getRawContent(), "{\"imageName\":\"foo\",\"serverId\":\"2\"}");
assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/json");
}
@Test
public void testSomethingNotAMap() throws SecurityException, NoSuchMethodException {
BindToJsonPayload binder = new BindToJsonPayload(json);
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
request = binder.bindToRequest(request, new File("foo"));
assertEquals(request.getPayload().getRawContent(), "{\"path\":\"foo\"}");
assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/json");
}
@Test(expectedExceptions = NullPointerException.class)
public void testNullIsBad() {
BindToJsonPayload binder = new BindToJsonPayload(json);
binder.bindToRequest(HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(), null);
}
}

View File

@ -0,0 +1,66 @@
/**
* 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.rest.binders;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.net.URI;
import org.jclouds.http.HttpRequest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
/**
* Tests behavior of {@code BindToStringPayload}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "BindToStringPayloadTest")
public class BindToStringPayloadTest {
@Test
public void testMap() throws SecurityException, NoSuchMethodException {
BindToStringPayload binder = new BindToStringPayload();
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
request = binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2"));
assertEquals(request.getPayload().getRawContent(), "{imageName=foo, serverId=2}");
assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/unknown");
}
@Test
public void testSomethingNotAMap() throws SecurityException, NoSuchMethodException {
BindToStringPayload binder = new BindToStringPayload();
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
request = binder.bindToRequest(request, new File("foo"));
assertEquals(request.getPayload().getRawContent(), "foo");
assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/unknown");
}
@Test(expectedExceptions = NullPointerException.class)
public void testNullIsBad() {
BindToStringPayload binder = new BindToStringPayload();
binder.bindToRequest(HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(), null);
}
}

View File

@ -20,7 +20,6 @@ package org.jclouds.rest.internal;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.inject.util.Types.newParameterizedType;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.reportMatcher;
@ -55,7 +54,6 @@ import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.jclouds.javax.annotation.Nullable;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Qualifier;
@ -108,6 +106,7 @@ import org.jclouds.http.options.HttpRequestOptions;
import org.jclouds.io.Payload;
import org.jclouds.io.PayloadEnclosing;
import org.jclouds.io.Payloads;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.logging.config.NullLoggingModule;
import org.jclouds.rest.AsyncClientFactory;
import org.jclouds.rest.AuthorizationException;
@ -161,7 +160,6 @@ import com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.AbstractModule;
import com.google.inject.ConfigurationException;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
@ -2457,11 +2455,6 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(form, "x-amz-copy-source=/eggs/robot");
}
@SuppressWarnings("unchecked")
private <T> RestAnnotationProcessor<T> factory(Class<T> clazz) {
return ((RestAnnotationProcessor<T>) injector.getInstance(Key.get(newParameterizedType(
RestAnnotationProcessor.class, clazz))));
}
DateService dateService = new SimpleDateFormatDateService();

View File

@ -26,7 +26,7 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Location;
import org.jclouds.location.suppliers.OnlyLocationOrFirstZoneOrRegionMatchingRegionId;
import org.jclouds.location.suppliers.OnlyLocationOrFirstRegionOptionallyMatchingRegionId;
import com.google.common.base.Supplier;
import com.google.inject.AbstractModule;
@ -66,7 +66,7 @@ public abstract class BindLoadBalancerSuppliersByClass extends AbstractModule {
}
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return OnlyLocationOrFirstZoneOrRegionMatchingRegionId.class;
return OnlyLocationOrFirstRegionOptionallyMatchingRegionId.class;
}
protected void bindImageSupplier(Class<? extends Supplier<Set<? extends Image>>> clazz) {

View File

@ -18,20 +18,17 @@
*/
package org.jclouds.aws.s3.binders;
import static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;
import static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;
import static org.jclouds.http.utils.ModifyRequest.endpoint;
import java.net.URI;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.utils.ModifyRequest;
import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;
import org.jclouds.rest.binders.BindAsHostPrefix;
import org.jclouds.s3.Bucket;
@ -48,10 +45,9 @@ public class AssignCorrectHostnameAndBindAsHostPrefixIfConfigured extends BindAs
@Inject
public AssignCorrectHostnameAndBindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, RegionToEndpointOrProviderIfNull r2,
Provider<UriBuilder> uriBuilderProvider, @Bucket Map<String, String> bucketToRegion) {
super(bindAsHostPrefix, isVhostStyle, servicePath, uriBuilderProvider);
RegionToEndpointOrProviderIfNull r2, Provider<UriBuilder> uriBuilderProvider,
@Bucket Map<String, String> bucketToRegion) {
super(bindAsHostPrefix, true, "/", uriBuilderProvider);
this.bucketToRegion = bucketToRegion;
this.r2 = r2;
}
@ -62,10 +58,8 @@ public class AssignCorrectHostnameAndBindAsHostPrefixIfConfigured extends BindAs
String region = bucketToRegion.get(bucket);
if (region != null) {
URI endpoint = r2.apply(region);
request = ModifyRequest.endpoint(
request,
uriBuilderProvider.get().uri(endpoint).path(request.getEndpoint().getPath())
.replaceQuery(request.getEndpoint().getQuery()).build());
request = endpoint(request, uriBuilderProvider.get().uri(endpoint).path(request.getEndpoint().getPath())
.replaceQuery(request.getEndpoint().getQuery()).build());
}
return super.bindToRequest(request, payload);
}

View File

@ -19,7 +19,6 @@
package org.jclouds.aws.s3;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Map;
@ -29,6 +28,7 @@ import java.util.concurrent.ConcurrentMap;
import org.jclouds.aws.s3.config.AWSS3RestClientModule;
import org.jclouds.aws.s3.functions.ETagFromHttpResponseViaRegex;
import org.jclouds.aws.s3.functions.UploadIdFromHttpResponseViaRegex;
import org.jclouds.blobstore.binders.BindBlobToMultipartFormTest;
import org.jclouds.date.TimeStamp;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.RequiresHttp;
@ -45,6 +45,7 @@ import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.s3.domain.ObjectMetadata;
import org.jclouds.s3.domain.ObjectMetadataBuilder;
import org.jclouds.s3.domain.S3Object;
import org.jclouds.s3.functions.ReturnFalseIfBucketAlreadyOwnedByYouOrIllegalState;
import org.jclouds.s3.options.PutBucketOptions;
import org.jclouds.s3.options.PutObjectOptions;
@ -84,6 +85,26 @@ public class AWSS3AsyncClientTest extends org.jclouds.s3.S3AsyncClientTest<AWSS3
checkFilters(request);
}
@Override
public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,
NoSuchMethodException, IOException {
Method method = AWSS3AsyncClient.class
.getMethod("putObject", String.class, S3Object.class, PutObjectOptions[].class);
HttpRequest request = processor.createRequest(method, "bucket",
blobToS3Object.apply(BindBlobToMultipartFormTest.TEST_BLOB));
assertRequestLineEquals(request, "PUT https://bucket." + url + "/hello HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket." + url + "\n");
assertPayloadEquals(request, "hello", "text/plain", false);
assertResponseParserClassEquals(method, request, ParseETagHeader.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
@Override
public void testGetBucketLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = AWSS3AsyncClient.class.getMethod("getBucketLocation", String.class);
@ -111,8 +132,8 @@ public class AWSS3AsyncClientTest extends org.jclouds.s3.S3AsyncClientTest<AWSS3
@Override
public void testPutBucketDefault() throws ArrayIndexOutOfBoundsException, SecurityException,
IllegalArgumentException, NoSuchMethodException, IOException {
Method method = AWSS3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array
.newInstance(PutBucketOptions.class, 0).getClass());
Method method = AWSS3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class,
PutBucketOptions[].class);
HttpRequest request = processor.createRequest(method, (String) null, "bucket");
assertRequestLineEquals(request, "PUT https://bucket.bucketendpoint/ HTTP/1.1");
@ -224,8 +245,8 @@ public class AWSS3AsyncClientTest extends org.jclouds.s3.S3AsyncClientTest<AWSS3
public void testPutBucketEu() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,
NoSuchMethodException, IOException {
Method method = AWSS3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array
.newInstance(PutBucketOptions.class, 0).getClass());
Method method = AWSS3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class,
PutBucketOptions[].class);
HttpRequest request = processor.createRequest(method, "EU", "bucket");
assertRequestLineEquals(request, "PUT https://bucket.bucketendpoint/ HTTP/1.1");

View File

@ -0,0 +1,84 @@
/**
* 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.aws.s3.binders;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import javax.inject.Provider;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;
import org.jclouds.rest.binders.BindAsHostPrefix;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.sun.jersey.api.uri.UriBuilderImpl;
/**
* Tests behavior of
* {@code AssignCorrectHostnameAndBindAsHostPrefixIfConfigured}
*
* @author Adrian Cole
*/
// NOTE:without testName, this will not call @Before* and fail w/NPE during
// surefire
@Test(groups = "unit", testName = "AssignCorrectHostnameAndBindAsHostPrefixIfConfiguredTest")
public class AssignCorrectHostnameAndBindAsHostPrefixIfConfiguredTest {
Provider<UriBuilder> uriBuilderProvider = new Provider<UriBuilder>() {
@Override
public UriBuilder get() {
return new UriBuilderImpl();
}
};
public void testWhenNoBucketRegionMappingInCache() {
HttpRequest request = new HttpRequest("GET", URI.create("https://s3.amazonaws.com"));
AssignCorrectHostnameAndBindAsHostPrefixIfConfigured binder = new AssignCorrectHostnameAndBindAsHostPrefixIfConfigured(
new BindAsHostPrefix(uriBuilderProvider), new RegionToEndpointOrProviderIfNull("aws-s3",
URI.create("https://s3.amazonaws.com"), ImmutableMap.of("us-standard",
URI.create("https://s3.amazonaws.com"), "us-west-1",
URI.create("https://s3-us-west-1.amazonaws.com"))), uriBuilderProvider,
ImmutableMap.<String, String> of());
request = binder.bindToRequest(request, "bucket");
assertEquals(request.getRequestLine(), "GET https://bucket.s3.amazonaws.com HTTP/1.1");
}
public void testWhenBucketRegionMappingInCache() {
HttpRequest request = new HttpRequest("GET", URI.create("https://s3.amazonaws.com"));
AssignCorrectHostnameAndBindAsHostPrefixIfConfigured binder = new AssignCorrectHostnameAndBindAsHostPrefixIfConfigured(
new BindAsHostPrefix(uriBuilderProvider), new RegionToEndpointOrProviderIfNull("aws-s3",
URI.create("https://s3.amazonaws.com"), ImmutableMap.of("us-standard",
URI.create("https://s3.amazonaws.com"), "us-west-1",
URI.create("https://s3-us-west-1.amazonaws.com"))), uriBuilderProvider,
ImmutableMap.<String, String> of("bucket", "us-west-1"));
request = binder.bindToRequest(request, "bucket");
assertEquals(request.getRequestLine(), "GET https://bucket.s3-us-west-1.amazonaws.com HTTP/1.1");
}
}

View File

@ -18,6 +18,8 @@
*/
package org.jclouds.cloudloadbalancers.config;
import static com.google.common.collect.Iterables.get;
import java.net.URI;
import java.util.Map;
import java.util.Set;
@ -37,10 +39,13 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.http.annotation.ClientError;
import org.jclouds.http.annotation.Redirection;
import org.jclouds.http.annotation.ServerError;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.config.GsonModule.DateAdapter;
import org.jclouds.json.config.GsonModule.Iso8601DateAdapter;
import org.jclouds.location.Provider;
import org.jclouds.location.Region;
import org.jclouds.location.config.ProvideRegionToURIViaProperties;
import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse;
import org.jclouds.openstack.config.OpenStackAuthenticationModule;
import org.jclouds.openstack.reference.AuthHeaders;
@ -48,6 +53,7 @@ import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.config.RestClientModule;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
@ -64,11 +70,11 @@ import com.google.inject.TypeLiteral;
@RequiresHttp
@ConfiguresRestClient
public class CloudLoadBalancersRestClientModule extends
RestClientModule<CloudLoadBalancersClient, CloudLoadBalancersAsyncClient> {
RestClientModule<CloudLoadBalancersClient, CloudLoadBalancersAsyncClient> {
public static final Map<Class<?>, Class<?>> DELEGATE_MAP = ImmutableMap.<Class<?>, Class<?>> builder()//
.put(LoadBalancerClient.class, LoadBalancerAsyncClient.class)//
.build();
.put(LoadBalancerClient.class, LoadBalancerAsyncClient.class)//
.build();
public CloudLoadBalancersRestClientModule() {
super(CloudLoadBalancersClient.class, CloudLoadBalancersAsyncClient.class, DELEGATE_MAP);
@ -83,8 +89,8 @@ public class CloudLoadBalancersRestClientModule extends
@Inject
protected ProvideRegionToURIViaPropertiesWithAccountID(Injector injector,
@Named("CONSTANTS") Multimap<String, String> constants,
@Named(RackspaceConstants.PROPERTY_ACCOUNT_ID) String accountID) {
@Named("CONSTANTS") Multimap<String, String> constants,
@Named(RackspaceConstants.PROPERTY_ACCOUNT_ID) String accountID) {
super(injector, constants);
constants.replaceValues(RackspaceConstants.PROPERTY_ACCOUNT_ID, ImmutableSet.of(accountID));
}
@ -118,14 +124,28 @@ public class CloudLoadBalancersRestClientModule extends
return endpoints.keySet();
}
@Provides
@Singleton
@Nullable
@Region
protected String getDefaultRegion(@Provider URI uri, @Region Map<String, URI> map, LoggerFactory logFactory) {
String region = ImmutableBiMap.copyOf(map).inverse().get(uri);
if (region == null && map.size() > 0) {
logFactory.getLogger(getClass().getName()).warn(
"failed to find region for current endpoint %s in %s; choosing first: %s", uri, map, region);
region = get(map.keySet(), 0);
}
return region;
}
@Override
protected void bindErrorHandlers() {
bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(
ParseCloudLoadBalancersErrorFromHttpResponse.class);
ParseCloudLoadBalancersErrorFromHttpResponse.class);
bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(
ParseCloudLoadBalancersErrorFromHttpResponse.class);
ParseCloudLoadBalancersErrorFromHttpResponse.class);
bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(
ParseCloudLoadBalancersErrorFromHttpResponse.class);
ParseCloudLoadBalancersErrorFromHttpResponse.class);
}
}

View File

@ -21,6 +21,8 @@ package org.jclouds.cloudloadbalancers.features;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Properties;
import org.jclouds.cloudloadbalancers.CloudLoadBalancersAsyncClient;
@ -40,6 +42,7 @@ import org.testng.annotations.BeforeClass;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Module;
/**
@ -50,6 +53,19 @@ public abstract class BaseCloudLoadBalancersAsyncClientTest<T> extends RestClien
@RequiresHttp
@ConfiguresRestClient
public static class CloudLoadBalancersRestClientModuleExtension extends CloudLoadBalancersRestClientModule {
protected void bindRegionsToProvider() {
bindRegionsToProvider(Regions.class);
}
static class Regions implements javax.inject.Provider<Map<String, URI>> {
@Override
public Map<String, URI> get() {
return ImmutableMap.<String, URI> of("DFW",
URI.create("https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/1234"));
}
}
@Override
protected String accountID(Supplier<AuthenticationResponse> in) {
return "1234";
@ -79,8 +95,8 @@ public abstract class BaseCloudLoadBalancersAsyncClientTest<T> extends RestClien
super.setupFactory();
try {
processor.setCaller(new ClassMethodArgs(CloudLoadBalancersAsyncClient.class,
CloudLoadBalancersAsyncClient.class.getMethod("getLoadBalancerClient", String.class),
new Object[] { Region.DFW }));
CloudLoadBalancersAsyncClient.class.getMethod("getLoadBalancerClient", String.class),
new Object[] { Region.DFW }));
} catch (Exception e) {
Throwables.propagate(e);
}

View File

@ -53,7 +53,7 @@ public class GoGridLocationSupplier extends JustProvider {
@Inject
GoGridLocationSupplier(@Iso3166 Set<String> isoCodes, @Provider String providerName, @Provider URI endpoint,
GoGridClient sync, @Iso3166 Map<String, Set<String>> isoCodesById) {
super(isoCodes, providerName, endpoint);
super(providerName, endpoint, isoCodes);
this.sync = checkNotNull(sync, "sync");
this.isoCodesById = checkNotNull(isoCodesById, "isoCodesById");
}

View File

@ -56,7 +56,7 @@ public class RimuHostingLocationSupplier extends JustProvider {
@Inject
RimuHostingLocationSupplier(@Iso3166 Set<String> isoCodes, @Provider String providerName, @Provider URI endpoint,
RimuHostingClient sync, @Iso3166 Map<String, Set<String>> isoCodesById) {
super(isoCodes, providerName, endpoint);
super(providerName, endpoint, isoCodes);
this.sync = checkNotNull(sync, "sync");
this.isoCodesById = checkNotNull(isoCodesById, "isoCodesById");
}

View File

@ -40,8 +40,8 @@ import com.google.common.collect.ImmutableSet;
@Test(singleThreaded = true, groups = "unit")
public class DatacenterToLocationTest {
static DatacenterToLocation function = new DatacenterToLocation(new JustProvider(ImmutableSet.<String> of(), "softlayer",
URI.create("foo")));;
static DatacenterToLocation function = new DatacenterToLocation(new JustProvider("softlayer", URI.create("foo"),
ImmutableSet.<String> of()));
@Test
public void testDatacenterToLocation() {
@ -85,7 +85,7 @@ public class DatacenterToLocationTest {
@Test
public void testGetIso3166CodeWhitespaceTrimmer() {
Address address = Address.builder().country(" US ").state(" TX ").description("This is spaced out Texas")
.build();
.build();
Datacenter datacenter = Datacenter.builder().id(1).longName("Nowhere").locationAddress(address).build();

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox;

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox;

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox;

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.compute;

View File

@ -1,175 +1,175 @@
/*
* *
* * 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.
/**
* 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.virtualbox.compute;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import javax.inject.Inject;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.inject.Singleton;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.location.suppliers.JustProvider;
import org.jclouds.virtualbox.functions.admin.ImageFromYamlStream;
import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.SessionState;
import org.virtualbox_4_1.VirtualBoxManager;
import org.virtualbox_4_1.*;
import com.google.common.base.Throwables;
import com.google.inject.Singleton;
import javax.inject.Inject;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
/**
* Defines the connection between the {@link org.virtualbox_4_1.VirtualBoxManager} implementation and the jclouds
* Defines the connection between the
* {@link org.virtualbox_4_1.VirtualBoxManager} implementation and the jclouds
* {@link org.jclouds.compute.ComputeService}
*
*
* @author Mattias Holmqvist, Andrea Turli
*/
@Singleton
public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IMachine, IMachine, Image, Location> {
private final VirtualBoxManager manager;
private final VirtualBoxManager manager;
private final JustProvider justProvider;
private Function<IMachine, Image> iMachineToImage;
@Inject
public VirtualBoxComputeServiceAdapter(VirtualBoxManager manager, JustProvider justProvider) {
this.manager = checkNotNull(manager, "manager");
@Inject
public VirtualBoxComputeServiceAdapter(VirtualBoxManager manager, JustProvider justProvider, Function<IMachine, Image> iMachineToImage) {
this.iMachineToImage = iMachineToImage;
this.manager = checkNotNull(manager, "manager");
this.justProvider = checkNotNull(justProvider, "justProvider");
}
}
@Override
public IMachine createNodeWithGroupEncodedIntoNameThenStoreCredentials(String tag, String name, Template template, Map<String, Credentials> credentialStore) {
return null;
}
@Override
public IMachine createNodeWithGroupEncodedIntoNameThenStoreCredentials(String tag, String name, Template template,
Map<String, Credentials> credentialStore) {
return null;
}
@Override
public Iterable<IMachine> listNodes() {
return Collections.emptyList();
}
@Override
public Iterable<IMachine> listHardwareProfiles() {
return manager.getVBox().getMachines();
}
@Override
public Iterable<IMachine> listNodes() {
return Collections.emptyList();
}
@Override
public Iterable<IMachine> listHardwareProfiles() {
return manager.getVBox().getMachines();
}
@Override
public Iterable<Image> listImages() {
InputStream is = getClass().getResourceAsStream("/testImages.yaml");
ImageFromYamlStream parser = new ImageFromYamlStream();
return parser.apply(is).asMap().values();
final Predicate<? super IMachine> imagePredicate = new Predicate<IMachine>() {
@Override
public boolean apply(@Nullable IMachine iMachine) {
return iMachine.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX);
}
};
final Iterable<IMachine> imageMachines = filter(manager.getVBox().getMachines(), imagePredicate);
return transform(imageMachines, iMachineToImage);
}
@SuppressWarnings("unchecked")
@SuppressWarnings("unchecked")
@Override
public Iterable<Location> listLocations() {
public Iterable<Location> listLocations() {
return (Iterable<Location>) justProvider.get();
}
}
@Override
public IMachine getNode(String vmName) {
return manager.getVBox().findMachine(vmName);
}
@Override
public IMachine getNode(String vmName) {
return manager.getVBox().findMachine(vmName);
}
@Override
public void destroyNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
machine.unregister(CleanupMode.Full);
}
@Override
public void destroyNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
machine.unregister(CleanupMode.Full);
}
@Override
public void rebootNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
launchVMProcess(machine, manager.getSessionObject());
}
@Override
public void rebootNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
launchVMProcess(machine, manager.getSessionObject());
}
@Override
public void resumeNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.openMachineSession(machine);
machineSession.getConsole().resume();
machineSession.unlockMachine();
} catch (Exception e) {
propogate(e);
}
}
@Override
public void resumeNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.openMachineSession(machine);
machineSession.getConsole().resume();
machineSession.unlockMachine();
} catch (Exception e) {
propogate(e);
}
}
@Override
public void suspendNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.openMachineSession(machine);
machineSession.getConsole().pause();
machineSession.unlockMachine();
} catch (Exception e) {
propogate(e);
}
}
@Override
public void suspendNode(String vmName) {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.openMachineSession(machine);
machineSession.getConsole().pause();
machineSession.unlockMachine();
} catch (Exception e) {
propogate(e);
}
}
protected <T> T propogate(Exception e) {
Throwables.propagate(e);
assert false;
return null;
}
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
protected <T> T propogate(Exception e) {
Throwables.propagate(e);
assert false;
return null;
}
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out
.println("waiting for unlocking session - session state: "
+ machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
}
}
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
}
}
}

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.config;
@ -85,21 +83,19 @@ public class VirtualBoxComputeServiceContextModule extends ComputeServiceAdapter
}).to(IMachineToNodeMetadata.class);
bind(new TypeLiteral<Function<Location, Location>>() {
}).to((Class) IdentityFunction.class);
bind(new TypeLiteral<Function<IMachine, Hardware>>() {
}).to(IMachineToHardware.class);
bind(new TypeLiteral<Function<Image, Image>>() {
}).to((Class) IdentityFunction.class);
/*
bind(new TypeLiteral<Function<IMachine, Hardware>>() {
}).to(IMachineToHardware.class);
bind(new TypeLiteral<Function<IMachine, Image>>() {
}).to(IMachineToImage.class);
*/
bind(new TypeLiteral<Supplier<Location>>() {
}).to(OnlyLocationOrFirstZone.class);
}
@Override
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
return template.osFamily(OsFamily.UBUNTU).os64Bit(false).osVersionMatches("11.04-server");
return template.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04");
}
@VisibleForTesting

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.config;

View File

@ -23,7 +23,7 @@
package org.jclouds.virtualbox.domain;
import static org.jclouds.virtualbox.functions.IMachineToImage.osFamily;
import static org.jclouds.compute.util.ComputeServiceUtils.parseOsFamilyOrUnrecognized;
import java.util.List;
import java.util.Map;
@ -141,8 +141,8 @@ public class YamlImage {
public Image apply(YamlImage arg0) {
if (arg0 == null)
return null;
OsFamily family = osFamily().apply(arg0.os_family);
OsFamily family = parseOsFamilyOrUnrecognized(arg0.os_family);
OperatingSystem operatingSystem = OperatingSystem.builder()
.description(arg0.os_description)
.family(family)

View File

@ -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.virtualbox.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VBoxException;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*
*/
public class AddIDEControllerIfNotExists implements Function<IMachine, Void> {
private final String controllerName;
public AddIDEControllerIfNotExists(String controllerName) {
this.controllerName = checkNotNull(controllerName, "controllerName");
}
@Override
public Void apply(IMachine machine) {
try {
machine.addStorageController(controllerName, StorageBus.IDE);
machine.saveSettings();
} catch (VBoxException e) {
if (e.getMessage().indexOf("already exists") == -1)
throw e;
}
return null;
}
@Override
public String toString() {
return String.format("addStorageController(%s, IDE)", controllerName);
}
}

View File

@ -0,0 +1,44 @@
/*
* 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.virtualbox.functions;
import com.google.common.base.Function;
import org.virtualbox_4_1.IMachine;
import javax.annotation.Nullable;
/**
* @author Mattias Holmqvist
*/
public class ApplyMemoryToMachine implements Function<IMachine, Object> {
private long memorySize;
public ApplyMemoryToMachine(long memorySize) {
this.memorySize = memorySize;
}
@Override
public Object apply(@Nullable IMachine machine) {
machine.setMemorySize(memorySize);
machine.saveSettings();
return null;
}
}

View File

@ -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.virtualbox.functions;
import com.google.common.base.Function;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.VBoxException;
import javax.annotation.Nullable;
/**
* @author Mattias Holmqvist
*/
public class AttachDistroMediumToMachine implements Function<IMachine, Void> {
private final String controllerIDE;
private final IMedium distroMedium;
public AttachDistroMediumToMachine(String controllerIDE, IMedium distroMedium) {
this.controllerIDE = controllerIDE;
this.distroMedium = distroMedium;
}
@Override
public Void apply(@Nullable IMachine machine) {
try {
int controllerPort = 0;
int device = 0;
machine.attachDevice(controllerIDE, controllerPort, device, DeviceType.DVD, distroMedium);
machine.saveSettings();
} catch (VBoxException e) {
if (!alreadyAttached(e))
throw e;
}
return null;
}
private boolean alreadyAttached(VBoxException e) {
return e.getMessage().indexOf("is already attached to port") != -1;
}
}

View File

@ -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.virtualbox.functions;
import com.google.common.base.Function;
import org.virtualbox_4_1.*;
import javax.annotation.Nullable;
import static org.virtualbox_4_1.DeviceType.HardDisk;
/**
* @author Mattias Holmqvist
*/
public class AttachMediumToMachineIfNotAlreadyAttached implements Function<IMachine, Void> {
private String controllerIDE;
private IMedium hardDisk;
private int controllerPort;
private int device;
private DeviceType deviceType;
public AttachMediumToMachineIfNotAlreadyAttached(String controllerIDE, IMedium hardDisk, int controllerPort, int device, DeviceType deviceType) {
this.controllerIDE = controllerIDE;
this.hardDisk = hardDisk;
this.controllerPort = controllerPort;
this.device = device;
this.deviceType = deviceType;
}
@Override
public Void apply(@Nullable IMachine machine) {
// Create and attach medium
try {
machine.attachDevice(controllerIDE, controllerPort, device, deviceType, hardDisk);
machine.saveSettings();
} catch (VBoxException e) {
if (!alreadyAttached(e))
throw e;
}
return null;
}
private boolean alreadyAttached(VBoxException e) {
return e.getMessage().indexOf("is already attached to port") != -1;
}
}

View File

@ -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.virtualbox.functions;
import com.google.common.base.Function;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.INetworkAdapter;
import javax.annotation.Nullable;
import static org.virtualbox_4_1.NATProtocol.TCP;
import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
/**
* @author Mattias Holmqvist
*/
public class AttachNATRedirectRuleToMachine implements Function<IMachine, Void> {
private long adapterIndex;
public AttachNATRedirectRuleToMachine(long adapterSlot) {
this.adapterIndex = adapterSlot;
}
@Override
public Void apply(@Nullable IMachine machine) {
INetworkAdapter networkAdapter = machine.getNetworkAdapter(adapterIndex);
networkAdapter.setAttachmentType(NAT);
networkAdapter.getNatDriver().addRedirect("guestssh", TCP, "127.0.0.1", 2222, "", 22);
networkAdapter.setEnabled(true);
machine.saveSettings();
return null;
}
}

View File

@ -0,0 +1,75 @@
/**
* 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.virtualbox.functions;
import com.google.common.base.Function;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import javax.annotation.Nullable;
/**
* @author Mattias Holmqvist
*/
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<String, IMachine> {
private String settingsFile;
private String osTypeId;
private String vmId;
private boolean forceOverwrite;
private VirtualBoxManager manager;
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(String settingsFile, String osTypeId, String vmId,
boolean forceOverwrite, VirtualBoxManager manager) {
this.settingsFile = settingsFile;
this.osTypeId = osTypeId;
this.vmId = vmId;
this.forceOverwrite = forceOverwrite;
this.manager = manager;
}
@Override
public IMachine apply(@Nullable String vmName) {
final IVirtualBox vBox = manager.getVBox();
try {
vBox.findMachine(vmName);
throw new IllegalStateException("Machine " + vmName + " is already registered.");
} catch (VBoxException e) {
if (machineNotFoundException(e))
return createMachine(vBox, vmName);
else
throw e;
}
}
private boolean machineNotFoundException(VBoxException e) {
return e.getMessage().indexOf("VirtualBox error: Could not find a registered machine named ") != -1;
}
private IMachine createMachine(IVirtualBox vBox, String vmName) {
IMachine newMachine = vBox.createMachine(settingsFile, vmName, osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newMachine);
return newMachine;
}
}

View File

@ -0,0 +1,97 @@
/**
* 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.virtualbox.functions;
import com.google.common.base.Function;
import org.virtualbox_4_1.*;
import javax.annotation.Nullable;
/**
* @author Mattias Holmqvist
*/
public class CreateMediumIfNotAlreadyExists implements Function<String, IMedium> {
private final VirtualBoxManager manager;
private final String diskFormat;
private boolean overwriteIfExists;
public CreateMediumIfNotAlreadyExists(VirtualBoxManager manager, String diskFormat, boolean overwriteIfExists) {
this.manager = manager;
this.diskFormat = diskFormat;
this.overwriteIfExists = overwriteIfExists;
}
@Override
public IMedium apply(@Nullable String path) {
IVirtualBox vBox = manager.getVBox();
try {
final IMedium medium = vBox.findMedium(path, DeviceType.HardDisk);
if (overwriteIfExists) {
final IProgress progress = medium.deleteStorage();
progress.waitForCompletion(-1);
return createNewMedium(vBox, path);
} else {
throw new IllegalStateException("Medium for path " + path + " already exists.");
}
} catch (VBoxException e) {
if (notFoundException(e))
return createNewMedium(vBox, path);
throw e;
}
}
private IMedium createNewMedium(IVirtualBox vBox, String path) {
IMedium hardDisk = vBox.createHardDisk(diskFormat, path);
createBaseStorage(hardDisk);
return hardDisk;
}
private boolean notFoundException(VBoxException e) {
return e.getMessage().indexOf("Could not find an open hard disk with location ") != -1;
}
private void createBaseStorage(IMedium hardDisk) {
try {
long size = 4L * 1024L * 1024L * 1024L - 4L;
IProgress storageCreation = hardDisk.createBaseStorage(size, (long) org.virtualbox_4_1.jaxws.MediumVariant.STANDARD.ordinal());
storageCreation.waitForCompletion(-1);
} catch (VBoxException e) {
if (fileNotFoundException(e)) {
// File for medium could not be found. Something wrong with creation.
hardDisk.deleteStorage();
}
if (!storageAlreadyExists(e)) {
// Hard disk file was created but the storage had been created before that.
throw e;
}
}
}
private boolean fileNotFoundException(VBoxException e) {
return e.getMessage().indexOf("VERR_FILE_NOT_FOUND") != -1;
}
private boolean storageAlreadyExists(VBoxException e) {
return e.getMessage().indexOf("VirtualBox error: Storage for the medium ") != -1 &&
e.getMessage().indexOf("is already created") != -1;
}
}

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions;

View File

@ -1,27 +1,33 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions;
import com.google.common.base.Function;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.parseOsFamilyOrUnrecognized;
import static org.jclouds.compute.util.ComputeServiceUtils.parseVersionOrReturnEmptyString;
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;
@ -31,76 +37,33 @@ import org.virtualbox_4_1.IGuestOSType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.VirtualBoxManager;
import javax.inject.Inject;
import com.google.common.base.Function;
@Singleton
public class IMachineToImage implements Function<IMachine, Image> {
private static final String UBUNTU = "Ubuntu";
private VirtualBoxManager virtualboxManager;
private final VirtualBoxManager virtualboxManager;
private final Map<OsFamily, Map<String, String>> osVersionMap;
@Inject
public IMachineToImage(VirtualBoxManager virtualboxManager) {
this.virtualboxManager = virtualboxManager;
public IMachineToImage(VirtualBoxManager virtualboxManager, Map<OsFamily, Map<String, String>> osVersionMap) {
this.virtualboxManager = checkNotNull(virtualboxManager, "virtualboxManager");
this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap");
}
@Override
public Image apply(@Nullable IMachine from) {
if (from == null)
return null;
IGuestOSType guestOSType = virtualboxManager.getVBox().getGuestOSType(from.getOSTypeId());
OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription());
String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(),
osVersionMap);
OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family)
.version(version).is64Bit(guestOSType.getIs64Bit()).build();
OsFamily family = osFamily().apply(guestOSType.getDescription());
OperatingSystem os = OperatingSystem.builder()
.description(guestOSType.getDescription())
.family(family)
.version(osVersion().apply(guestOSType.getDescription()))
.is64Bit(guestOSType.getIs64Bit())
.build();
return new ImageBuilder()
.id("" + from.getId())
.description(from.getDescription())
.operatingSystem(os)
.build();
return new ImageBuilder().id("" + from.getId()).description(from.getDescription()).operatingSystem(os).build();
}
/**
* Parses the item description to determine the OSFamily
*
* @return the @see OsFamily or OsFamily.UNRECOGNIZED
*/
public static Function<String, OsFamily> osFamily() {
return new Function<String, OsFamily>() {
@Override
public OsFamily apply(String osDescription) {
if (osDescription.startsWith("linux")) return OsFamily.LINUX;
return OsFamily.UNRECOGNIZED;
}
};
}
/**
* Parses the item description to determine the os version
*
* @return the version, empty if not found
*/
public static Function<String, String> osVersion() {
return new Function<String, String>() {
@Override
public String apply(String osDescription) {
OsFamily family = osFamily().apply(osDescription);
if (family.equals(OsFamily.UBUNTU))
return parseVersion(osDescription, UBUNTU);
else
return "";
}
};
}
private static String parseVersion(String description, String os) {
String noOsName = description.replaceFirst(os, "").trim();
return noOsName.split(" ")[0];
}
}

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions;

View File

@ -1,26 +1,25 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.propagate;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
@ -28,20 +27,16 @@ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTA
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR;
import static org.virtualbox_4_1.AccessMode.ReadOnly;
import static org.virtualbox_4_1.DeviceType.DVD;
import static org.virtualbox_4_1.DeviceType.HardDisk;
import static org.virtualbox_4_1.LockType.Shared;
import static org.virtualbox_4_1.LockType.Write;
import static org.virtualbox_4_1.NATProtocol.TCP;
import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
import java.io.File;
import javax.annotation.Resource;
import javax.inject.Named;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.options.RunScriptOptions;
@ -53,249 +48,267 @@ import org.jclouds.ssh.SshException;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning;
import org.jclouds.virtualbox.settings.KeyboardScancodes;
import org.virtualbox_4_1.AccessMode;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VirtualBoxManager;
import org.virtualbox_4_1.jaxws.MediumVariant;
import org.virtualbox_4_1.*;
import com.google.common.base.Function;
import com.google.inject.Inject;
public class IsoToIMachine implements Function<String, IMachine> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private VirtualBoxManager manager;
private String adminDisk;
private String diskFormat;
private String settingsFile;
private String vmName;
private String osTypeId;
private String vmId;
private String controllerIDE;
private boolean forceOverwrite;
private ComputeServiceContext context;
private String hostId;
private String guestId;
private Credentials credentials;
private VirtualBoxManager manager;
private String adminDisk;
private String diskFormat;
private String settingsFile;
private String vmName;
private String osTypeId;
private String vmId;
private String controllerIDE;
private boolean forceOverwrite;
private ComputeServiceContext context;
private String hostId;
private String guestId;
private Credentials credentials;
@Inject
public IsoToIMachine(VirtualBoxManager manager,
String adminDisk,
String diskFormat,
String settingsFile,
String vmName,
String osTypeId,
String vmId,
boolean forceOverwrite,
String controllerIDE,
ComputeServiceContext context,
String hostId,
String guestId,
Credentials credentials) {
super();
this.manager = manager;
this.adminDisk = adminDisk;
this.diskFormat = diskFormat;
this.settingsFile = settingsFile;
this.vmName = vmName;
this.osTypeId = osTypeId;
this.vmId = vmId;
this.controllerIDE = controllerIDE;
this.forceOverwrite = forceOverwrite;
this.context = context;
this.hostId = hostId;
this.guestId = guestId;
this.credentials = credentials;
}
@Inject
public IsoToIMachine(VirtualBoxManager manager, String adminDisk, String diskFormat, String settingsFile,
String vmName, String osTypeId, String vmId, boolean forceOverwrite, String controllerIDE,
ComputeServiceContext context, String hostId, String guestId, Credentials credentials) {
super();
this.manager = manager;
this.adminDisk = adminDisk;
this.diskFormat = diskFormat;
this.settingsFile = settingsFile;
this.vmName = vmName;
this.osTypeId = osTypeId;
this.vmId = vmId;
this.controllerIDE = controllerIDE;
this.forceOverwrite = forceOverwrite;
this.context = context;
this.hostId = hostId;
this.guestId = guestId;
this.credentials = credentials;
}
@Override
public IMachine apply(@Nullable String isoName) {
@Override
public IMachine apply(@Nullable String isoName) {
String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080");
String basebaseResource = ".";
Server server = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource);
IMachine vm = manager.getVBox().createMachine(settingsFile, vmName, osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(vm);
String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080");
String baseResource = ".";
Server server = new StartJettyIfNotAlreadyRunning(port).apply(baseResource);
String defaultWorkingDir = System.getProperty("user.home") + "/jclouds-virtualbox-test";
String workingDir = System.getProperty(VIRTUALBOX_WORKINGDIR, defaultWorkingDir);
IMedium distroMedium = manager.getVBox().openMedium(workingDir + "/" + isoName, DVD, ReadOnly, forceOverwrite);
IMachine vm = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(settingsFile, osTypeId, vmId, forceOverwrite, manager).apply(vmName);
// Change RAM
Long memorySize = new Long(1024);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, Write);
IMachine mutable = session.getMachine();
mutable.setMemorySize(memorySize);
mutable.saveSettings();
session.unlockMachine();
String defaultWorkingDir = System.getProperty("user.home") + "/jclouds-virtualbox-test";
String workingDir = System.getProperty(VIRTUALBOX_WORKINGDIR, defaultWorkingDir);
// IDE Controller
machine.lockMachine(session, Write);
mutable = session.getMachine();
mutable.addStorageController(controllerIDE, StorageBus.IDE);
mutable.saveSettings();
session.unlockMachine();
// Change RAM
ensureMachineHasMemory(vmName, 1024l);
// DISK
String adminDiskPath = workingDir + "/" + adminDisk;
if (new File(adminDiskPath).exists()) {
new File(adminDiskPath).delete();
}
IMedium hd = manager.getVBox().createHardDisk(diskFormat, adminDiskPath);
long size = 4L * 1024L * 1024L * 1024L - 4L;
IProgress storageCreation = hd.createBaseStorage(size, (long) MediumVariant.STANDARD.ordinal());
storageCreation.waitForCompletion(-1);
// IDE Controller
ensureMachineHasIDEControllerNamed(vmName, controllerIDE);
machine.lockMachine(session, Write);
mutable = session.getMachine();
mutable.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
mutable.saveSettings();
session.unlockMachine();
// Distribution medium
ensureMachineHasAttachedDistroMedium(isoName, workingDir, controllerIDE);
// Create and attach hard disk
machine.lockMachine(session, Write);
mutable = session.getMachine();
mutable.attachDevice(controllerIDE, 0, 1, DeviceType.HardDisk, hd);
mutable.saveSettings();
session.unlockMachine();
// DISK
String adminDiskPath = workingDir + "/" + adminDisk;
if (new File(adminDiskPath).exists()) {
new File(adminDiskPath).delete();
}
// NIC
machine.lockMachine(session, Write);
mutable = session.getMachine();
// Create hard disk
IMedium hardDisk = new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath);
// NAT
mutable.getNetworkAdapter(0l).setAttachmentType(NAT);
machine.getNetworkAdapter(0l)
.getNatDriver()
.addRedirect("guestssh", TCP, "127.0.0.1", 2222, "", 22);
mutable.getNetworkAdapter(0l).setEnabled(true);
mutable.saveSettings();
session.unlockMachine();
// Attach hard disk to machine
ensureMachineHasHardDiskAttached(vmName, hardDisk);
String guestAdditionsDvd = workingDir + "/VBoxGuestAdditions_4.1.2.iso";
IMedium guestAdditionsDvdMedium = manager.getVBox().openMedium(guestAdditionsDvd, DeviceType.DVD, AccessMode.ReadOnly, forceOverwrite);
machine.lockMachine(session, Write);
mutable = session.getMachine();
mutable.attachDevice(controllerIDE, 1, 1, DeviceType.DVD, guestAdditionsDvdMedium);
mutable.saveSettings();
session.unlockMachine();
// NAT
ensureNATNetworkingIsAppliedToMachine(vmName);
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
propagate(e);
}
String guestAdditionsDvd = workingDir + "/VBoxGuestAdditions_4.1.2.iso";
final IMedium guestAdditionsDvdMedium = manager.getVBox().openMedium(guestAdditionsDvd, DeviceType.DVD,
AccessMode.ReadOnly, forceOverwrite);
String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence());
sendKeyboardSequence(installKeySequence);
session.unlockMachine();
// Guest additions
ensureGuestAdditionsMediumIsAttached(vmName, guestAdditionsDvdMedium);
boolean sshDeamonIsRunning = false;
while (!sshDeamonIsRunning) {
try {
if (runScriptOnNode(guestId, "id", wrapInInitScript(false)).getExitCode() == 0) {
logger.debug("Got response from ssh daemon.");
sshDeamonIsRunning = true;
}
} catch (SshException e) {
logger.debug("No response from ssh daemon...");
}
}
IProgress prog = vm.launchVMProcess(manager.getSessionObject(), "gui", "");
prog.waitForCompletion(-1);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
propagate(e);
}
logger.debug("Installation of image complete. Powering down...");
String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence());
sendKeyboardSequence(installKeySequence);
machine.lockMachine(session, LockType.Shared);
IProgress powerDownProgress = session.getConsole().powerDown();
powerDownProgress.waitForCompletion(-1);
session.unlockMachine();
boolean sshDeamonIsRunning = false;
while (!sshDeamonIsRunning) {
try {
if (runScriptOnNode(guestId, "id", wrapInInitScript(false)).getExitCode() == 0) {
logger.debug("Got response from ssh daemon.");
sshDeamonIsRunning = true;
}
} catch (SshException e) {
logger.debug("No response from ssh daemon...");
}
}
try {
logger.debug("Stopping Jetty server...");
server.stop();
logger.debug("Jetty server stopped.");
} catch (Exception e) {
logger.error(e, "Could not stop Jetty server.");
}
return vm;
}
logger.debug("Installation of image complete. Powering down...");
lockSessionOnMachineAndApply(manager, Shared, vmName, new Function<ISession, Void>() {
private String defaultInstallSequence() {
return "<Esc><Esc><Enter> "
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us "
+ "hostname="
+ vmName
+ " "
+ "fb=false debconf/frontend=noninteractive "
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
+ "initrd=/install/initrd.gz -- <Enter>";
}
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
private void sendKeyboardSequence(String keyboardSequence) {
String[] sequenceSplited = keyboardSequence.split(" ");
StringBuilder sb = new StringBuilder();
for (String line : sequenceSplited) {
String converted = stringToKeycode(line);
for (String word : converted.split(" ")) {
sb.append("vboxmanage controlvm " + vmName
+ " keyboardputscancode " + word + "; ");
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Enter>"))) {
runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false));
sb.delete(0, sb.length() - 1);
}
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Return>"))) {
runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false));
sb.delete(0, sb.length() - 1);
}
});
try {
logger.debug("Stopping Jetty server...");
server.stop();
logger.debug("Jetty server stopped.");
} catch (Exception e) {
logger.error(e, "Could not stop Jetty server.");
}
return vm;
}
}
}
}
private void ensureGuestAdditionsMediumIsAttached(String vmName, final IMedium guestAdditionsDvdMedium) {
lockMachineAndApply(manager, Write, vmName,
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, guestAdditionsDvdMedium, 1, 1, DeviceType.DVD));
}
private String stringToKeycode(String s) {
StringBuilder keycodes = new StringBuilder();
if (s.startsWith("<")) {
String[] specials = s.split("<");
for (int i = 1; i < specials.length; i++) {
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get("<" + specials[i]) + " ");
}
return keycodes.toString();
}
private void ensureMachineHasHardDiskAttached(String vmName, IMedium hardDisk) {
lockMachineAndApply(manager, Write, vmName,
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, 0, 1, HardDisk));
}
int i = 0;
while (i < s.length()) {
String digit = s.substring(i, i + 1);
String hex = KeyboardScancodes.NORMAL_KEYBOARD_BUTTON_MAP
.get(digit);
keycodes.append(hex + " ");
if (i != 0 && i % 14 == 0)
keycodes.append(" ");
i++;
}
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get("<Spacebar>") + " ");
private void ensureMachineHasMemory(String vmName, final long memorySize) {
lockMachineAndApply(manager, Write, vmName, new ApplyMemoryToMachine(memorySize));
}
return keycodes.toString();
}
private void ensureNATNetworkingIsAppliedToMachine(String vmName) {
lockMachineAndApply(manager, Write, vmName, new AttachNATRedirectRuleToMachine(0l));
}
protected ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) {
return context.getComputeService().runScriptOnNode(nodeId, command, options);
}
private void ensureMachineHasAttachedDistroMedium(String isoName, String workingDir, String controllerIDE) {
final String pathToIsoFile = checkFileExists(workingDir + "/" + isoName);
final IMedium distroMedium = manager.getVBox().openMedium(pathToIsoFile, DVD, ReadOnly, forceOverwrite);
lockMachineAndApply(manager, Write, vmName,
new AttachDistroMediumToMachine(
checkNotNull(controllerIDE, "controllerIDE"),
checkNotNull(distroMedium, "distroMedium")));
}
public static String checkFileExists(String filePath) {
if (new File(filePath).exists()) {
return filePath;
}
throw new IllegalStateException("File " + filePath + " does not exist.");
}
public void ensureMachineHasIDEControllerNamed(String vmName, String controllerIDE) {
lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"),
new AddIDEControllerIfNotExists(checkNotNull(controllerIDE, "controllerIDE")));
}
public static <T> T lockMachineAndApply(VirtualBoxManager manager, final LockType type, final String machineId,
final Function<IMachine, T> function) {
return lockSessionOnMachineAndApply(manager, type, machineId, new Function<ISession, T>() {
@Override
public T apply(ISession session) {
return function.apply(session.getMachine());
}
@Override
public String toString() {
return function.toString();
}
});
}
public static <T> T lockSessionOnMachineAndApply(VirtualBoxManager manager, LockType type, String machineId,
Function<ISession, T> function) {
try {
ISession session = manager.getSessionObject();
IMachine immutableMachine = manager.getVBox().findMachine(machineId);
immutableMachine.lockMachine(session, type);
try {
return function.apply(session);
} finally {
session.unlockMachine();
}
} catch (VBoxException e) {
throw new RuntimeException(String.format("error applying %s to %s with %s lock: %s", function, machineId,
type, e.getMessage()), e);
}
}
private String defaultInstallSequence() {
return "<Esc><Esc><Enter> "
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " "
+ "fb=false debconf/frontend=noninteractive "
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
+ "initrd=/install/initrd.gz -- <Enter>";
}
private void sendKeyboardSequence(String keyboardSequence) {
String[] sequenceSplited = keyboardSequence.split(" ");
StringBuilder sb = new StringBuilder();
for (String line : sequenceSplited) {
String converted = stringToKeycode(line);
for (String word : converted.split(" ")) {
sb.append("vboxmanage controlvm " + vmName + " keyboardputscancode " + word + "; ");
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Enter>"))) {
runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false));
sb.delete(0, sb.length() - 1);
}
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Return>"))) {
runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false));
sb.delete(0, sb.length() - 1);
}
}
}
}
private String stringToKeycode(String s) {
StringBuilder keycodes = new StringBuilder();
if (s.startsWith("<")) {
String[] specials = s.split("<");
for (int i = 1; i < specials.length; i++) {
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<" + specials[i]) + " ");
}
return keycodes.toString();
}
int i = 0;
while (i < s.length()) {
String digit = s.substring(i, i + 1);
String hex = KeyboardScancodes.NORMAL_KEYBOARD_BUTTON_MAP.get(digit);
keycodes.append(hex + " ");
if (i != 0 && i % 14 == 0)
keycodes.append(" ");
i++;
}
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Spacebar>") + " ");
return keycodes.toString();
}
protected ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) {
return context.getComputeService().runScriptOnNode(nodeId, command, options);
}
}

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions.admin;

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions.admin;

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions.admin;

View File

@ -19,16 +19,20 @@
package org.jclouds.virtualbox.compute;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import java.net.URI;
import java.util.Map;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.inject.Guice;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule;
import org.jclouds.location.suppliers.JustProvider;
import org.jclouds.net.IPSocket;
import org.jclouds.ssh.SshClient;
@ -40,21 +44,28 @@ import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import java.net.URI;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
@Test(groups = "live", singleThreaded = true, testName = "VirtualBoxComputeServiceAdapterLiveTest")
public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClientLiveTest {
private VirtualBoxComputeServiceAdapter adapter;
private IMachine machine;
private final Map<OsFamily, Map<String, String>> osVersionMap = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class));
@BeforeGroups(groups = { "live" })
@BeforeGroups(groups = {"live"})
public void setupClient() {
super.setupClient();
adapter = new VirtualBoxComputeServiceAdapter(getManager(),
new JustProvider(ImmutableSet.<String> of(), provider, URI.create(endpoint)));
final VirtualBoxManager manager = getManager();
Function<IMachine, Image> iMachineToImage = new IMachineToImage(manager, osVersionMap);
adapter = new VirtualBoxComputeServiceAdapter(manager,
new JustProvider(provider, URI.create(endpoint), ImmutableSet.<String>of()), iMachineToImage);
}
protected VirtualBoxManager getManager() {
@ -78,7 +89,7 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien
// check other things, like cpu correct, mem correct, image/os is correct
// (as possible)
assert credentialStore.containsKey("node#" + machine.getId()) : "credentials to log into machine not found "
+ machine;
+ machine;
// TODO: what's the IP address?
// assert InetAddresses.isInetAddress(machine.getPrimaryBackendIpAddress()) : machine;
doConnectViaSsh(machine, credentialStore.get("node#" + machine.getId()));
@ -86,7 +97,7 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien
protected void doConnectViaSsh(IMachine machine, Credentials creds) {
SshClient ssh = context.utils().sshFactory()
.create(new IPSocket("//TODO", 22), creds);
.create(new IPSocket("//TODO", 22), creds);
try {
ssh.connect();
ExecResponse hello = ssh.exec("echo hello");
@ -106,6 +117,7 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien
assertFalse(Iterables.isEmpty(profiles));
// check state;
}
@Test
public void testListImages() {
Iterable<Image> iMageIterable = adapter.listImages();

View File

@ -0,0 +1,93 @@
/**
* 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.virtualbox.compute;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.inject.Guice;
import org.easymock.EasyMock;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image;
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.location.suppliers.JustProvider;
import org.jclouds.virtualbox.functions.IMachineToImage;
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.VirtualBoxManager;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.easymock.classextension.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
import static org.testng.Assert.assertEquals;
@Test(groups = "unit")
public class VirtualBoxComputeServiceAdapterTest {
Map<OsFamily, Map<String, String>> osMap = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class));
@Test
public void testListImages() throws Exception {
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
JustProvider justProvider = createNiceMock(JustProvider.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
IGuestOSType osType = createNiceMock(IGuestOSType.class);
List<IMachine> machines = new ArrayList<IMachine>();
IMachine imageMachine = createNiceMock(IMachine.class);
IMachine clonedMachine = createNiceMock(IMachine.class);
machines.add(imageMachine);
machines.add(clonedMachine);
expect(clonedMachine.getName()).andReturn("My Linux Node");
expect(clonedMachine.getDescription()).andReturn("My Linux Node");
expect(imageMachine.getName()).andReturn(VIRTUALBOX_IMAGE_PREFIX + "ubuntu-10.04");
expect(imageMachine.getDescription()).andReturn(VIRTUALBOX_IMAGE_PREFIX + "ubuntu-10.04");
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.getMachines()).andReturn(machines).anyTimes();
expect(vBox.getGuestOSType(EasyMock.<String>anyObject())).andReturn(osType).anyTimes();
expect(osType.getDescription()).andReturn("Ubuntu 10.04").anyTimes();
expect(osType.getIs64Bit()).andReturn(true).anyTimes();
replay(manager, justProvider, vBox, clonedMachine, imageMachine, osType);
Function<IMachine, Image> iMachineToImage = new IMachineToImage(manager, osMap);
VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(manager, justProvider, iMachineToImage);
Iterator<Image> iterator = adapter.listImages().iterator();
Image image = Iterators.getOnlyElement(iterator);
assertEquals(image.getDescription(), VIRTUALBOX_IMAGE_PREFIX + "ubuntu-10.04");
}
}

View File

@ -1,3 +1,22 @@
/**
* 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.virtualbox.compute;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
@ -21,7 +40,7 @@ import com.google.common.collect.ImmutableSet;
* @author Andrea Turli
*/
@Test(groups = "live")
@Test(groups = "live", testName = "VirtualBoxTemplateBuilderLiveTest")
public class VirtualBoxTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {
public VirtualBoxTemplateBuilderLiveTest() {
@ -36,14 +55,7 @@ public class VirtualBoxTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTe
public boolean apply(OsFamilyVersion64Bit input) {
switch (input.family) {
case UBUNTU:
return !(input.version.startsWith("11") || input.version.equals("8.04")) && input.is64Bit;
case DEBIAN:
return !(input.version.equals("6.0")) && input.is64Bit;
case CENTOS:
return !(input.version.matches("5.[023]") || input.version.equals("8.04")) && input.is64Bit;
case WINDOWS:
return input.version.equals("2008 SP2") || input.version.equals("")
|| (input.version.equals("2008 R2") && input.is64Bit);
return input.version.equals("11.04") && !input.is64Bit;
default:
return false;
}
@ -54,8 +66,9 @@ public class VirtualBoxTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTe
@Test
public void testTemplateBuilder() {
System.out.println(this.context.getComputeService().listImages());
Template defaultTemplate = this.context.getComputeService().templateBuilder().build();
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), false);
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "10.04");
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);

View File

@ -0,0 +1,91 @@
/**
* 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.virtualbox.functions;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IStorageController;
import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VBoxException;
/**
*
* @author Adrian Cole
*
*/
@Test(groups = "unit", testName = "AddIDEControllerIfNotExistsTest")
public class AddIDEControllerIfNotExistsTest {
@Test
public void testFine() throws Exception {
IMachine vm = createMock(IMachine.class);
String controllerName = "IDE Controller";
expect(vm.addStorageController(controllerName, StorageBus.IDE)).andReturn(
createNiceMock(IStorageController.class));
vm.saveSettings();
replay(vm);
new AddIDEControllerIfNotExists(controllerName).apply(vm);
verify(vm);
}
@Test
public void testAcceptableException() throws Exception {
IMachine vm = createMock(IMachine.class);
String controllerName = "IDE Controller";
expect(vm.addStorageController(controllerName, StorageBus.IDE)).andThrow(
new VBoxException(createNiceMock(Throwable.class),
"VirtualBox error: Storage controller named 'IDE Controller' already exists (0x80BB000C)"));
replay(vm);
new AddIDEControllerIfNotExists(controllerName).apply(vm);
verify(vm);
}
@Test(expectedExceptions = VBoxException.class)
public void testUnacceptableException() throws Exception {
IMachine vm = createMock(IMachine.class);
String controllerName = "IDE Controller";
expect(vm.addStorageController(controllerName, StorageBus.IDE)).andThrow(
new VBoxException(createNiceMock(Throwable.class), "VirtualBox error: General Error"));
replay(vm);
new AddIDEControllerIfNotExists(controllerName).apply(vm);
verify(vm);
}
}

View File

@ -0,0 +1,68 @@
/*
* 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.virtualbox.functions;
import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.VBoxException;
import static org.easymock.classextension.EasyMock.*;
/**
* @author Mattias Holmqvist
*/
@Test(groups = "unit", testName = "ApplyMemoryToMachineTest")
public class ApplyMemoryToMachineTest {
@Test
public void testSetRAMSizeSuccessful() throws Exception {
long memorySize = 1024l;
IMachine machine = createMock(IMachine.class);
machine.setMemorySize(memorySize);
machine.saveSettings();
replay(machine);
new ApplyMemoryToMachine(memorySize).apply(machine);
verify(machine);
}
@Test(expectedExceptions = VBoxException.class)
public void testRethrowInvalidRamSizeError() throws Exception {
// Mainly here for documentation purposes
final String error = "VirtualBox error: Invalid RAM size: " +
"3567587327 MB (must be in range [4, 2097152] MB) (0x80070057)";
long memorySize = 1024l;
IMachine machine = createMock(IMachine.class);
VBoxException invalidRamSizeException = new VBoxException(createNiceMock(Throwable.class), error);
machine.setMemorySize(memorySize);
expectLastCall().andThrow(invalidRamSizeException);
machine.saveSettings();
replay(machine);
new ApplyMemoryToMachine(memorySize).apply(machine);
}
}

View File

@ -0,0 +1,106 @@
/**
* 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.virtualbox.functions;
import org.testng.annotations.Test;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.VBoxException;
import static org.easymock.classextension.EasyMock.*;
/**
* @author Mattias Holmqvist
*/
@Test(groups = "unit", testName = "AttachDistroMediumToMachineTest")
public class AttachDistroMediumToMachineTest {
@Test
public void testAttachDistroMedium() throws Exception {
String controllerIDE = "IDE Controller";
IMedium distroMedium = createNiceMock(IMedium.class);
IMachine machine = createMock(IMachine.class);
machine.saveSettings();
machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
replay(machine, distroMedium);
new AttachDistroMediumToMachine(controllerIDE, distroMedium).apply(machine);
verify(machine);
}
@Test
public void testAcceptAlreadyAttachedDistroMedium() throws Exception {
String controllerIDE = "IDE Controller";
IMedium distroMedium = createNiceMock(IMedium.class);
IMachine machine = createNiceMock(IMachine.class);
final StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("VirtualBox error: ");
errorBuilder.append("Medium '/Users/johndoe/jclouds-virtualbox-test/ubuntu-11.04-server-i386.iso' ");
errorBuilder.append("is already attached to port 0, device 0 of controller 'IDE Controller' ");
errorBuilder.append("of this virtual machine (0x80BB000C)");
String isoAlreadyAttachedException = errorBuilder.toString();
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
expectLastCall().andThrow(isoAttachedException);
replay(machine, distroMedium);
new AttachDistroMediumToMachine(controllerIDE, distroMedium).apply(machine);
verify(machine);
}
@Test(expectedExceptions = VBoxException.class)
public void testFailOnOtherVBoxErrors() throws Exception {
String controllerIDE = "IDE Controller";
IMedium distroMedium = createNiceMock(IMedium.class);
IMachine machine = createNiceMock(IMachine.class);
final StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("VirtualBox error: ");
errorBuilder.append("Some other VBox error");
String isoAlreadyAttachedException = errorBuilder.toString();
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
expectLastCall().andThrow(isoAttachedException);
replay(machine, distroMedium);
new AttachDistroMediumToMachine(controllerIDE, distroMedium).apply(machine);
}
}

View File

@ -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.virtualbox.functions;
import org.testng.annotations.Test;
import org.virtualbox_4_1.*;
import static org.easymock.classextension.EasyMock.*;
import static org.virtualbox_4_1.DeviceType.HardDisk;
/**
* @author Mattias Holmqvist
*/
@Test(groups = "unit", testName = "AttachMediumToMachineIfNotAlreadyAttachedTest")
public class AttachMediumToMachineIfNotAlreadyAttachedTest {
@Test
public void testAttachHardDiskIfNotAttached() throws Exception {
String controllerIDE = "IDE Controller";
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
String diskFormat = "vdi";
int controllerPort = 0;
int device = 1;
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createNiceMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(hardDisk);
expect(hardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk);
machine.saveSettings();
replay(manager, machine, vBox, hardDisk);
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk).apply(machine);
verify(machine);
}
@Test
public void testDoNothingIfAlreadyAttachedAttachHardDisk() throws Exception {
String controllerIDE = "IDE Controller";
int controllerPort = 0;
int device = 1;
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createNiceMock(IMedium.class);
final StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("VirtualBox error: ");
errorBuilder.append("Medium '/Users/mattias/jclouds-virtualbox-test/testadmin.vdi' ");
errorBuilder.append("is already attached to port 0, device 1 of controller 'IDE Controller' ");
errorBuilder.append("of this virtual machine (0x80BB000C)");
String isoAlreadyAttachedException = errorBuilder.toString();
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk);
expectLastCall().andThrow(isoAttachedException);
replay(manager, machine, vBox, hardDisk);
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk).apply(machine);
verify(machine);
}
@Test(expectedExceptions = VBoxException.class)
public void testFailOnOtherVBoxError() throws Exception {
String controllerIDE = "IDE Controller";
int controllerPort = 0;
int device = 1;
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createNiceMock(IMedium.class);
final StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("VirtualBox error: ");
errorBuilder.append("Some other VBox error");
String isoAlreadyAttachedException = errorBuilder.toString();
VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException);
machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk);
expectLastCall().andThrow(isoAttachedException);
replay(manager, machine, vBox, hardDisk);
new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk).apply(machine);
}
}

View File

@ -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.virtualbox.functions;
import org.testng.annotations.Test;
import org.virtualbox_4_1.*;
import static org.easymock.classextension.EasyMock.*;
import static org.virtualbox_4_1.NATProtocol.TCP;
import static org.virtualbox_4_1.NetworkAttachmentType.NAT;
/**
* @author Mattias Holmqvist
*/
@Test(groups = "unit", testName = "AttachNATRedirectRuleToMachineTest")
public class AttachNATRedirectRuleToMachineTest {
@Test
public void testApplyNetworkingToNonExistingAdapter() throws Exception {
Long adapterId = 0l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
expect(machine.getNetworkAdapter(adapterId)).andReturn(networkAdapter);
networkAdapter.setAttachmentType(NAT);
expect(networkAdapter.getNatDriver()).andReturn(natEngine);
natEngine.addRedirect("guestssh", TCP, "127.0.0.1", 2222, "", 22);
networkAdapter.setEnabled(true);
machine.saveSettings();
replay(machine, networkAdapter, natEngine);
new AttachNATRedirectRuleToMachine(adapterId).apply(machine);
verify(machine, networkAdapter, natEngine);
}
@Test(expectedExceptions = VBoxException.class)
public void testRethrowInvalidAdapterSlotException() throws Exception {
Long adapterId = 30l;
IMachine machine = createMock(IMachine.class);
INetworkAdapter networkAdapter = createMock(INetworkAdapter.class);
INATEngine natEngine = createMock(INATEngine.class);
String error = "VirtualBox error: Argument slot is invalid " +
"(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)";
VBoxException invalidSlotException = new VBoxException(createNiceMock(Throwable.class), error);
expect(machine.getNetworkAdapter(adapterId)).andThrow(invalidSlotException);
replay(machine, networkAdapter, natEngine);
new AttachNATRedirectRuleToMachine(adapterId).apply(machine);
verify(machine, networkAdapter, natEngine);
}
}

View File

@ -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.virtualbox.functions;
import org.easymock.EasyMock;
import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import static org.easymock.EasyMock.anyBoolean;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.*;
/**
* @author Mattias Holmqvist
*/
@Test(groups = "unit", testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest")
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
@Test
public void testCreateIfNotAlreadyExists() throws Exception {
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
String vmName = "jclouds-image-my-ubuntu-image";
IMachine createdMachine = createMock(IMachine.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.append("VirtualBox error: Could not find a registered machine named ");
errorMessageBuilder.append("'jclouds-image-virtualbox-iso-to-machine-test' (0x80BB0001)");
String errorMessage = errorMessageBuilder.toString();
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
vBox.findMachine(vmName);
expectLastCall().andThrow(vBoxException);
expect(vBox.createMachine(anyString(), eq(vmName), anyString(), anyString(), anyBoolean())).andReturn(createdMachine).anyTimes();
vBox.registerMachine(createdMachine);
replay(manager, vBox);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("", "", "", false, manager).apply(vmName);
verify(manager, vBox);
}
@Test(expectedExceptions = IllegalStateException.class)
public void testFailIfMachineIsAlreadyRegistered() throws Exception {
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
String vmName = "jclouds-image-my-ubuntu-image";
IMachine registeredMachine = createMock(IMachine.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMachine(vmName)).andReturn(registeredMachine).anyTimes();
replay(manager, vBox);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("", "", "", false, manager).apply(vmName);
}
@Test(expectedExceptions = VBoxException.class)
public void testFailIfOtherVBoxExceptionIsThrown() throws Exception {
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
String vmName = "jclouds-image-my-ubuntu-image";
String errorMessage = "VirtualBox error: Soem other VBox error";
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
vBox.findMachine(vmName);
expectLastCall().andThrow(vBoxException);
replay(manager, vBox);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("", "", "", false, manager).apply(vmName);
}
private String anyString() {
return EasyMock.<String>anyObject();
}
}

View File

@ -0,0 +1,141 @@
/**
* 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.virtualbox.functions;
import org.testng.annotations.Test;
import org.virtualbox_4_1.*;
import static org.easymock.EasyMock.anyLong;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.*;
import static org.testng.Assert.assertNotSame;
/**
* @author Mattias Holmqvist
*/
public class CreateMediumIfNotAlreadyExistsTest {
@Test
public void testCreateMediumWhenDiskDoesNotExists() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
String diskFormat = "vdi";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class);
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("org.virtualbox_4_1.VBoxException: VirtualBox error: ");
errorBuilder.append("Could not find an open hard disk with location ");
errorBuilder.append("'/Users/johndoe/jclouds-virtualbox-test/testadmin.vdi' (0x80BB0001)");
String errorMessage = errorBuilder.toString();
expect(manager.getVBox()).andReturn(vBox).anyTimes();
VBoxException notFoundException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andThrow(notFoundException);
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(hardDisk);
expect(hardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, hardDisk);
new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath);
verify(machine, vBox);
}
@Test
public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwrite() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
String diskFormat = "vdi";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class);
IMedium newHardDisk = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(hardDisk);
expect(hardDisk.deleteStorage()).andReturn(progress);
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(newHardDisk);
expect(newHardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, hardDisk, newHardDisk, progress);
IMedium newDisk = new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath);
verify(machine, vBox, hardDisk);
assertNotSame(newDisk, hardDisk);
}
@Test(expectedExceptions = IllegalStateException.class)
public void testFailWhenMediumExistsAndNotUsingOverwrite() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
String diskFormat = "vdi";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class);
IMedium newHardDisk = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(hardDisk);
replay(manager, machine, vBox, hardDisk, newHardDisk, progress);
new CreateMediumIfNotAlreadyExists(manager, diskFormat, false).apply(adminDiskPath);
}
@Test(expectedExceptions = VBoxException.class)
public void testFailOnOtherVBoxException() throws Exception {
String adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
String diskFormat = "vdi";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium hardDisk = createMock(IMedium.class);
IProgress progress = createNiceMock(IProgress.class);
String errorMessage = "VirtualBox error: Some other VBox error";
expect(manager.getVBox()).andReturn(vBox).anyTimes();
VBoxException notFoundException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andThrow(notFoundException);
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(hardDisk);
expect(hardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, hardDisk);
new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath);
}
}

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions;

View File

@ -1,36 +1,24 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions;
import com.google.common.base.Function;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OsFamily;
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.VirtualBoxManager;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createNiceMock;
@ -38,14 +26,34 @@ import static org.easymock.classextension.EasyMock.replay;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Map;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image;
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.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.VirtualBoxManager;
import com.google.inject.Guice;
@Test(groups = "unit")
public class IMachineToImageTest {
Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class));
@Test
public void testConvert() throws Exception {
VirtualBoxManager vbm = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox= createNiceMock(IVirtualBox.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
IMachine vm = createNiceMock(IMachine.class);
IGuestOSType guestOsType = createNiceMock(IGuestOSType.class);
String linuxDescription = "Ubuntu 10.04";
@ -59,7 +67,7 @@ public class IMachineToImageTest {
replay(vbm, vBox, vm, guestOsType);
IMachineToImage fn = new IMachineToImage(vbm);
IMachineToImage fn = new IMachineToImage(vbm, map);
Image image = fn.apply(vm);
@ -72,20 +80,41 @@ public class IMachineToImageTest {
}
@Test
public void testOsVersion() throws Exception {
public void testConvert1() throws Exception {
String osDescription = "Ubuntu 10.04";
VirtualBoxManager vbm = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
IMachine vm = createNiceMock(IMachine.class);
IGuestOSType guestOsType = createNiceMock(IGuestOSType.class);
String guestOsDescription = "ubuntu 11.04 server (i386)";
String vmDescription = "ubuntu-11.04-server-i386";
expect(vbm.getVBox()).andReturn(vBox).anyTimes();
Function<String, String> iMachineStringFunction = IMachineToImage.osVersion();
assertEquals("10.04", iMachineStringFunction.apply(osDescription));
expect(vm.getOSTypeId()).andReturn("os-type").anyTimes();
expect(vBox.getGuestOSType(eq("os-type"))).andReturn(guestOsType);
expect(vm.getDescription()).andReturn(vmDescription).anyTimes();
expect(guestOsType.getDescription()).andReturn(guestOsDescription).anyTimes();
expect(guestOsType.getIs64Bit()).andReturn(true);
replay(vbm, vBox, vm, guestOsType);
IMachineToImage fn = new IMachineToImage(vbm, map);
Image image = fn.apply(vm);
assertEquals(image.getDescription(), vmDescription);
assertEquals(image.getOperatingSystem().getDescription(), guestOsDescription);
assertTrue(image.getOperatingSystem().is64Bit());
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getOperatingSystem().getVersion(), "11.04");
}
@Test
public void testUnparseableOsString() throws Exception {
VirtualBoxManager vbm = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox= createNiceMock(IVirtualBox.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
IMachine vm = createNiceMock(IMachine.class);
IGuestOSType guestOsType = createNiceMock(IGuestOSType.class);
@ -100,12 +129,11 @@ public class IMachineToImageTest {
replay(vbm, vBox, vm, guestOsType);
Image image = new IMachineToImage(vbm).apply(vm);
Image image = new IMachineToImage(vbm, map).apply(vm);
assertEquals(image.getOperatingSystem().getDescription(), "SomeOtherOs 2.04");
assertEquals(image.getOperatingSystem().getVersion(), "");
}
}

View File

@ -19,7 +19,9 @@
package org.jclouds.virtualbox.functions;
import com.google.common.collect.ImmutableSet;
import java.util.Map;
import java.util.Set;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Credentials;
@ -29,8 +31,7 @@ import org.testng.annotations.Test;
import org.virtualbox_4_1.MachineState;
import org.virtualbox_4_1.VirtualBoxManager;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
//@Test(groups = "live")
public class IMachineToNodeMetadataTest {
@ -49,7 +50,7 @@ public class IMachineToNodeMetadataTest {
IMachineToNodeMetadata parser = new IMachineToNodeMetadata();
IMachineToHardware hwParser = new IMachineToHardware(manager);
// hwParser.apply()
// hwParser.apply()
}
}

View File

@ -1,22 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions;
@ -30,25 +28,35 @@ import static com.google.common.collect.Iterables.any;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.inject.Guice;
@Test(groups = "live", singleThreaded = true, testName = "IsoToIMachineLiveTest")
public class IsoToIMachineLiveTest extends BaseVirtualBoxClientLiveTest {
Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class));
private String settingsFile = null;
private boolean forceOverwrite = true;
private String vmId = "jclouds-image-1";
private String vmId = "jclouds-image-iso-1";
private String osTypeId = "";
private String controllerIDE = "IDE Controller";
private String diskFormat = "";
@ -83,8 +91,9 @@ public class IsoToIMachineLiveTest extends BaseVirtualBoxClientLiveTest {
guestId,
new Credentials("toor", "password")).apply("ubuntu-11.04-server-i386.iso");
IMachineToImage iMachineToImage = new IMachineToImage(manager);
IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
Image newImage = iMachineToImage.apply(imageMachine);
//TODO add the description to the cache of the images or serialize to YAML the image desc
Set<? extends Image> images = context.getComputeService().listImages();
assertTrue(any(images, equalTo(newImage)));

View File

@ -8,53 +8,47 @@ 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.virtualbox.BaseVirtualBoxClientLiveTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
/**
*
* 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.
*
*
* @author Andrea Turli
*/
public class ImageFromYamlStreamTest extends BaseVirtualBoxClientLiveTest {
public static final Image TEST1 = new ImageBuilder()
.id("myTestId")
.name("ubuntu-11.04-server-i386")
.description("ubuntu 11.04 server (i386)")
.operatingSystem(OperatingSystem.builder()
.description("ubuntu")
.family(OsFamily.LINUX)
.version("11.04")
.build())
.build();
*
* 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.
*
*
* @author Andrea Turli
*/
@Test(groups = "unit")
public class ImageFromYamlStreamTest {
@Test
public void testNodesParse() throws Exception {
InputStream is = getClass().getResourceAsStream("/testImages.yaml");
ImageFromYamlStream parser = new ImageFromYamlStream();
assertEquals(parser.apply(is).asMap(), ImmutableMap.of(TEST1.getId(), TEST1));
is.close();
}
public static final Image TEST1 = new ImageBuilder()
.id("myTestId")
.name("ubuntu-11.04-server-i386")
.description("ubuntu 11.04 server (i386)")
.operatingSystem(
OperatingSystem.builder().description("ubuntu").family(OsFamily.UBUNTU).version("11.04").build())
.build();
@Test
public void testNodesParse() throws Exception {
InputStream is = getClass().getResourceAsStream("/testImages.yaml");
ImageFromYamlStream parser = new ImageFromYamlStream();
assertEquals(parser.apply(is).asMap(), ImmutableMap.of(TEST1.getId(), TEST1));
is.close();
}
}

View File

@ -1,23 +1,20 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions.admin;

View File

@ -1,24 +1,21 @@
/*
* *
* * 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.
/**
* 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.virtualbox.functions.admin;
import org.jclouds.compute.ComputeServiceContext;

View File

@ -3,7 +3,7 @@ images:
name: ubuntu-11.04-server-i386
description: ubuntu 11.04 server (i386)
os_arch: x86
os_family: linux
os_family: ubuntu
os_description: ubuntu
os_version: 11.04
iso: http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso

View File

@ -35,6 +35,7 @@ import org.jclouds.scriptbuilder.domain.StatementList;
import org.jclouds.scriptbuilder.statements.ssh.SshStatements;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
@ -46,17 +47,26 @@ import com.google.inject.ImplementedBy;
* Controls the administrative access to a node. By default, it will perform the following:
*
* <ul>
* <li>setup a new admin user which folks should use as opposed to the built-in vcloud account</li>
* <ul>
* <li>associate a random password to account</li>
* <ul>
* <li>securely ( use sha 512 on client side and literally rewrite the shadow entry, rather than
* pass password to OS in a script )</li>
* <li>setup a new admin user which folks should use as opposed to any built-in account</li>
* <ul>
* <li>associate a random (or given) password to that account
* <ul>
* <li>securely (using sha 512 on client side and literally rewriting the shadow entry,
* rather than sending password plaintext to OS in a script)</li>
* <li>but note password access is often blocked in any case, see below</li>
* </ul>
* <li>associate the users' ssh public key with the account for login</li>
* <li>associate it with the os group wheel</li>
* </ul>
* <li>set up sudoers for password-less access to root for this user (shouldGrantSudo)</li>
* <ul>
* <li>creating os group wheel and assigning the new admin user to it</li>
* <li>create (overwriting) sudoers file to grant root access for wheel members</li>
* </ul>
* <li>reset password for the user logging in (e.g. root, because root password is
* sometimes known to the provider), securely and randomly as described above (resetLoginPassword)</li>
* <li>lockdown sshd_config for no root login, nor passwords allowed (lockSsh)</li>
* </ul>
* <li>associate the users' ssh public key with the account for login</li> <li>
* associate it with the os group wheel</li> </ul> <li>create os group wheel</li> <li>add sudoers
* for nopassword access to root by group wheel</li> <li>reset root password securely</li> <li>
* lockdown sshd_config for no root login, nor passwords allowed</li> </ul>
*
* @author Adrian Cole
*/
@ -335,6 +345,8 @@ public class AdminAccess implements Statement {
if (family == OsFamily.WINDOWS)
throw new UnsupportedOperationException("windows not yet implemented");
checkNotNull(config.getAdminUsername(), "adminUsername");
Preconditions.checkArgument(!"root".equals(config.getAdminUsername()), "cannot create admin user 'root'; " +
"ensure jclouds is not running as root, or specify an explicit non-root username in AdminAccess");
checkNotNull(config.getAdminPassword(), "adminPassword");
checkNotNull(config.getAdminPublicKey(), "adminPublicKey");
checkNotNull(config.getAdminPrivateKey(), "adminPrivateKey");

View File

@ -51,9 +51,9 @@ public class DefaultConfiguration implements Configuration {
@Override
public Map<String, String> get() {
try {
return ImmutableMap.of("public",
Files.toString(new File(System.getProperty("user.home") + "/.ssh/id_rsa.pub"), UTF_8), "private",
Files.toString(new File(System.getProperty("user.home") + "/.ssh/id_rsa"), UTF_8));
return ImmutableMap.of(
"public", Files.toString(new File(System.getProperty("user.home") + "/.ssh/id_rsa.pub"), UTF_8),
"private", Files.toString(new File(System.getProperty("user.home") + "/.ssh/id_rsa"), UTF_8));
} catch (IOException e) {
return SshKeys.generate();
}

View File

@ -43,6 +43,13 @@ import com.google.common.collect.Lists;
import com.google.inject.Inject;
/**
* Creates a statement that will add a given user to a machine ("login"), with optional
* password, groups, private key, and authorized keys.
* <p>
* This is supported on most *nix environments. Not currently supported on Windows.
* <p>
* Note that some places where this is used may have stricter requirements on the parameters
* (for example {@link AdminAccess} requires password and keys).
*
* @author Adrian Cole
*/
@ -65,11 +72,13 @@ public class UserAdd implements Statement {
return this;
}
/** the username of the user to add (not the login to use when performing the add) */
public UserAdd.Builder login(String login) {
this.login = login;
return this;
}
/** the password to add for the user (not the password to use when logging in to perform the add) */
public UserAdd.Builder password(String password) {
this.password = password;
return this;

View File

@ -76,4 +76,16 @@ public class AdminAccessTest {
public void testCreateWheelWindowsNotSupported() {
AdminAccess.standard().init(TestConfiguration.INSTANCE).render(OsFamily.WINDOWS);
}
@Test(expectedExceptions=IllegalArgumentException.class)
//for issue 682
public void testRootNotAllowed() throws IOException {
TestConfiguration.INSTANCE.reset();
try {
AdminAccess.builder().adminUsername("root").build().init(TestConfiguration.INSTANCE).render(OsFamily.UNIX);
} finally {
TestConfiguration.INSTANCE.reset();
}
}
}