com.microsoft.rest.serializer.JacksonAdapter Java Examples

The following examples show how to use com.microsoft.rest.serializer.JacksonAdapter. 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: TestKubernetesCluster.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Parse azure auth to hashmap
 * @param authFilename the azure auth location
 * @return all fields in azure auth json
 * @throws Exception exception
 */
private static HashMap<String, String> ParseAuthFile(String authFilename) throws Exception {
    String content = Files.toString(new File(authFilename), Charsets.UTF_8).trim();
    HashMap<String, String> auth = new HashMap<>();
    if (isJsonBased(content)) {
        auth = new JacksonAdapter().deserialize(content, auth.getClass());
    } else {
        Properties authSettings = new Properties();
        FileInputStream credentialsFileStream = new FileInputStream(new File(authFilename));
        authSettings.load(credentialsFileStream);
        credentialsFileStream.close();

        for (final String authName: authSettings.stringPropertyNames()) {
            auth.put(authName, authSettings.getProperty(authName));
        }
    }
    return auth;
}
 
Example #2
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
@Test
public void canHandleComposedGenericPolymorphicTypeWithAndWithoutTypeId() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    //
    // -- Validate vector property
    //
    String serializedCollectionWithTypeId = "{\"turtlesSet2\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20 }]}";
    // de-serialization
    //
    ComposeTurtles composedTurtleDeserialized = adapter.deserialize(serializedCollectionWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet2());
    Assert.assertEquals(2, composedTurtleDeserialized.turtlesSet2().size());
    //
    Assert.assertTrue(composedTurtleDeserialized.turtlesSet2().get(0) instanceof TurtleWithTypeIdContainingDot);
    Assert.assertTrue(composedTurtleDeserialized.turtlesSet2().get(1) instanceof NonEmptyAnimalWithTypeIdContainingDot);
    //
    adapter.serialize(composedTurtleDeserialized);
}
 
Example #3
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
@Test
public void canHandleComposedSpecificPolymorphicTypeWithAndWithoutTypeId() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    //
    // -- Validate vector property
    //
    String serializedCollectionWithTypeId = "{\"turtlesSet1\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20 }]}";
    // de-serialization
    //
    ComposeTurtles composedTurtleDeserialized = adapter.deserialize(serializedCollectionWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet1());
    Assert.assertEquals(2, composedTurtleDeserialized.turtlesSet1().size());
    //
    adapter.serialize(composedTurtleDeserialized);
}
 
Example #4
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Validates decoding and encoding of a type with type id containing dot and no additional properties
 * For decoding and encoding base type will be used.
 *
 * @throws IOException
 */
@Test
public void canHandleTypeWithTypeIdContainingDotAndNoProperties() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();

    String rabbitSerialized = "{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}";
    String shelterSerialized = "{\"properties\":{\"animalsInfo\":[{\"animal\":{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}},{\"animal\":{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}}]}}";

    AnimalWithTypeIdContainingDot rabbitDeserialized = adapter.deserialize(rabbitSerialized, AnimalWithTypeIdContainingDot.class);
    Assert.assertTrue(rabbitDeserialized instanceof RabbitWithTypeIdContainingDot);
    Assert.assertNotNull(rabbitDeserialized);

    AnimalShelter shelterDeserialized = adapter.deserialize(shelterSerialized, AnimalShelter.class);
    Assert.assertTrue(shelterDeserialized instanceof AnimalShelter);
    Assert.assertEquals(2, shelterDeserialized.animalsInfo().size());
    for (FlattenableAnimalInfo animalInfo: shelterDeserialized.animalsInfo()) {
        Assert.assertTrue(animalInfo.animal() instanceof RabbitWithTypeIdContainingDot);
        Assert.assertNotNull(animalInfo.animal());
    }
}
 
Example #5
Source File: AdditionalPropertiesSerializerTests.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
@Test
public void canSerializeAdditionalPropertiesThroughInheritance() throws Exception {
    Foo foo = new FooChild();
    foo.bar = "hello.world";
    foo.baz = new ArrayList<>();
    foo.baz.add("hello");
    foo.baz.add("hello.world");
    foo.qux = new HashMap<>();
    foo.qux.put("hello", "world");
    foo.qux.put("a.b", "c.d");
    foo.qux.put("bar.a", "ttyy");
    foo.qux.put("bar.b", "uuzz");
    foo.additionalProperties = new HashMap<>();
    foo.additionalProperties.put("bar", "baz");
    foo.additionalProperties.put("a.b", "c.d");
    foo.additionalProperties.put("properties.bar", "barbar");

    String serialized = new JacksonAdapter().serialize(foo);
    Assert.assertEquals("{\"$type\":\"foochild\",\"properties\":{\"bar\":\"hello.world\",\"props\":{\"baz\":[\"hello\",\"hello.world\"],\"q\":{\"qux\":{\"hello\":\"world\",\"a.b\":\"c.d\",\"bar.b\":\"uuzz\",\"bar.a\":\"ttyy\"}}}},\"bar\":\"baz\",\"a.b\":\"c.d\",\"properties.bar\":\"barbar\"}", serialized);
}
 
Example #6
Source File: AdditionalPropertiesSerializerTests.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
@Test
public void canSerializeAdditionalProperties() throws Exception {
    Foo foo = new Foo();
    foo.bar = "hello.world";
    foo.baz = new ArrayList<>();
    foo.baz.add("hello");
    foo.baz.add("hello.world");
    foo.qux = new HashMap<>();
    foo.qux.put("hello", "world");
    foo.qux.put("a.b", "c.d");
    foo.qux.put("bar.a", "ttyy");
    foo.qux.put("bar.b", "uuzz");
    foo.additionalProperties = new HashMap<>();
    foo.additionalProperties.put("bar", "baz");
    foo.additionalProperties.put("a.b", "c.d");
    foo.additionalProperties.put("properties.bar", "barbar");

    String serialized = new JacksonAdapter().serialize(foo);
    Assert.assertEquals("{\"$type\":\"foo\",\"properties\":{\"bar\":\"hello.world\",\"props\":{\"baz\":[\"hello\",\"hello.world\"],\"q\":{\"qux\":{\"hello\":\"world\",\"a.b\":\"c.d\",\"bar.b\":\"uuzz\",\"bar.a\":\"ttyy\"}}}},\"bar\":\"baz\",\"a.b\":\"c.d\",\"properties.bar\":\"barbar\"}", serialized);
}
 
Example #7
Source File: KubernetesClustersTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Parse azure auth to hashmap
 * @param authFilename the azure auth location
 * @return all fields in azure auth json
 * @throws Exception exception
 */
private static HashMap<String, String> ParseAuthFile(String authFilename) throws Exception {
    String content = Files.toString(new File(authFilename), Charsets.UTF_8).trim();
    HashMap<String, String> auth = new HashMap<>();
    if (isJsonBased(content)) {
        auth = new JacksonAdapter().deserialize(content, auth.getClass());
    } else {
        Properties authSettings = new Properties();
        FileInputStream credentialsFileStream = new FileInputStream(new File(authFilename));
        authSettings.load(credentialsFileStream);
        credentialsFileStream.close();

        for (final String authName: authSettings.stringPropertyNames()) {
            auth.put(authName, authSettings.getProperty(authName));
        }
    }
    return auth;
}
 
Example #8
Source File: ApplicationGatewayTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private static ManagedServiceIdentity createManagedServiceIdentityFromIdentity(Identity identity) throws Exception{
    JsonObject userAssignedIdentitiesValueObject = new JsonObject();
    userAssignedIdentitiesValueObject.addProperty("principalId", identity.principalId());
    userAssignedIdentitiesValueObject.addProperty("clientId", identity.clientId());
    ManagedServiceIdentityUserAssignedIdentitiesValue userAssignedIdentitiesValue = 
            new JacksonAdapter().deserialize(userAssignedIdentitiesValueObject.toString(), 
                    ManagedServiceIdentityUserAssignedIdentitiesValue.class);

    Map<String, ManagedServiceIdentityUserAssignedIdentitiesValue> userAssignedIdentities = 
            new HashMap<>();
    userAssignedIdentities.put(identity.id(), userAssignedIdentitiesValue);

    ManagedServiceIdentity serviceIdentity = new ManagedServiceIdentity();
    serviceIdentity.withType(ResourceIdentityType.USER_ASSIGNED);
    serviceIdentity.withUserAssignedIdentities(userAssignedIdentities);
    return serviceIdentity;
}
 
Example #9
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Validates that decoding and encoding of a type with flattenable property and type id containing dot and can be done.
 * For decoding and encoding base type will be used.
 *
 * @throws IOException
 */
@Test
public void canHandleTypeWithFlattenablePropertyAndTypeIdContainingDot0() throws IOException {
    AnimalWithTypeIdContainingDot animalToSerialize = new DogWithTypeIdContainingDot().withBreed("AKITA").withCuteLevel(10);
    JacksonAdapter adapter = new JacksonAdapter();
    // serialization
    String serialized = adapter.serialize(animalToSerialize);
    String[] results = {
            "{\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10}}",
            "{\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}",
            "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10}}",
            "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\"}",
            "{\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\"}",
            "{\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}",
    };
    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // de-serialization
    AnimalWithTypeIdContainingDot animalDeserialized = adapter.deserialize(serialized, AnimalWithTypeIdContainingDot.class);
    Assert.assertTrue(animalDeserialized instanceof DogWithTypeIdContainingDot);
    DogWithTypeIdContainingDot dogDeserialized = (DogWithTypeIdContainingDot) animalDeserialized;
    Assert.assertNotNull(dogDeserialized);
    Assert.assertEquals(dogDeserialized.breed(), "AKITA");
    Assert.assertEquals(dogDeserialized.cuteLevel(), (Integer) 10);
}
 
Example #10
Source File: CBRefreshTokenClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public CBRefreshTokenClient(String baseUrl) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor(LogLevel.BODY_AND_HEADERS));
    builder.proxyAuthenticator(new JavaNetAuthenticator());
    service = new Builder()
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(new JacksonAdapter().converterFactory())
            .baseUrl(baseUrl)
            .client(builder.build())
            .build().create(RefreshTokenService.class);
}
 
Example #11
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canHandleEscapedProperties() throws IOException {
    FlattenedProduct productToSerialize = new FlattenedProduct();
    productToSerialize.withProductName("drink");
    productToSerialize.withPType("chai");
    JacksonAdapter adapter = new JacksonAdapter();
    // serialization
    //
    String serialized = adapter.serialize(productToSerialize);
    String[] results = {
            "{\"properties\":{\"p.name\":\"drink\",\"type\":\"chai\"}}",
            "{\"properties\":{\"type\":\"chai\",\"p.name\":\"drink\"}}",
    };

    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // de-serialization
    //
    FlattenedProduct productDeserialized = adapter.deserialize(serialized, FlattenedProduct.class);
    Assert.assertNotNull(productDeserialized);
    Assert.assertEquals(productDeserialized.productName(), "drink");
    Assert.assertEquals(productDeserialized.productType, "chai");
}
 
Example #12
Source File: PartnerServiceClient.java    From Partner-Center-Java with MIT License 5 votes vote down vote up
/**
 * Initializes a new instance of the PartnerServiceClient class.
 *
 * @param baseUrl The base service endpoint address.
 */
public PartnerServiceClient(String baseUrl)
{
	super(
		new RestClient.Builder()
			.withBaseUrl(baseUrl)
			.withRetryStrategy(
				new PartnerServiceRetryStrategy(
					PartnerService.getInstance().getConfiguration().getDefaultMaxRetryAttempts()))
			.withSerializerAdapter(new JacksonAdapter())
			.withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
			.build());

	errorHandler = new DefaultPartnerServiceErrorHandler();
}
 
Example #13
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canHandleComposedGenericPolymorphicTypeWithoutTypeId() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    //
    // -- Validate vector property
    //
    String serializedCollectionWithTypeId = "{\"turtlesSet2\":[{\"age\":100,\"size\":10 },{\"age\":200,\"size\":20 }]}";
    // de-serialization
    //
    ComposeTurtles composedTurtleDeserialized = adapter.deserialize(serializedCollectionWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet2());
    Assert.assertEquals(2, composedTurtleDeserialized.turtlesSet2().size());
    //
    Assert.assertFalse(composedTurtleDeserialized.turtlesSet2().get(0) instanceof TurtleWithTypeIdContainingDot);
    Assert.assertTrue(composedTurtleDeserialized.turtlesSet2().get(0) instanceof NonEmptyAnimalWithTypeIdContainingDot);
    Assert.assertFalse(composedTurtleDeserialized.turtlesSet2().get(1) instanceof TurtleWithTypeIdContainingDot);
    Assert.assertTrue(composedTurtleDeserialized.turtlesSet2().get(1) instanceof NonEmptyAnimalWithTypeIdContainingDot);
    //
    // -- Validate scalar property
    //
    adapter.serialize(composedTurtleDeserialized);
    //
    String serializedScalarWithTypeId = "{\"turtlesSet2Lead\":{\"age\":100,\"size\":10 }}";
    // de-serialization
    //
    composedTurtleDeserialized = adapter.deserialize(serializedScalarWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet2Lead());
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet2Lead() instanceof NonEmptyAnimalWithTypeIdContainingDot);
    //
    adapter.serialize(composedTurtleDeserialized);
}
 
Example #14
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canHandleComposedGenericPolymorphicTypeWithTypeId() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    //
    // -- Validate vector property
    //
    String serializedCollectionWithTypeId = "{\"turtlesSet2\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}]}";
    // de-serialization
    //
    ComposeTurtles composedTurtleDeserialized = adapter.deserialize(serializedCollectionWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet2());
    Assert.assertEquals(2, composedTurtleDeserialized.turtlesSet2().size());
    //
    Assert.assertTrue(composedTurtleDeserialized.turtlesSet2().get(0) instanceof TurtleWithTypeIdContainingDot);
    Assert.assertTrue(composedTurtleDeserialized.turtlesSet2().get(1) instanceof TurtleWithTypeIdContainingDot);
    //
    adapter.serialize(composedTurtleDeserialized);
    //
    // -- Validate scalar property
    //
    String serializedScalarWithTypeId = "{\"turtlesSet2Lead\":{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}}";
    // de-serialization
    //
    composedTurtleDeserialized = adapter.deserialize(serializedScalarWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet2Lead());
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet2Lead() instanceof TurtleWithTypeIdContainingDot);
    Assert.assertEquals(10 , (long) ((TurtleWithTypeIdContainingDot) composedTurtleDeserialized.turtlesSet2Lead()).size());
    Assert.assertEquals(100 , (long) composedTurtleDeserialized.turtlesSet2Lead().age());
    //
    adapter.serialize(composedTurtleDeserialized);
}
 
Example #15
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canHandleComposedSpecificPolymorphicTypeWithoutTypeId() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    //
    // -- Validate vector property
    //
    String serializedCollectionWithTypeId = "{\"turtlesSet1\":[{\"age\":100,\"size\":10 },{\"age\":200,\"size\":20 }]}";
    // de-serialization
    //
    ComposeTurtles composedTurtleDeserialized = adapter.deserialize(serializedCollectionWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet1());
    Assert.assertEquals(2, composedTurtleDeserialized.turtlesSet1().size());
    //
    adapter.serialize(composedTurtleDeserialized);
    //
    // -- Validate scalar property
    //
    String serializedScalarWithTypeId = "{\"turtlesSet1Lead\":{\"age\":100,\"size\":10 }}";
    // de-serialization
    //
    composedTurtleDeserialized = adapter.deserialize(serializedScalarWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet1Lead());
    Assert.assertEquals(100 , (long) composedTurtleDeserialized.turtlesSet1Lead().age());
    //
    adapter.serialize(composedTurtleDeserialized);
}
 
Example #16
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canHandleComposedSpecificPolymorphicTypeWithTypeId() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    //
    // -- Validate vector property
    //
    String serializedCollectionWithTypeId = "{\"turtlesSet1\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}]}";
    // de-serialization
    //
    ComposeTurtles composedTurtleDeserialized = adapter.deserialize(serializedCollectionWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet1());
    Assert.assertEquals(2, composedTurtleDeserialized.turtlesSet1().size());
    //
    adapter.serialize(composedTurtleDeserialized);
    //
    // -- Validate scalar property
    //
    String serializedScalarWithTypeId = "{\"turtlesSet1Lead\":{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}}";
    // de-serialization
    //
    composedTurtleDeserialized = adapter.deserialize(serializedScalarWithTypeId, ComposeTurtles.class);
    Assert.assertNotNull(composedTurtleDeserialized);
    Assert.assertNotNull(composedTurtleDeserialized.turtlesSet1Lead());
    Assert.assertEquals(10 , (long) composedTurtleDeserialized.turtlesSet1Lead().size());
    Assert.assertEquals(100 , (long) composedTurtleDeserialized.turtlesSet1Lead().age());
    //
    adapter.serialize(composedTurtleDeserialized);
}
 
Example #17
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Validates that decoding and encoding of a type with flattenable property and type id containing dot and can be done.
 * For decoding and encoding concrete type will be used.
 *
 * @throws IOException
 */
@Test
public void canHandleTypeWithFlattenablePropertyAndTypeIdContainingDot1() throws IOException {
    DogWithTypeIdContainingDot dogToSerialize = new DogWithTypeIdContainingDot().withBreed("AKITA").withCuteLevel(10);
    JacksonAdapter adapter = new JacksonAdapter();
    // serialization
    String serialized = adapter.serialize(dogToSerialize);
    String[] results = {
            "{\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10}}",
            "{\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}",
            "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10}}",
            "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\"}",
            "{\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\"}",
            "{\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}",
    };
    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // de-serialization
    DogWithTypeIdContainingDot dogDeserialized = adapter.deserialize(serialized, DogWithTypeIdContainingDot.class);
    Assert.assertNotNull(dogDeserialized);
    Assert.assertEquals(dogDeserialized.breed(), "AKITA");
    Assert.assertEquals(dogDeserialized.cuteLevel(), (Integer) 10);
}
 
Example #18
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Validates that decoding and encoding of a type with type id containing dot and can be done.
 * For decoding and encoding concrete type will be used.
 *
 * @throws IOException
 */
@Test
public void canHandleTypeWithTypeIdContainingDot1() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    // Serialize
    //
    List<String> meals = new ArrayList<>();
    meals.add("carrot");
    meals.add("apple");
    //
    RabbitWithTypeIdContainingDot rabbitToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals);
    String serialized = adapter.serialize(rabbitToSerialize);
    //
    String[] results = {
            "{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}",
            "{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}"
    };
    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // De-Serialize
    //
    RabbitWithTypeIdContainingDot rabbitDeserialized = adapter.deserialize(serialized, RabbitWithTypeIdContainingDot.class);
    Assert.assertTrue(rabbitDeserialized instanceof RabbitWithTypeIdContainingDot);
    Assert.assertNotNull(rabbitDeserialized.meals());
    Assert.assertEquals(rabbitDeserialized.meals().size(), 2);
}
 
Example #19
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Validates that decoding and encoding of a type with type id containing dot and can be done.
 * For decoding and encoding base type will be used.
 *
 * @throws IOException
 */
@Test
public void canHandleTypeWithTypeIdContainingDot0() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    // Serialize
    //
    List<String> meals = new ArrayList<>();
    meals.add("carrot");
    meals.add("apple");
    //
    AnimalWithTypeIdContainingDot animalToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals);
    String serialized = adapter.serialize(animalToSerialize);
    //
    String[] results = {
            "{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}",
            "{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}"
    };
    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
     Assert.assertTrue(found);
    // De-Serialize
    //
    AnimalWithTypeIdContainingDot animalDeserialized = adapter.deserialize(serialized, AnimalWithTypeIdContainingDot.class);
    Assert.assertTrue(animalDeserialized instanceof RabbitWithTypeIdContainingDot);
    RabbitWithTypeIdContainingDot rabbit = (RabbitWithTypeIdContainingDot) animalDeserialized;
    Assert.assertNotNull(rabbit.meals());
    Assert.assertEquals(rabbit.meals().size(), 2);
}
 
Example #20
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canFlatten() throws Exception {
    Foo foo = new Foo();
    foo.bar = "hello.world";
    foo.baz = new ArrayList<>();
    foo.baz.add("hello");
    foo.baz.add("hello.world");
    foo.qux = new HashMap<>();
    foo.qux.put("hello", "world");
    foo.qux.put("a.b", "c.d");
    foo.qux.put("bar.a", "ttyy");
    foo.qux.put("bar.b", "uuzz");

    JacksonAdapter adapter = new JacksonAdapter();

    // serialization
    String serialized = adapter.serialize(foo);
    Assert.assertEquals("{\"$type\":\"foo\",\"properties\":{\"bar\":\"hello.world\",\"props\":{\"baz\":[\"hello\",\"hello.world\"],\"q\":{\"qux\":{\"hello\":\"world\",\"a.b\":\"c.d\",\"bar.b\":\"uuzz\",\"bar.a\":\"ttyy\"}}}}}", serialized);

    // deserialization
    Foo deserialized = adapter.deserialize(serialized, Foo.class);
    Assert.assertEquals("hello.world", deserialized.bar);
    Assert.assertArrayEquals(new String[]{"hello", "hello.world"}, deserialized.baz.toArray());
    Assert.assertNotNull(deserialized.qux);
    Assert.assertEquals("world", deserialized.qux.get("hello"));
    Assert.assertEquals("c.d", deserialized.qux.get("a.b"));
    Assert.assertEquals("ttyy", deserialized.qux.get("bar.a"));
    Assert.assertEquals("uuzz", deserialized.qux.get("bar.b"));
}
 
Example #21
Source File: RestClientTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void defaultConfigs() {
    RestClient restClient = new RestClient.Builder()
            .withBaseUrl("https://management.azure.com/")
            .withSerializerAdapter(new JacksonAdapter())
            .withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
            .build();
    Assert.assertEquals("https://management.azure.com/", restClient.retrofit().baseUrl().toString());
    Assert.assertEquals(LogLevel.NONE, restClient.logLevel());
    Assert.assertTrue(restClient.responseBuilderFactory() instanceof ServiceResponseBuilder.Factory);
    Assert.assertTrue(restClient.serializerAdapter() instanceof JacksonAdapter);
    Assert.assertNull(restClient.credentials());
}
 
Example #22
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 #23
Source File: ResponseBuilderTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void nullOnGet404() throws Exception {
    RestClient restClient = new RestClient.Builder()
            .withBaseUrl("https://microsoft.com/")
            .withSerializerAdapter(new JacksonAdapter())
            .withResponseBuilderFactory(new ServiceResponseBuilder.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();
    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);
    Assert.assertNull(sr.body());
    Assert.assertEquals(404, sr.response().code());
}
 
Example #24
Source File: AdditionalPropertiesSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canDeserializeAdditionalPropertiesThroughInheritance() throws Exception {
    String wireValue = "{\"$type\":\"foochild\",\"properties\":{\"bar\":\"hello.world\",\"props\":{\"baz\":[\"hello\",\"hello.world\"],\"q\":{\"qux\":{\"hello\":\"world\",\"a.b\":\"c.d\",\"bar.b\":\"uuzz\",\"bar.a\":\"ttyy\"}}}},\"bar\":\"baz\",\"a.b\":\"c.d\",\"properties.bar\":\"barbar\"}";
    Foo deserialized = new JacksonAdapter().deserialize(wireValue, Foo.class);
    Assert.assertNotNull(deserialized.additionalProperties);
    Assert.assertEquals("baz", deserialized.additionalProperties.get("bar"));
    Assert.assertEquals("c.d", deserialized.additionalProperties.get("a.b"));
    Assert.assertEquals("barbar", deserialized.additionalProperties.get("properties.bar"));
    Assert.assertTrue(deserialized instanceof FooChild);
}
 
Example #25
Source File: ServiceClient.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Initializes a new instance of the ServiceClient class.
 *
 * @param baseUrl the service base uri
 * @param clientBuilder the http client builder
 * @param restBuilder the retrofit rest client builder
 */
protected ServiceClient(String baseUrl, OkHttpClient.Builder clientBuilder, Retrofit.Builder restBuilder) {
    this(new RestClient.Builder(clientBuilder, restBuilder)
            .withBaseUrl(baseUrl)
            .withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
            .withSerializerAdapter(new JacksonAdapter())
            .build());
}
 
Example #26
Source File: AdditionalPropertiesSerializerTests.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Test
public void canDeserializeAdditionalProperties() throws Exception {
    String wireValue = "{\"$type\":\"foo\",\"properties\":{\"bar\":\"hello.world\",\"props\":{\"baz\":[\"hello\",\"hello.world\"],\"q\":{\"qux\":{\"hello\":\"world\",\"a.b\":\"c.d\",\"bar.b\":\"uuzz\",\"bar.a\":\"ttyy\"}}}},\"bar\":\"baz\",\"a.b\":\"c.d\",\"properties.bar\":\"barbar\"}";
    Foo deserialized = new JacksonAdapter().deserialize(wireValue, Foo.class);
    Assert.assertNotNull(deserialized.additionalProperties);
    Assert.assertEquals("baz", deserialized.additionalProperties.get("bar"));
    Assert.assertEquals("c.d", deserialized.additionalProperties.get("a.b"));
    Assert.assertEquals("barbar", deserialized.additionalProperties.get("properties.bar"));
}
 
Example #27
Source File: ConnectionPoolTests.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
@Test
public void canUseOkHttpThreadPool() throws Exception {
    RestClient restClient = new RestClient.Builder()
            .withBaseUrl("https://microsoft.com")
            .withSerializerAdapter(new JacksonAdapter())
            .withResponseBuilderFactory(new Factory())
            .withDispatcher(new Dispatcher(Executors.newFixedThreadPool(2)))
            .useHttpClientThreadPool(true)
            .withInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new IOException(e);
                    }
                    return new Response.Builder()
                            .request(chain.request())
                            .code(200)
                            .message("OK")
                            .protocol(Protocol.HTTP_1_1)
                            .body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks"))
                            .build();
                }
            })
            .build();

    final Service service = restClient.retrofit().create(Service.class);

    final CountDownLatch latch = new CountDownLatch(1);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    Observable.range(1, 4)
            .flatMap(new Func1<Integer, Observable<?>>() {
                @Override
                public Observable<?> call(Integer integer) {
                    return service.getAsync().subscribeOn(Schedulers.io());
                }
            })
            .doOnCompleted(new Action0() {
                @Override
                public void call() {
                    latch.countDown();
                }
            }).subscribe();

    latch.await();
    stopWatch.stop();
    Assert.assertTrue(stopWatch.getTime() > 2000);
}
 
Example #28
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
/**
 * Validates that decoding and encoding of a array of type with type id containing dot and can be done.
 * For decoding and encoding base type will be used.
 *
 * @throws IOException
 */
@Test
public void canHandleArrayOfTypeWithTypeIdContainingDot0() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    // Serialize
    //
    List<String> meals = new ArrayList<>();
    meals.add("carrot");
    meals.add("apple");
    //
    AnimalWithTypeIdContainingDot animalToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals);
    List<AnimalWithTypeIdContainingDot> animalsToSerialize = new ArrayList<>();
    animalsToSerialize.add(animalToSerialize);
    String serialized = adapter.serialize(animalsToSerialize);
    String[] results = {
            "[{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}]",
            "[{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}]",
    };
    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // De-serialize
    //
    List<AnimalWithTypeIdContainingDot> animalsDeserialized = adapter.deserialize(serialized, new ParameterizedType() {
        @Override
        public Type[] getActualTypeArguments() {
            return new Type[] { AnimalWithTypeIdContainingDot.class };
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    });
    Assert.assertNotNull(animalsDeserialized);
    Assert.assertEquals(1, animalsDeserialized.size());
    AnimalWithTypeIdContainingDot animalDeserialized = animalsDeserialized.get(0);
    Assert.assertTrue(animalDeserialized instanceof RabbitWithTypeIdContainingDot);
    RabbitWithTypeIdContainingDot rabbitDeserialized = (RabbitWithTypeIdContainingDot) animalDeserialized;
    Assert.assertNotNull(rabbitDeserialized.meals());
    Assert.assertEquals(rabbitDeserialized.meals().size(), 2);
}
 
Example #29
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
/**
 * Validates that decoding and encoding of a array of type with type id containing dot and can be done.
 * For decoding and encoding concrete type will be used.
 *
 * @throws IOException
 */
@Test
public void canHandleArrayOfTypeWithTypeIdContainingDot1() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    // Serialize
    //
    List<String> meals = new ArrayList<>();
    meals.add("carrot");
    meals.add("apple");
    //
    RabbitWithTypeIdContainingDot rabbitToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals);
    List<RabbitWithTypeIdContainingDot> rabbitsToSerialize = new ArrayList<>();
    rabbitsToSerialize.add(rabbitToSerialize);
    String serialized = adapter.serialize(rabbitsToSerialize);
    String[] results = {
            "[{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}]",
            "[{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}]",
    };
    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // De-serialize
    //
    List<RabbitWithTypeIdContainingDot> rabbitsDeserialized = adapter.deserialize(serialized, new ParameterizedType() {
        @Override
        public Type[] getActualTypeArguments() {
            return new Type[] { RabbitWithTypeIdContainingDot.class };
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    });
    Assert.assertNotNull(rabbitsDeserialized);
    Assert.assertEquals(1, rabbitsDeserialized.size());
    RabbitWithTypeIdContainingDot rabbitDeserialized = rabbitsDeserialized.get(0);
    Assert.assertNotNull(rabbitDeserialized.meals());
    Assert.assertEquals(rabbitDeserialized.meals().size(), 2);
}
 
Example #30
Source File: FlatteningSerializerTests.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
/**
 * Validates that decoding and encoding of a composed type with type id containing dot and can be done.
 *
 * @throws IOException
 */
@Test
public void canHandleComposedTypeWithTypeIdContainingDot0() throws IOException {
    JacksonAdapter adapter = new JacksonAdapter();
    // serialization
    //
    List<String> meals = new ArrayList<>();
    meals.add("carrot");
    meals.add("apple");
    AnimalWithTypeIdContainingDot animalToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals);
    FlattenableAnimalInfo animalInfoToSerialize = new FlattenableAnimalInfo().withAnimal(animalToSerialize);
    List<FlattenableAnimalInfo> animalsInfoSerialized = ImmutableList.of(animalInfoToSerialize);
    AnimalShelter animalShelterToSerialize = new AnimalShelter().withAnimalsInfo(animalsInfoSerialized);
    String serialized = adapter.serialize(animalShelterToSerialize);
    String[] results = {
            "{\"properties\":{\"animalsInfo\":[{\"animal\":{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}}]}}",
            "{\"properties\":{\"animalsInfo\":[{\"animal\":{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}}]}}",
    };

    boolean found = false;
    for (String result : results) {
        if (result.equals(serialized)) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // de-serialization
    //
    AnimalShelter shelterDeserialized = adapter.deserialize(serialized, AnimalShelter.class);
    Assert.assertNotNull(shelterDeserialized.animalsInfo());
    Assert.assertEquals(shelterDeserialized.animalsInfo().size(), 1);
    FlattenableAnimalInfo animalsInfoDeserialized = shelterDeserialized.animalsInfo().get(0);
    Assert.assertTrue(animalsInfoDeserialized.animal() instanceof RabbitWithTypeIdContainingDot);
    AnimalWithTypeIdContainingDot animalDeserialized = animalsInfoDeserialized.animal();
    Assert.assertTrue(animalDeserialized instanceof RabbitWithTypeIdContainingDot);
    RabbitWithTypeIdContainingDot rabbitDeserialized = (RabbitWithTypeIdContainingDot) animalDeserialized;
    Assert.assertNotNull(rabbitDeserialized);
    Assert.assertNotNull(rabbitDeserialized.meals());
    Assert.assertEquals(rabbitDeserialized.meals().size(), 2);
}