com.microsoft.rest.protocol.SerializerAdapter Java Examples

The following examples show how to use com.microsoft.rest.protocol.SerializerAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AzureAsyncOperation.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Creates AzureAsyncOperation from the given HTTP response.
 *
 * @param serializerAdapter the adapter to use for deserialization
 * @param response the response
 * @return the async operation object
 * @throws CloudException if the deserialization fails or response contains invalid body
 */
static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {
    AzureAsyncOperation asyncOperation = null;
    String rawString = null;
    if (response.body() != null) {
        try {
            rawString = response.body().string();
            asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);
        } catch (IOException exception) {
            // Exception will be handled below
        } finally {
            response.body().close();
        }
    }
    if (asyncOperation == null || asyncOperation.status() == null) {
        throw new CloudException("polling response does not contain a valid body: " + rawString, response);
    }
    else {
        asyncOperation.rawString = rawString;
    }
    return asyncOperation;
}
 
Example #2
Source File: CloudErrorDeserializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void cloudErrorDeserialization() throws Exception {
    SerializerAdapter<ObjectMapper> serializerAdapter = new AzureJacksonAdapter();
    String bodyString =
        "{" +
        "    \"error\": {" +
        "        \"code\": \"BadArgument\"," +
        "        \"message\": \"The provided database ‘foo’ has an invalid username.\"," +
        "        \"target\": \"query\"," +
        "        \"details\": [" +
        "            {" +
        "                \"code\": \"301\"," +
        "                \"target\": \"$search\"," +
        "                \"message\": \"$search query option not supported\"" +
        "            }" +
        "        ]," +
        "        \"additionalInfo\": [" +
        "            {" +
        "                \"type\": \"SomeErrorType\"," +
        "                \"info\": {" +
        "                    \"someProperty\": \"SomeValue\"" +
        "                }" +
        "            }" +
        "        ]" +
        "    }" +
        "}";
    
    CloudError cloudError = serializerAdapter.deserialize(bodyString, CloudError.class);

    Assert.assertEquals("BadArgument", cloudError.code());
    Assert.assertEquals("The provided database ‘foo’ has an invalid username.", cloudError.message());
    Assert.assertEquals("query", cloudError.target());
    Assert.assertEquals(1, cloudError.details().size());
    Assert.assertEquals("301", cloudError.details().get(0).code());
    Assert.assertEquals(1, cloudError.additionalInfo().size());
    Assert.assertEquals("SomeErrorType", cloudError.additionalInfo().get(0).type());
    Assert.assertEquals("SomeValue", cloudError.additionalInfo().get(0).info().get("someProperty").asText());
}
 
Example #3
Source File: ResponseBuilderTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void throwOnGet404() {
    ResponseBuilder.Factory factory = new ResponseBuilder.Factory() {
        @Override
        public <T, E extends RestException> ResponseBuilder<T, E> newInstance(SerializerAdapter<?> serializerAdapter) {
            return new ServiceResponseBuilder.Factory().<T, E>newInstance(serializerAdapter)
                    .withThrowOnGet404(true);
        }
    };

    RestClient restClient = new RestClient.Builder()
            .withBaseUrl("https://microsoft.com/")
            .withSerializerAdapter(new JacksonAdapter())
            .withResponseBuilderFactory(factory)
            .withInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    return new Response.Builder()
                            .code(404)
                            .request(chain.request())
                            .protocol(Protocol.HTTP_1_1)
                            .message("not found")
                            .body(ResponseBody.create(MediaType.get("text/plain"), "{\"code\":\"NotFound\"}"))
                            .build();
                }
            })
            .build();
    try {
        retrofit2.Response<ResponseBody> response = restClient.retrofit().create(Service.class).get("https://microsoft.com/").toBlocking().single();
        ServiceResponse<String> sr = restClient.responseBuilderFactory().<String, RestException>newInstance(restClient.serializerAdapter())
                .register(200, new TypeToken<String>() { }.getType())
                .registerError(RestException.class)
                .build(response);
        fail();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof RestException);
        Assert.assertEquals("Status code 404, {\"code\":\"NotFound\"}", e.getMessage());
        Assert.assertEquals(404, ((RestException) e).response().code());
    }
}
 
Example #4
Source File: ServiceResponseBuilder.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Create a ServiceResponseBuilder instance.
 *
 * @param serializerAdapter the serialization utils to use for deserialization operations
 */
private ServiceResponseBuilder(SerializerAdapter<?> serializerAdapter) {
    this.serializerAdapter = serializerAdapter;
    this.responseTypes = new HashMap<>();
    this.exceptionType = RestException.class;
    this.responseTypes.put(0, Object.class);
    this.throwOnGet404 = false;
}
 
Example #5
Source File: SecretsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private SecretImpl wrapModel(SecretItem inner) {
    if (inner == null) {
        return null;
    }
    SerializerAdapter<?> serializer = vault.manager().inner().restClient().serializerAdapter();
    try {
        return wrapModel(serializer.<SecretBundle>deserialize(serializer.serialize(inner), SecretBundle.class));
    } catch (IOException e) {
        return null;
    }
}
 
Example #6
Source File: ActiveDirectoryGroupImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<ActiveDirectoryObject> listMembersAsync() {
    return manager().inner().groups().getGroupMembersAsync(id())
            .flatMap(new Func1<Page<AADObjectInner>, Observable<AADObjectInner>>() {
                @Override
                public Observable<AADObjectInner> call(Page<AADObjectInner> aadObjectInnerPage) {
                    return Observable.from(aadObjectInnerPage.items());
                }
            }).map(new Func1<AADObjectInner, ActiveDirectoryObject>() {
                @Override
                public ActiveDirectoryObject call(AADObjectInner aadObjectInner) {
                    SerializerAdapter<?> adapter = manager().inner().restClient().serializerAdapter();
                    try {
                        String serialized = adapter.serialize(aadObjectInner);
                        switch (aadObjectInner.objectType()) {
                            case "User":
                                return new ActiveDirectoryUserImpl(adapter.<UserInner>deserialize(serialized, UserInner.class), manager());
                            case "Group":
                                return new ActiveDirectoryGroupImpl(adapter.<ADGroupInner>deserialize(serialized, ADGroupInner.class), manager());
                            case "ServicePrincipal":
                                return new ServicePrincipalImpl(adapter.<ServicePrincipalInner>deserialize(serialized, ServicePrincipalInner.class), manager());
                            case "Application":
                                return new ActiveDirectoryApplicationImpl(adapter.<ApplicationInner>deserialize(serialized, ApplicationInner.class), manager());
                            default:
                                return null;
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
}
 
Example #7
Source File: AzureResponseBuilder.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
@Override
public <T, E extends RestException> AzureResponseBuilder<T, E> newInstance(final SerializerAdapter<?> serializerAdapter) {
    return new AzureResponseBuilder<T, E>(serializerAdapter);
}
 
Example #8
Source File: PollingState.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
/**
 * Creates a polling state.
 *
 * @param response the response from Retrofit REST call that initiate the long running operation.
 * @param lroOptions long running operation options.
 * @param defaultRetryTimeout the long running operation retry timeout.
 * @param resourceType the type of the resource the long running operation returns
 * @param serializerAdapter the adapter for the Jackson object mapper
 * @param <T> the result type
 * @return the polling state
 * @throws IOException thrown by deserialization
 */
public static <T> PollingState<T> create(Response<ResponseBody> response, LongRunningOperationOptions lroOptions, int defaultRetryTimeout, Type resourceType, SerializerAdapter<?> serializerAdapter) throws IOException {
    PollingState<T> pollingState = new PollingState<>();
    pollingState.initialHttpMethod = response.raw().request().method();
    pollingState.defaultRetryTimeout = defaultRetryTimeout;
    pollingState.withResponse(response);
    pollingState.resourceType = resourceType;
    pollingState.serializerAdapter = serializerAdapter;
    pollingState.loggingContext = response.raw().request().header(LOGGING_HEADER);
    pollingState.finalStateVia = lroOptions.finalStateVia();

    String responseContent = null;
    PollingResource resource = null;
    if (response.body() != null) {
        responseContent = response.body().string();
        response.body().close();
    }
    if (responseContent != null && !responseContent.isEmpty()) {
        pollingState.resource = serializerAdapter.deserialize(responseContent, resourceType);
        resource = serializerAdapter.deserialize(responseContent, PollingResource.class);
    }
    final int statusCode = pollingState.response.code();
    if (resource != null && resource.properties != null
            && resource.properties.provisioningState != null) {
        pollingState.withStatus(resource.properties.provisioningState, statusCode);
    } else {
        switch (statusCode) {
            case 202:
                pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);
                break;
            case 204:
            case 201:
            case 200:
                pollingState.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);
                break;
            default:
                pollingState.withStatus(AzureAsyncOperation.FAILED_STATUS, statusCode);
        }
    }
    return pollingState;
}
 
Example #9
Source File: KeyVaultClientCustomImpl.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Override
public SerializerAdapter<?> serializerAdapter() {
    return super.serializerAdapter();
}
 
Example #10
Source File: CloudErrorDeserializerTests.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
@Test
public void cloudErrorWithPolicyViolationDeserialization() throws Exception {
    SerializerAdapter<ObjectMapper> serializerAdapter = new AzureJacksonAdapter();
    String bodyString =
        "{" +
        "    \"error\": {" +
        "        \"code\": \"BadArgument\"," +
        "        \"message\": \"The provided database ‘foo’ has an invalid username.\"," +
        "        \"target\": \"query\"," +
        "        \"details\": [" +
        "        {" +
        "            \"code\": \"301\"," +
        "            \"target\": \"$search\"," +
        "            \"message\": \"$search query option not supported\"," +
        "            \"additionalInfo\": [" +
        "            {" +
        "                \"type\": \"PolicyViolation\"," +
        "                \"info\": {" +
        "                    \"policyDefinitionDisplayName\": \"Allowed locations\"," +
        "                    \"policyDefinitionId\": \"testDefinitionId\"," +
        "                    \"policyDefinitionName\": \"testDefinitionName\"," +
        "                    \"policyDefinitionEffect\": \"deny\"," +
        "                    \"policyAssignmentId\": \"testAssignmentId\"," +
        "                    \"policyAssignmentName\": \"testAssignmentName\"," +
        "                    \"policyAssignmentDisplayName\": \"test assignment\"," +
        "                    \"policyAssignmentScope\": \"/subscriptions/testSubId/resourceGroups/jilimpolicytest2\"," +
        "                    \"policyAssignmentParameters\": {" +
        "                        \"listOfAllowedLocations\": {" +
        "                            \"value\": [" +
        "                                \"westus\"" +
        "                	         ]" +
        "                    	 }" +
        "                    }" +            
        "                }" +
        "            }" +
        "            ]" +
        "        }" +
        "        ]," +
        "        \"additionalInfo\": [" +
        "            {" +
        "                \"type\": \"SomeErrorType\"," +
        "                \"info\": {" +
        "                    \"someProperty\": \"SomeValue\"" +
        "                }" +
        "            }" +
        "        ]" +
        "    }" +
        "}";
    
    CloudError cloudError = serializerAdapter.deserialize(bodyString, CloudError.class);

    Assert.assertEquals("BadArgument", cloudError.code());
    Assert.assertEquals("The provided database ‘foo’ has an invalid username.", cloudError.message());
    Assert.assertEquals("query", cloudError.target());
    Assert.assertEquals(1, cloudError.details().size());
    Assert.assertEquals("301", cloudError.details().get(0).code());
    Assert.assertEquals(1, cloudError.additionalInfo().size());
    Assert.assertEquals("SomeErrorType", cloudError.additionalInfo().get(0).type());
    Assert.assertEquals("SomeValue", cloudError.additionalInfo().get(0).info().get("someProperty").asText());
    Assert.assertEquals(1, cloudError.details().get(0).additionalInfo().size());
    Assert.assertTrue(cloudError.details().get(0).additionalInfo().get(0) instanceof PolicyViolation);
    
    PolicyViolation policyViolation = (PolicyViolation)cloudError.details().get(0).additionalInfo().get(0);
    
    Assert.assertEquals("PolicyViolation", policyViolation.type());
    Assert.assertEquals("Allowed locations", policyViolation.policyErrorInfo().getPolicyDefinitionDisplayName());
    Assert.assertEquals("westus", policyViolation.policyErrorInfo().getPolicyAssignmentParameters().get("listOfAllowedLocations").getValue().elements().next().asText());
}
 
Example #11
Source File: CloudErrorDeserializerTests.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
@Test
public void cloudErrorWitDifferentCasing() throws Exception {
    SerializerAdapter<ObjectMapper> serializerAdapter = new AzureJacksonAdapter();
    String bodyString =
        "{" +
        "    \"error\": {" +
        "        \"Code\": \"BadArgument\"," +
        "        \"Message\": \"The provided database ‘foo’ has an invalid username.\"," +
        "        \"Target\": \"query\"," +
        "        \"Details\": [" +
        "        {" +
        "            \"Code\": \"301\"," +
        "            \"Target\": \"$search\"," +
        "            \"Message\": \"$search query option not supported\"," +
        "            \"AdditionalInfo\": [" +
        "            {" +
        "                \"Type\": \"PolicyViolation\"," +
        "                \"Info\": {" +
        "                    \"PolicyDefinitionDisplayName\": \"Allowed locations\"," +
        "                    \"PolicyAssignmentParameters\": {" +
        "                        \"listOfAllowedLocations\": {" +
        "                            \"Value\": [" +
        "                                \"westus\"" +
        "                	         ]" +
        "                    	 }" +
        "                    }" +            
        "                }" +
        "            }" +
        "            ]" +
        "        }" +
        "        ]" +
        "    }" +
        "}";
    
    CloudError cloudError = serializerAdapter.deserialize(bodyString, CloudError.class);

    Assert.assertEquals("BadArgument", cloudError.code());
    Assert.assertEquals("The provided database ‘foo’ has an invalid username.", cloudError.message());
    Assert.assertEquals("query", cloudError.target());
    Assert.assertEquals(1, cloudError.details().size());
    Assert.assertEquals("301", cloudError.details().get(0).code());
    Assert.assertEquals(1, cloudError.details().get(0).additionalInfo().size());
    Assert.assertTrue(cloudError.details().get(0).additionalInfo().get(0) instanceof PolicyViolation);
    
    PolicyViolation policyViolation = (PolicyViolation)cloudError.details().get(0).additionalInfo().get(0);
    
    Assert.assertEquals("PolicyViolation", policyViolation.type());
    Assert.assertEquals("Allowed locations", policyViolation.policyErrorInfo().getPolicyDefinitionDisplayName());
    Assert.assertEquals("westus", policyViolation.policyErrorInfo().getPolicyAssignmentParameters().get("listOfAllowedLocations").getValue().elements().next().asText());
}
 
Example #12
Source File: AzureAsyncOperationDeserializerTests.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
@Test
public void DeserializeLROResult() throws IOException {
    SerializerAdapter<ObjectMapper> serializerAdapter = new AzureJacksonAdapter();

    String bodyString =
            "{"  +
            "        \"name\":\"1431219a-acad-4d70-9a17-f8b7a5a143cb\",\"status\":\"InProgress\"" +
            "}";

    AzureAsyncOperation asyncOperation = serializerAdapter.deserialize(bodyString, AzureAsyncOperation.class);

    Assert.assertEquals("InProgress", asyncOperation.status());
    Assert.assertEquals(null, asyncOperation.getError());

    Exception e = null;
     asyncOperation = null;
    bodyString =
            "{"  +
            "        \"name\":\"1431219a-acad-4d70-9a17-f8b7a5a143cb\",\"status\":\"InProgress\"," +
            "        \"error\":{" +
            "                  }" +
            "}";
    try {
        asyncOperation = serializerAdapter.deserialize(bodyString, AzureAsyncOperation.class);
    } catch (Exception ex) {
        e = ex;
    }

    Assert.assertNull(e);
    Assert.assertEquals("InProgress", asyncOperation.status());
    CloudError error = asyncOperation.getError();
    Assert.assertNotNull(error);
    Assert.assertNull(error.message());
    Assert.assertNull(error.code());

    asyncOperation = null;
    bodyString =
            "{"  +
            "        \"name\":\"1431219a-acad-4d70-9a17-f8b7a5a143cb\",\"status\":\"InProgress\"," +
            "        \"error\":{" +
            "                  \"code\":\"None\",\"message\":null,\"target\":\"e1a19fd1-8110-470a-a82f-9f789c2b2917\"" +
            "                  }" +
            "}";

    asyncOperation = serializerAdapter.deserialize(bodyString, AzureAsyncOperation.class);
    Assert.assertEquals("InProgress", asyncOperation.status());
    error = asyncOperation.getError();
    Assert.assertNotNull(error);
    Assert.assertEquals("None", error.code());
    Assert.assertNull(error.message());
    Assert.assertEquals("e1a19fd1-8110-470a-a82f-9f789c2b2917", error.target());
}
 
Example #13
Source File: ServiceClient.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
/**
 * @return the adapter to a Jackson {@link com.fasterxml.jackson.databind.ObjectMapper}.
 */
public SerializerAdapter<?> serializerAdapter() {
    return this.restClient.serializerAdapter();
}
 
Example #14
Source File: ServiceResponseBuilder.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
@Override
public <T, E extends RestException> ServiceResponseBuilder<T, E> newInstance(final SerializerAdapter<?> serializerAdapter) {
    return new ServiceResponseBuilder<T, E>(serializerAdapter);
}
 
Example #15
Source File: RestClient.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
/**
 * @return the current serializer adapter.
 */
public SerializerAdapter<?> serializerAdapter() {
    return builder.serializerAdapter;
}
 
Example #16
Source File: AzureResponseBuilder.java    From autorest-clientruntime-for-java with MIT License 2 votes vote down vote up
/**
 * Create a ServiceResponseBuilder instance.
 *
 * @param serializer the serialization utils to use for deserialization operations
 */
private AzureResponseBuilder(SerializerAdapter<?> serializer) {
    baseBuilder = new ServiceResponseBuilder.Factory().newInstance(serializer);
}
 
Example #17
Source File: PollingState.java    From autorest-clientruntime-for-java with MIT License 2 votes vote down vote up
/**
 * Sets the serializer adapter.
 *
 * @param serializerAdapter the serializer adapter.
 */
PollingState<T> withSerializerAdapter(SerializerAdapter<?> serializerAdapter) {
    this.serializerAdapter = serializerAdapter;
    return this;
}
 
Example #18
Source File: KeyVaultClientCustom.java    From azure-keyvault-java with MIT License 2 votes vote down vote up
/**
 * @return the adapter to a Jackson
 *         {@link com.fasterxml.jackson.databind.ObjectMapper}.
 */
SerializerAdapter<?> serializerAdapter();
 
Example #19
Source File: RestClient.java    From autorest-clientruntime-for-java with MIT License 2 votes vote down vote up
/**
 * Sets the serialization adapter.
 *
 * @param serializerAdapter the adapter to a serializer
 * @return the builder itself for chaining
 */
public Builder withSerializerAdapter(SerializerAdapter<?> serializerAdapter) {
    this.serializerAdapter = serializerAdapter;
    return this;
}