Issue 100: get and metadata support

git-svn-id: http://jclouds.googlecode.com/svn/trunk@1971 3d8758e0-26b5-11de-8745-db77d3ebf521
This commit is contained in:
adrian.f.cole 2009-10-12 06:05:38 +00:00
parent 9c3dcdf495
commit 99cc328996
14 changed files with 407 additions and 35 deletions

View File

@ -51,7 +51,7 @@ public interface SDNAuthentication {
@GET @GET
@ResponseParser(ParseSessionTokenFromJsonResponse.class) @ResponseParser(ParseSessionTokenFromJsonResponse.class)
@Path("/Authentication/Login.ashx") @Path("/ws/Authentication/Login.ashx")
String authenticate(@QueryParam(SDNQueryParams.APPKEY) String appKey, String authenticate(@QueryParam(SDNQueryParams.APPKEY) String appKey,
@QueryParam(SDNQueryParams.USERNAME) String user, @QueryParam(SDNQueryParams.USERNAME) String user,
@QueryParam(SDNQueryParams.PASSWORD) String password); @QueryParam(SDNQueryParams.PASSWORD) String password);

View File

@ -39,10 +39,12 @@ import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.nirvanix.sdn.binders.BindMetadataToQueryParams; import org.jclouds.nirvanix.sdn.binders.BindMetadataToQueryParams;
import org.jclouds.nirvanix.sdn.domain.UploadInfo; import org.jclouds.nirvanix.sdn.domain.UploadInfo;
import org.jclouds.nirvanix.sdn.filters.AddSessionTokenToRequest; import org.jclouds.nirvanix.sdn.filters.AddSessionTokenToRequest;
import org.jclouds.nirvanix.sdn.filters.InsertUserContextIntoPath;
import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse; import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse;
import org.jclouds.nirvanix.sdn.reference.SDNQueryParams; import org.jclouds.nirvanix.sdn.reference.SDNQueryParams;
import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.OverrideRequestFilters;
import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.ResponseParser;
@ -58,9 +60,9 @@ import com.google.common.collect.Multimap;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Endpoint(SDN.class) @Endpoint(SDN.class)
@QueryParams(keys = SDNQueryParams.OUTPUT, values = "json")
@RequestFilters(AddSessionTokenToRequest.class) @RequestFilters(AddSessionTokenToRequest.class)
@SkipEncoding( { '/', ':' }) @SkipEncoding( { '/', ':' })
@QueryParams(keys = SDNQueryParams.OUTPUT, values = "json")
public interface SDNConnection { public interface SDNConnection {
/** /**
@ -68,7 +70,7 @@ public interface SDNConnection {
* to. It returns the host to upload to and an Upload Token that will be used to authenticate. * to. It returns the host to upload to and an Upload Token that will be used to authenticate.
*/ */
@GET @GET
@Path("/IMFS/GetStorageNode.ashx") @Path("/ws/IMFS/GetStorageNode.ashx")
@ResponseParser(ParseUploadInfoFromJsonResponse.class) @ResponseParser(ParseUploadInfoFromJsonResponse.class)
UploadInfo getStorageNode(@QueryParam(SDNQueryParams.DESTFOLDERPATH) String folderPath, UploadInfo getStorageNode(@QueryParam(SDNQueryParams.DESTFOLDERPATH) String folderPath,
@QueryParam(SDNQueryParams.SIZEBYTES) long size); @QueryParam(SDNQueryParams.SIZEBYTES) long size);
@ -84,7 +86,7 @@ public interface SDNConnection {
* The SetMetadata method is used to set specified metadata for a file or folder. * The SetMetadata method is used to set specified metadata for a file or folder.
*/ */
@PUT @PUT
@Path("/Metadata/SetMetadata.ashx") @Path("/ws/Metadata/SetMetadata.ashx")
@QueryParams(keys = SDNQueryParams.PATH, values = "{path}") @QueryParams(keys = SDNQueryParams.PATH, values = "{path}")
Future<Void> setMetadata(@PathParam("path") String path, Future<Void> setMetadata(@PathParam("path") String path,
@BinderParam(BindMetadataToQueryParams.class) Multimap<String, String> metadata); @BinderParam(BindMetadataToQueryParams.class) Multimap<String, String> metadata);
@ -93,7 +95,17 @@ public interface SDNConnection {
* The GetMetadata method is used to retrieve all metadata from a file or folder. * The GetMetadata method is used to retrieve all metadata from a file or folder.
*/ */
@GET @GET
@Path("/Metadata/GetMetadata.ashx") @Path("/ws/Metadata/GetMetadata.ashx")
@QueryParams(keys = SDNQueryParams.PATH, values = "{path}") @QueryParams(keys = SDNQueryParams.PATH, values = "{path}")
Future<String> getMetadata(@PathParam("path") String path); Future<String> getMetadata(@PathParam("path") String path);
/**
* Get the contents of a file
*/
@GET
@Path("/{path}")
@OverrideRequestFilters
@RequestFilters(InsertUserContextIntoPath.class)
Future<String> getFile(@PathParam("path") String path);
} }

View File

@ -45,9 +45,14 @@ import com.google.inject.TypeLiteral;
*/ */
public class SDNContextBuilder extends CloudContextBuilder<SDNConnection> { public class SDNContextBuilder extends CloudContextBuilder<SDNConnection> {
public SDNContextBuilder(String apikey, String id, String secret) { public SDNContextBuilder(String apikey, String appname, String password) {
this(new Properties()); this(new Properties());
authenticate(this, apikey, id, secret); authenticate(this, apikey, appname, appname, password);
}
public SDNContextBuilder(String apikey, String appname, String username, String password) {
this(new Properties());
authenticate(this, apikey, appname, username, password);
} }
public SDNContextBuilder(Properties props) { public SDNContextBuilder(Properties props) {
@ -61,19 +66,21 @@ public class SDNContextBuilder extends CloudContextBuilder<SDNConnection> {
addAuthenticationModule(this); addAuthenticationModule(this);
} }
public static void authenticate(SDNContextBuilder builder, String appkey, String id, public static void authenticate(SDNContextBuilder builder, String appkey, String appname,
String secret) { String username, String password) {
builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_APPKEY, builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_APPKEY,
checkNotNull(appkey, "appkey")); checkNotNull(appkey, "appkey"));
builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_APPNAME,
checkNotNull(appname, "appname"));
builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_USERNAME, builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_USERNAME,
checkNotNull(id, "user")); checkNotNull(username, "username"));
builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_PASSWORD, builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_PASSWORD,
checkNotNull(secret, "key")); checkNotNull(password, "password"));
} }
public static void initialize(SDNContextBuilder builder) { public static void initialize(SDNContextBuilder builder) {
builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_ENDPOINT, builder.getProperties().setProperty(SDNConstants.PROPERTY_SDN_ENDPOINT,
"http://services.nirvanix.com/ws"); "http://services.nirvanix.com");
} }
public static void addAuthenticationModule(SDNContextBuilder builder) { public static void addAuthenticationModule(SDNContextBuilder builder) {

View File

@ -0,0 +1,52 @@
package org.jclouds.nirvanix.sdn.filters;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpRequestFilter;
import org.jclouds.nirvanix.sdn.reference.SDNConstants;
import org.jclouds.rest.internal.GeneratedHttpRequest;
/**
* Adds the Session Token to the request. This will update the Session Token before 20 minutes is
* up.
*
* @author Adrian Cole
*
*/
@Singleton
public class InsertUserContextIntoPath implements HttpRequestFilter {
private final AddSessionTokenToRequest sessionManager;
private final String pathPrefix;
@Inject
public InsertUserContextIntoPath(AddSessionTokenToRequest sessionManager,
@Named(SDNConstants.PROPERTY_SDN_APPNAME) String appname,
@Named(SDNConstants.PROPERTY_SDN_USERNAME) String username) {
this.sessionManager = sessionManager;
this.pathPrefix = String.format("/%s/%s/", appname, username);
}
public void filter(HttpRequest request) throws HttpException {
checkArgument(checkNotNull(request, "input") instanceof GeneratedHttpRequest<?>,
"this decorator is only valid for GeneratedHttpRequests!");
String sessionToken = sessionManager.getSessionToken();
int prefixIndex = request.getEndpoint().getPath().indexOf(pathPrefix);
String path;
if (prefixIndex == -1) { // addToken
path = "/" + sessionToken + pathPrefix + request.getEndpoint().getPath().substring(1);
} else { // replace token
path = "/" + sessionToken + request.getEndpoint().getPath().substring(prefixIndex);
}
((GeneratedHttpRequest<?>) request).replacePath(path);
}
}

View File

@ -0,0 +1,72 @@
/**
*
* Copyright (C) 2009 Global Cloud Specialists, Inc. <info@globalcloudspecialists.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.nirvanix.sdn.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.jclouds.http.functions.ParseJson;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
/**
* This parses a Map of Metadata from a Nirvanix response
*
* @author Adrian Cole
*/
public class ParseMetadataFromJsonResponse extends ParseJson<Map<String, String>> {
@Inject
public ParseMetadataFromJsonResponse(Gson gson) {
super(gson);
}
private static class SessionTokenResponse {
Integer ResponseCode;
List<Map<String, String>> Metadata;
}
public Map<String, String> apply(InputStream stream) {
try {
SessionTokenResponse response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
SessionTokenResponse.class);
if (response.ResponseCode == null || response.ResponseCode != 0)
throw new RuntimeException("bad response code: " + response.ResponseCode);
Map<String, String> metadata = Maps.newHashMap();
for (Map<String, String> keyValue : response.Metadata) {
metadata.put(keyValue.get("Type"), keyValue.get("Value"));
}
return metadata;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -33,4 +33,5 @@ public interface SDNConstants {
public static final String PROPERTY_SDN_USERNAME = "jclouds.nirvanix.sdn.username"; public static final String PROPERTY_SDN_USERNAME = "jclouds.nirvanix.sdn.username";
public static final String PROPERTY_SDN_PASSWORD = "jclouds.nirvanix.sdn.password"; public static final String PROPERTY_SDN_PASSWORD = "jclouds.nirvanix.sdn.password";
public static final String PROPERTY_SDN_APPKEY = "jclouds.nirvanix.sdn.appkey"; public static final String PROPERTY_SDN_APPKEY = "jclouds.nirvanix.sdn.appkey";
public static final String PROPERTY_SDN_APPNAME = "jclouds.nirvanix.sdn.appname";
} }

View File

@ -51,7 +51,8 @@ import com.google.inject.Provides;
*/ */
@Test(groups = "live", testName = "sdn.SDNAuthenticationLiveTest") @Test(groups = "live", testName = "sdn.SDNAuthenticationLiveTest")
public class SDNAuthenticationLiveTest { public class SDNAuthenticationLiveTest {
String app = checkNotNull(System.getProperty("jclouds.test.app"), "jclouds.test.app"); String appname = checkNotNull(System.getProperty("jclouds.test.appname"), "jclouds.test.appname");
String appid = checkNotNull(System.getProperty("jclouds.test.appid"), "jclouds.test.appid");
String user = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user"); String user = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user");
String password = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key"); String password = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key");
@ -60,7 +61,7 @@ public class SDNAuthenticationLiveTest {
@Test @Test
public void testAuthentication() throws Exception { public void testAuthentication() throws Exception {
SDNAuthentication authentication = injector.getInstance(SDNAuthentication.class); SDNAuthentication authentication = injector.getInstance(SDNAuthentication.class);
String response = authentication.authenticate(app, user, password); String response = authentication.authenticate(appid, user, password);
assertNotNull(response); assertNotNull(response);
} }
@ -70,7 +71,7 @@ public class SDNAuthenticationLiveTest {
@Override @Override
protected void configure() { protected void configure() {
bind(URI.class).annotatedWith(SDN.class).toInstance( bind(URI.class).annotatedWith(SDN.class).toInstance(
URI.create("http://services.nirvanix.com/ws")); URI.create("http://services.nirvanix.com"));
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")

View File

@ -64,7 +64,7 @@ public class SDNAuthenticationTest {
HttpRequest httpMethod = processor.createRequest(method, HttpRequest httpMethod = processor.createRequest(method,
new Object[] { "apple", "foo", "bar" }); new Object[] { "apple", "foo", "bar" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/Authentication/Login.ashx"); assertEquals(httpMethod.getEndpoint().getPath(), "/ws/Authentication/Login.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), assertEquals(httpMethod.getEndpoint().getQuery(),
"output=json&password=bar&username=foo&appKey=apple"); "output=json&password=bar&username=foo&appKey=apple");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);

View File

@ -1,7 +1,7 @@
package org.jclouds.nirvanix.sdn; package org.jclouds.nirvanix.sdn;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.*;
import java.net.URI; import java.net.URI;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@ -16,9 +16,6 @@ import org.jclouds.nirvanix.sdn.domain.UploadInfo;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
/** /**
* Tests behavior of {@code SDNConnection} * Tests behavior of {@code SDNConnection}
* *
@ -35,12 +32,14 @@ public class SDNConnectionLiveTest {
@BeforeGroups(groups = { "live" }) @BeforeGroups(groups = { "live" })
public void setupConnection() { public void setupConnection() {
String app = checkNotNull(System.getProperty("jclouds.test.app"), "jclouds.test.app"); String appname = checkNotNull(System.getProperty("jclouds.test.appname"),
"jclouds.test.appname");
String appid = checkNotNull(System.getProperty("jclouds.test.appid"), "jclouds.test.appid");
String user = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user"); String user = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user");
String password = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key"); String password = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key");
connection = new SDNContextBuilder(app, user, password).withModules(new Log4JLoggingModule()) connection = new SDNContextBuilder(appid, appname, user, password).withModules(
.buildContext().getApi(); new Log4JLoggingModule()).buildContext().getApi();
} }
public void testUploadToken() throws InterruptedException, ExecutionException, TimeoutException { public void testUploadToken() throws InterruptedException, ExecutionException, TimeoutException {
@ -51,16 +50,17 @@ public class SDNConnectionLiveTest {
assertNotNull(uploadInfo.getToken()); assertNotNull(uploadInfo.getToken());
connection.upload(uploadInfo.getHost(), uploadInfo.getToken(), containerName, connection.upload(uploadInfo.getHost(), uploadInfo.getToken(), containerName,
new Blob<BlobMetadata>("key", "value")).get(30, TimeUnit.SECONDS); new Blob<BlobMetadata>("test.txt", "value")).get(30, TimeUnit.SECONDS);
String metadataS = connection.getMetadata(containerName + "/test.txt").get(30,
String metadataS = connection.getMetadata(containerName).get(30, TimeUnit.SECONDS); TimeUnit.SECONDS);
System.err.println(metadataS);
Multimap<String, String> metadata = ImmutableMultimap.of("chef", "sushi", "foo", "bar");
connection.setMetadata(containerName, metadata).get(30, TimeUnit.SECONDS);
metadataS = connection.getMetadata(containerName).get(30, TimeUnit.SECONDS);
System.err.println(metadataS); System.err.println(metadataS);
String content = connection.getFile(containerName + "/test.txt").get(30, TimeUnit.SECONDS);
assertEquals(content, "value");
// Multimap<String, String> metadata = ImmutableMultimap.of("chef", "sushi", "foo", "bar");
// connection.setMetadata(containerName+"/test.txt", metadata).get(30, TimeUnit.SECONDS);
} }
} }

View File

@ -44,10 +44,14 @@ import org.jclouds.http.functions.ReturnStringIf200;
import org.jclouds.http.functions.ReturnVoidIf2xx; import org.jclouds.http.functions.ReturnVoidIf2xx;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.nirvanix.sdn.filters.AddSessionTokenToRequest;
import org.jclouds.nirvanix.sdn.filters.InsertUserContextIntoPath;
import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse; import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse;
import org.jclouds.nirvanix.sdn.reference.SDNConstants;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.Jsr330;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -76,13 +80,15 @@ public class SDNConnectionTest {
GeneratedHttpRequest<?> httpMethod = processor.createRequest(method, new Object[] { GeneratedHttpRequest<?> httpMethod = processor.createRequest(method, new Object[] {
"adriansmovies", 734859264 }); "adriansmovies", 734859264 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/IMFS/GetStorageNode.ashx"); assertEquals(httpMethod.getEndpoint().getPath(), "/ws/IMFS/GetStorageNode.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), assertEquals(httpMethod.getEndpoint().getQuery(),
"output=json&sizeBytes=734859264&destFolderPath=adriansmovies"); "output=json&sizeBytes=734859264&destFolderPath=adriansmovies");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(RestAnnotationProcessor.getParserOrThrowException(method), assertEquals(RestAnnotationProcessor.getParserOrThrowException(method),
ParseUploadInfoFromJsonResponse.class); ParseUploadInfoFromJsonResponse.class);
assertEquals(httpMethod.getFilters().size(), 1);
assertEquals(httpMethod.getFilters().get(0).getClass(), AddSessionTokenToRequest.class);
} }
public void testUpload() throws SecurityException, NoSuchMethodException, IOException { public void testUpload() throws SecurityException, NoSuchMethodException, IOException {
@ -106,6 +112,8 @@ public class SDNConnectionTest {
BindBlobToMultipartFormTest.EXPECTS); BindBlobToMultipartFormTest.EXPECTS);
assertEquals(processor.createResponseParser(method, httpMethod).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
assertEquals(httpMethod.getFilters().size(), 1);
assertEquals(httpMethod.getFilters().get(0).getClass(), AddSessionTokenToRequest.class);
} }
public void testSetMetadata() throws SecurityException, NoSuchMethodException, IOException { public void testSetMetadata() throws SecurityException, NoSuchMethodException, IOException {
@ -114,7 +122,7 @@ public class SDNConnectionTest {
.createRequest(method, new Object[] { "adriansmovies/sushi.avi", .createRequest(method, new Object[] { "adriansmovies/sushi.avi",
ImmutableMultimap.of("Chef", "Kawasaki") }); ImmutableMultimap.of("Chef", "Kawasaki") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/Metadata/SetMetadata.ashx"); assertEquals(httpMethod.getEndpoint().getPath(), "/ws/Metadata/SetMetadata.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), assertEquals(httpMethod.getEndpoint().getQuery(),
"output=json&path=adriansmovies/sushi.avi&metadata=chef:Kawasaki"); "output=json&path=adriansmovies/sushi.avi&metadata=chef:Kawasaki");
assertEquals(httpMethod.getMethod(), HttpMethod.PUT); assertEquals(httpMethod.getMethod(), HttpMethod.PUT);
@ -124,6 +132,8 @@ public class SDNConnectionTest {
assertEquals(httpMethod.getEntity(), null); assertEquals(httpMethod.getEntity(), null);
assertEquals(processor.createResponseParser(method, httpMethod).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
assertEquals(httpMethod.getFilters().size(), 1);
assertEquals(httpMethod.getFilters().get(0).getClass(), AddSessionTokenToRequest.class);
} }
public void testGetMetadata() throws SecurityException, NoSuchMethodException, IOException { public void testGetMetadata() throws SecurityException, NoSuchMethodException, IOException {
@ -131,13 +141,31 @@ public class SDNConnectionTest {
GeneratedHttpRequest<SDNConnection> httpMethod = processor.createRequest(method, GeneratedHttpRequest<SDNConnection> httpMethod = processor.createRequest(method,
new Object[] { "adriansmovies/sushi.avi" }); new Object[] { "adriansmovies/sushi.avi" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/Metadata/GetMetadata.ashx"); assertEquals(httpMethod.getEndpoint().getPath(), "/ws/Metadata/GetMetadata.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), "output=json&path=adriansmovies/sushi.avi"); assertEquals(httpMethod.getEndpoint().getQuery(), "output=json&path=adriansmovies/sushi.avi");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(httpMethod.getEntity(), null); assertEquals(httpMethod.getEntity(), null);
assertEquals(processor.createResponseParser(method, httpMethod).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnStringIf200.class); ReturnStringIf200.class);
assertEquals(httpMethod.getFilters().size(), 1);
assertEquals(httpMethod.getFilters().get(0).getClass(), AddSessionTokenToRequest.class);
}
public void testGetFile() throws SecurityException, NoSuchMethodException, IOException {
Method method = SDNConnection.class.getMethod("getFile", String.class);
GeneratedHttpRequest<SDNConnection> httpMethod = processor.createRequest(method,
new Object[] { "adriansmovies/sushi.avi" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/adriansmovies/sushi.avi");
assertEquals(httpMethod.getEndpoint().getQuery(), "output=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(httpMethod.getEntity(), null);
assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnStringIf200.class);
assertEquals(httpMethod.getFilters().size(), 1);
assertEquals(httpMethod.getFilters().get(0).getClass(), InsertUserContextIntoPath.class);
} }
@BeforeClass @BeforeClass
@ -152,6 +180,12 @@ public class SDNConnectionTest {
return Logger.NULL; return Logger.NULL;
} }
}); });
bindConstant().annotatedWith(Jsr330.named(SDNConstants.PROPERTY_SDN_APPKEY)).to(
"appKey");
bindConstant().annotatedWith(Jsr330.named(SDNConstants.PROPERTY_SDN_APPNAME)).to(
"appname");
bindConstant().annotatedWith(Jsr330.named(SDNConstants.PROPERTY_SDN_USERNAME)).to(
"username");
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")

View File

@ -0,0 +1,130 @@
/**
*
* Copyright (C) 2009 Global Cloud Specialists, Inc. <info@globalcloudspecialists.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.nirvanix.sdn.filters;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.testng.Assert.assertEquals;
import java.lang.reflect.Method;
import java.net.URI;
import javax.ws.rs.POST;
import javax.ws.rs.ext.RuntimeDelegate;
import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.nirvanix.sdn.reference.SDNConstants;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.rest.internal.RuntimeDelegateImpl;
import org.jclouds.util.Jsr330;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
@Test(groups = "unit", sequential = true, testName = "sdn.InsertUserContextIntoPathTest")
// sequential as easymock isn't threadsafe
public class InsertUserContextIntoPathTest {
private Injector injector;
private InsertUserContextIntoPath filter;
private RestAnnotationProcessor<TestService> factory;
private Method method;
private static interface TestService {
@POST
public void foo(@Endpoint URI endpoint);
}
public void testRequestInvalid() {
GeneratedHttpRequest<TestService> request = factory.createRequest(method, URI
.create("https://host/path"));
filter.filter(request);
filter.filter(request);
assertEquals(request.getEndpoint().getPath(), "/token/appname/username/path");
assertEquals(request.getEndpoint().getHost(), "host");
}
public void testRequestNoSession() {
GeneratedHttpRequest<TestService> request = factory.createRequest(method, URI
.create("https://host/path"));
filter.filter(request);
assertEquals(request.getEndpoint().getPath(), "/token/appname/username/path");
assertEquals(request.getEndpoint().getHost(), "host");
}
public void testRequestAlreadyHasSession() {
GeneratedHttpRequest<TestService> request = factory.createRequest(method, URI
.create("https://host/token/appname/username/path"));
filter.filter(request);
assertEquals(request.getEndpoint().getPath(), "/token/appname/username/path");
assertEquals(request.getEndpoint().getHost(), "host");
}
@BeforeClass
protected void createFilter() throws SecurityException, NoSuchMethodException {
injector = Guice.createInjector(new RestModule(), new ExecutorServiceModule(
new WithinThreadExecutorService()), new JavaUrlHttpCommandExecutorServiceModule(),
new AbstractModule() {
protected void configure() {
RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() {
public Logger getLogger(String category) {
return Logger.NULL;
}
});
AddSessionTokenToRequest sessionManager = createMock(AddSessionTokenToRequest.class);
expect(sessionManager.getSessionToken()).andReturn("token").anyTimes();
replay(sessionManager);
bind(AddSessionTokenToRequest.class).toInstance(sessionManager);
bindConstant().annotatedWith(Jsr330.named(SDNConstants.PROPERTY_SDN_APPKEY))
.to("appKey");
bindConstant().annotatedWith(Jsr330.named(SDNConstants.PROPERTY_SDN_USERNAME))
.to("username");
bindConstant().annotatedWith(Jsr330.named(SDNConstants.PROPERTY_SDN_APPNAME))
.to("appname");
}
});
filter = injector.getInstance(InsertUserContextIntoPath.class);
factory = injector.getInstance(Key
.get(new TypeLiteral<RestAnnotationProcessor<TestService>>() {
}));
method = TestService.class.getMethod("foo", URI.class);
}
}

View File

@ -0,0 +1,61 @@
/**
*
* Copyright (C) 2009 Global Cloud Specialists, Inc. <info@globalcloudspecialists.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.nirvanix.sdn.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Map;
import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.util.DateService;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code ParseMetadataFromJsonResponse}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "sdn.ParseMetadataFromJsonResponseTest")
public class ParseMetadataFromJsonResponseTest {
Injector i = Guice.createInjector(new ParserModule());
DateService dateService = new DateService();
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/metadata.json");
ParseMetadataFromJsonResponse parser = new ParseMetadataFromJsonResponse(i
.getInstance(Gson.class));
Map<String, String> response = parser.apply(is);
assertEquals(response, ImmutableMap.of("MD5","IGPBYI1uC6+AJJxC4r5YBA==","test","1"));
}
}

View File

@ -0,0 +1 @@
{"ResponseCode":0,"Metadata":[{"Type":"MD5","Value":"IGPBYI1uC6+AJJxC4r5YBA=="},{"Type":"test","Value":"1"}]}

View File

@ -42,7 +42,8 @@
<jclouds.test.initializer>org.jclouds.nirvanix.sdn.integration.SDNTestInitializer</jclouds.test.initializer> <jclouds.test.initializer>org.jclouds.nirvanix.sdn.integration.SDNTestInitializer</jclouds.test.initializer>
<jclouds.test.user>${jclouds.nirvanix.sdn.username}</jclouds.test.user> <jclouds.test.user>${jclouds.nirvanix.sdn.username}</jclouds.test.user>
<jclouds.test.key>${jclouds.nirvanix.sdn.password}</jclouds.test.key> <jclouds.test.key>${jclouds.nirvanix.sdn.password}</jclouds.test.key>
<jclouds.test.app>${jclouds.nirvanix.sdn.appkey}</jclouds.test.app> <jclouds.test.appname>${jclouds.nirvanix.sdn.appname}</jclouds.test.appname>
<jclouds.test.appid>${jclouds.nirvanix.sdn.appkey}</jclouds.test.appid>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>