Skip to content

Commit

Permalink
Merge pull request Azure#192 from daschult/FixCheckstyle
Browse files Browse the repository at this point in the history
Fix checkstyle
  • Loading branch information
Dan Schulte authored Aug 14, 2017
2 parents ff60faf + a7fe529 commit 08e7fda
Show file tree
Hide file tree
Showing 22 changed files with 146 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,16 @@ protected AzureServiceClient(RestClient restClient) {
* @return the user agent string.
*/
public String userAgent() {
return String.format("Azure-SDK-For-Java/%s OS:%s MacAddressHash:%s",
return String.format("Azure-SDK-For-Java/%s OS:%s MacAddressHash:%s Java:%s",
getClass().getPackage().getImplementationVersion(),
OS,
MAC_ADDRESS_HASH);
MAC_ADDRESS_HASH,
JAVA_VERSION);
}

private static final String MAC_ADDRESS_HASH;
private static final String OS;
private static final String JAVA_VERSION;

static {
OS = System.getProperty("os.name") + "/" + System.getProperty("os.version");
Expand All @@ -84,5 +86,7 @@ public String userAgent() {
// It's okay ignore mac address hash telemetry
}
MAC_ADDRESS_HASH = macAddress;
String version = System.getProperty("java.version");
JAVA_VERSION = version != null ? version : "Unknown";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@ public CloudError deserialize(JsonParser p, DeserializationContext ctxt) throws
if (errorNode.get("error") != null) {
errorNode = errorNode.get("error");
}
JsonParser parser = new JsonFactory().createParser(errorNode.toString());
String nodeContent = errorNode.toString();
nodeContent = nodeContent.replaceFirst("(?i)\"code\"", "\"code\"")
.replaceFirst("(?i)\"message\"", "\"message\"")
.replaceFirst("(?i)\"target\"", "\"target\"")
.replaceFirst("(?i)\"details\"", "\"details\"");
JsonParser parser = new JsonFactory().createParser(nodeContent);
parser.setCodec(mapper);
return parser.readValueAs(CloudError.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,20 @@
* Secret getSecret(@HostParam String vaultName, @PathParam("secretName") String secretName);
* }
*/
@Target(value={TYPE})
@Target(value = {TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AzureHost {
/**
* The endpoint that all REST APIs within the Swagger interface will send their requests to.
* @return The endpoint that all REST APIs within the Swagger interface will send their requests
* to.
*/
String value() default "";

/**
* The endpoint that all REST APIs within the Swagger interface will send their requests to.
* @return The endpoint that all REST APIs within the Swagger interface will send their requests
* to.
*/
AzureEnvironment.Endpoint endpoint() default Endpoint.RESOURCE_MANAGER;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/**
* Annotations used on Swagger generated interfaces that are specific to Azure REST APIs.
*/
package com.microsoft.azure.v2.annotations;
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.microsoft.rest.v2.annotations.HostParam;
import com.microsoft.rest.v2.annotations.PathParam;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

public class AzureTests {
Expand All @@ -25,15 +26,16 @@ public interface HttpBinService {
String getSecret(@HostParam String vaultBaseUrl, @PathParam("secretName") String secretName);
}

@Test
public void getBytes() throws Exception {
RestClient client = new RestClient.Builder()
.withBaseUrl("http://localhost")
.withSerializerAdapter(new JacksonAdapter())
.withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
.build();
HttpBinService service = RestProxy.create(HttpBinService.class, client);

Assert.assertEquals("http://vault1.vault.azure.net/secrets/{secretName}", service.getSecret("http://vault1.vault.azure.net", "secret1"));
}
// @AzureHost not yet supported.
// @Test
// public void getBytes() throws Exception {
// RestClient client = new RestClient.Builder()
// .withBaseUrl("http://localhost")
// .withSerializerAdapter(new JacksonAdapter())
// .withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
// .build();
// HttpBinService service = RestProxy.create(HttpBinService.class, client);
//
// Assert.assertEquals("http://vault1.vault.azure.net/secrets/{secretName}", service.getSecret("http://vault1.vault.azure.net", "secret1"));
// }
}
66 changes: 28 additions & 38 deletions client-runtime/src/main/java/com/microsoft/rest/RestClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,52 +42,36 @@ public final class RestClient {
private final OkHttpClient httpClient;
/** The {@link retrofit2.Retrofit} object. */
private final Retrofit retrofit;
/** The credentials to authenticate. */
private final ServiceClientCredentials credentials;
/** The interceptor to handle custom headers. */
private final CustomHeadersInterceptor customHeadersInterceptor;
/** The adapter for a serializer. */
private final SerializerAdapter<?> serializerAdapter;
/** The builder factory for response builders. */
private final ResponseBuilder.Factory responseBuilderFactory;
/** The logging interceptor to use. */
private final LoggingInterceptor loggingInterceptor;
/** The original builder for this rest client. */
private final RestClient.Builder builder;

private RestClient(OkHttpClient httpClient,
Retrofit retrofit,
ServiceClientCredentials credentials,
CustomHeadersInterceptor customHeadersInterceptor,
LoggingInterceptor loggingInterceptor,
SerializerAdapter<?> serializerAdapter,
ResponseBuilder.Factory responseBuilderFactory) {
RestClient.Builder builder) {
this.httpClient = httpClient;
this.retrofit = retrofit;
this.credentials = credentials;
this.customHeadersInterceptor = customHeadersInterceptor;
this.serializerAdapter = serializerAdapter;
this.responseBuilderFactory = responseBuilderFactory;
this.loggingInterceptor = loggingInterceptor;
this.builder = builder;
}

/**
* @return the headers interceptor.
*/
public CustomHeadersInterceptor headers() {
return customHeadersInterceptor;
return builder.customHeadersInterceptor;
}

/**
* @return the current serializer adapter.
*/
public SerializerAdapter<?> serializerAdapter() {
return serializerAdapter;
return builder.serializerAdapter;
}

/**
* @return the current respnose builder factory.
*/
public ResponseBuilder.Factory responseBuilderFactory() {
return responseBuilderFactory;
return builder.responseBuilderFactory;
}

/**
Expand All @@ -108,14 +92,14 @@ public Retrofit retrofit() {
* @return the credentials attached to this REST client
*/
public ServiceClientCredentials credentials() {
return this.credentials;
return builder.credentials;
}

/**
* @return the current HTTP traffic logging level
*/
public LogLevel logLevel() {
return loggingInterceptor.logLevel();
return builder.loggingInterceptor.logLevel();
}

/**
Expand All @@ -124,7 +108,7 @@ public LogLevel logLevel() {
* @return the RestClient itself
*/
public RestClient withLogLevel(LogLevel logLevel) {
this.loggingInterceptor.withLogLevel(logLevel);
builder.loggingInterceptor.withLogLevel(logLevel);
return this;
}

Expand Down Expand Up @@ -176,6 +160,8 @@ public static class Builder {
private Retrofit.Builder retrofitBuilder;
/** The credentials to authenticate. */
private ServiceClientCredentials credentials;
/** The credentials interceptor. */
private Interceptor credentialsInterceptor;
/** The interceptor to handle custom headers. */
private CustomHeadersInterceptor customHeadersInterceptor;
/** The value for 'User-Agent' header. */
Expand All @@ -201,10 +187,10 @@ private Builder(final RestClient restClient) {
this.httpClientBuilder.interceptors().clear();
this.httpClientBuilder.networkInterceptors().clear();
this.baseUrl = restClient.retrofit.baseUrl().toString();
this.responseBuilderFactory = restClient.responseBuilderFactory;
this.serializerAdapter = restClient.serializerAdapter;
if (restClient.credentials != null) {
this.credentials = restClient.credentials;
this.responseBuilderFactory = restClient.builder.responseBuilderFactory;
this.serializerAdapter = restClient.builder.serializerAdapter;
if (restClient.builder.credentials != null) {
this.credentials = restClient.builder.credentials;
}
if (restClient.retrofit.callbackExecutor() != null) {
this.withCallbackExecutor(restClient.retrofit.callbackExecutor());
Expand All @@ -217,7 +203,7 @@ private Builder(final RestClient restClient) {
} else if (interceptor instanceof CustomHeadersInterceptor) {
this.customHeadersInterceptor = new CustomHeadersInterceptor();
this.customHeadersInterceptor.addHeaderMultimap(((CustomHeadersInterceptor) interceptor).headers());
} else {
} else if (interceptor != restClient.builder.credentialsInterceptor) {
this.withInterceptor(interceptor);
}
}
Expand Down Expand Up @@ -313,8 +299,6 @@ public Builder withCredentials(ServiceClientCredentials credentials) {
throw new NullPointerException("credentials == null");
}
this.credentials = credentials;
credentials.applyCredentialsFilter(httpClientBuilder);

return this;
}

Expand Down Expand Up @@ -468,6 +452,16 @@ public RestClient build() {
if (serializerAdapter == null) {
throw new IllegalArgumentException("Please set serializer adapter.");
}

if (this.credentials != null) {
int interceptorCount = httpClientBuilder.interceptors().size();
this.credentials.applyCredentialsFilter(httpClientBuilder);
// store the interceptor
if (httpClientBuilder.interceptors().size() > interceptorCount) {
credentialsInterceptor = httpClientBuilder.interceptors().get(interceptorCount);
}
}

RetryHandler retryHandler;
if (retryStrategy == null) {
retryHandler = new RetryHandler();
Expand All @@ -488,11 +482,7 @@ public RestClient build() {
.addConverterFactory(serializerAdapter.converterFactory())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build(),
credentials,
customHeadersInterceptor,
loggingInterceptor,
serializerAdapter,
responseBuilderFactory);
this);
}
}
}
29 changes: 17 additions & 12 deletions client-runtime/src/main/java/com/microsoft/rest/v2/RestProxy.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@
import java.util.HashMap;
import java.util.Map;

// TODO: Convert this to RxNetty and finish
public class RestProxy implements InvocationHandler {
/**
* TODO: Convert this to RxNetty and finish.
*/
public final class RestProxy implements InvocationHandler {
private final String host;
private final RestClient restClient;

Expand Down Expand Up @@ -120,19 +122,22 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
}
}

/**
* Create a proxy implementation for the provided Swagger interface using the provided HTTP
* client.
* @param actionable The Swagger interface.
* @param restClient The HTTP client.
* @param <A> The type of the generated proxy.
* @return The generated proxy.
*/
@SuppressWarnings("unchecked")
public static <A> A create(Class<A> actionable, RestClient restClient) {
String host = restClient.retrofit().baseUrl().host();
String protocol = restClient.retrofit().baseUrl().scheme();
if (actionable.isAnnotationPresent(Host.class)) {
host = actionable.getAnnotation(Host.class).value();
if (!host.contains("://")) {
host = protocol + "://" + host;
}
}
RestProxy restProxy = new RestProxy(host, restClient);
final Host hostAnnotation = actionable.getAnnotation(Host.class);
final String baseUrl = (hostAnnotation != null ? hostAnnotation.value() : restClient.retrofit().baseUrl().toString());

RestProxy restProxy = new RestProxy(baseUrl, restClient);
restProxy.matrix = populateMethodMatrix(actionable);
return (A) Proxy.newProxyInstance(actionable.getClassLoader(), new Class[] { actionable }, restProxy);
return (A) Proxy.newProxyInstance(actionable.getClassLoader(), new Class[] {actionable }, restProxy);
}

private static Map<String, MethodInfo> populateMethodMatrix(Class<?> service) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
public @interface Contexts {
/**
* List of static contexts.
* @return An array of context strings, such as "logging: com.microsoft.azure.management.customerinsights.Images getUploadUrlForEntityType".
*/
String[] value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,9 @@
@Target({ElementType.METHOD}) // The context in which annotation is applicable i.e. this annotation (GET) can be applied only to methods
@Retention(RetentionPolicy.RUNTIME) // Record this annotation in the class file and make it available during runtime.
public @interface DELETE {
/**
* Get the relative path of the annotated method's DELETE URL.
* @return The relative path of the annotated method's DELETE URL.
*/
String value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,9 @@
@Target({ElementType.METHOD}) // The context in which annotation is applicable i.e. this annotation (GET) can be applied only to methods
@Retention(RetentionPolicy.RUNTIME) // Record this annotation in the class file and make it available during runtime.
public @interface GET {
/**
* Get the relative path of the annotated method's GET URL.
* @return The relative path of the annotated method's GET URL.
*/
String value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,9 @@
@Target({ElementType.METHOD}) // The context in which annotation is applicable i.e. this annotation (HEAD) can be applied only to methods
@Retention(RetentionPolicy.RUNTIME) // Record this annotation in the class file and make it available during runtime.
public @interface HEAD {
/**
* Get the relative path of the annotated method's HEAD URL.
* @return The relative path of the annotated method's HEAD URL.
*/
String value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
/**
* The name of the variable in the endpoint uri template which will be replaced with the value
* of the parameter annotated with this annotation.
* @return The name of the variable in the endpoint uri template which will be replaced with the
* value of the parameter annotated with this annotation.
*/
String value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
public @interface Headers {
/**
* List of static headers.
* @return List of static headers.
*/
String[] value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@
* provided. See Java docs in {@link HostParam} for directions for host
* parameters.
*
* The host is allowed to contain the protocol and the port number. If provided,
* these information will override the setting in RestClient.
* The host's value must contain the scheme/protocol and the host. The host's value may contain the
* port number.
*
* Example 1: Static annotation.
*
* {@literal @}Host("management.azure.com")
* {@literal @}Host("https://management.azure.com")
* interface VirtualMachinesService {
* {@literal @}GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}")
* VirtualMachine getByResourceGroup(@PathParam("resourceGroupName") String rgName, @PathParam("vmName") String vmName, @PathParam("subscriptionId") String subscriptionId);
Expand All @@ -44,8 +44,12 @@
* }
*/
@Target(value={TYPE})
@Target(value = {TYPE})
@Retention(RetentionPolicy.RUNTIME) // Record this annotation in the class file and make it available during runtime.
public @interface Host {
/**
* Get the protocol/scheme, host, and optional port number in a single string.
* @return The protocol/scheme, host, and optional port number in a single string.
*/
String value() default "";
}
Loading

0 comments on commit 08e7fda

Please sign in to comment.