Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix deserialization of entities #14551

Merged
merged 4 commits into from
Aug 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
import com.azure.core.util.serializer.SerializerAdapter;
import com.azure.data.tables.implementation.AzureTableImpl;
import com.azure.data.tables.implementation.AzureTableImplBuilder;
import com.azure.data.tables.implementation.TablesConstants;
import com.azure.data.tables.implementation.TablesModelHelper;
import com.azure.data.tables.implementation.ModelHelper;
import com.azure.data.tables.implementation.models.OdataMetadataFormat;
import com.azure.data.tables.implementation.models.QueryOptions;
import com.azure.data.tables.implementation.models.ResponseFormat;
Expand All @@ -32,8 +31,6 @@

import java.net.URI;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -519,7 +516,7 @@ private Mono<PagedResponse<TableEntity>> listEntities(String nextPartitionKey, S
}

final List<TableEntity> entities = entityResponseValue.stream()
.map(entityMap -> deserializeEntity(logger, entityMap))
.map(ModelHelper::createEntity)
.collect(Collectors.toList());

return Mono.just(new EntityPaged(response, entities,
Expand Down Expand Up @@ -632,60 +629,9 @@ Mono<Response<TableEntity>> getEntityWithResponse(String partitionKey, String ro

// Deserialize the first entity.
// TODO: Potentially update logic to deserialize them all.
final TableEntity entity = deserializeEntity(logger, matchingEntities.get(0));
final TableEntity entity = ModelHelper.createEntity(matchingEntities.get(0));
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
entity));
});
}

/**
* Given a Map, creates the corresponding entity.
*
* @param properties Properties representing the entity.
*
* @return The Entity represented by this map.
* @throws IllegalArgumentException if the Map is missing a row key or partition key.
* @throws NullPointerException if 'properties' is null.
*/
private static TableEntity deserializeEntity(ClientLogger logger, Map<String, Object> properties) {
final Object partitionKeyValue = properties.get(TablesConstants.PARTITION_KEY);
if (!(partitionKeyValue instanceof String) || ((String) partitionKeyValue).isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"'%s' does not exist in property map or is an empty value.", TablesConstants.PARTITION_KEY)));
}

final Object rowKeyValue = properties.get(TablesConstants.ROW_KEY);
if (!(rowKeyValue instanceof String) || ((String) rowKeyValue).isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"'%s' does not exist in property map or is an empty value.", TablesConstants.ROW_KEY)));
}

final Object timestampValue = properties.get(TablesConstants.TIMESTAMP_KEY);
OffsetDateTime timestamp = null;
if (timestampValue != null) {
if (!(timestampValue instanceof String)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"'%s' value is of the wrong type.", TablesConstants.TIMESTAMP_KEY)));
}
try {
timestamp = OffsetDateTime.parse((String) timestampValue);
} catch (DateTimeParseException e) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"'%s' value is not a valid OffsetDateTime.", TablesConstants.TIMESTAMP_KEY), e));
}
}

final Object etagValue = properties.get(TablesConstants.ODATA_ETAG_KEY);
if (etagValue != null && !(etagValue instanceof String)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"'%s' value is of the wrong type.", TablesConstants.ODATA_ETAG_KEY)));
}

final TableEntity entity = new TableEntity((String) partitionKeyValue, (String) rowKeyValue);
TablesModelHelper.setValues(entity, timestamp, (String) etagValue);

properties.forEach((key, value) -> entity.getProperties().putIfAbsent(key, value));

return entity;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import com.azure.core.util.serializer.SerializerAdapter;
import com.azure.data.tables.implementation.AzureTableImpl;
import com.azure.data.tables.implementation.AzureTableImplBuilder;
import com.azure.data.tables.implementation.TablesModelHelper;
import com.azure.data.tables.implementation.ModelHelper;
import com.azure.data.tables.implementation.models.OdataMetadataFormat;
import com.azure.data.tables.implementation.models.QueryOptions;
import com.azure.data.tables.implementation.models.ResponseFormat;
Expand Down Expand Up @@ -268,7 +268,7 @@ private Mono<PagedResponse<TableItem>> listTables(String nextTableName, Context
return Mono.empty();
}
final List<TableItem> tables = tableResponsePropertiesList.stream()
.map(TablesModelHelper::createItem).collect(Collectors.toList());
.map(ModelHelper::createItem).collect(Collectors.toList());

return Mono.just(new TablePaged(response, tables,
response.getDeserializedHeaders().getXMsContinuationNextTableName()));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.tables.implementation;

import com.azure.core.util.logging.ClientLogger;
import com.azure.data.tables.implementation.models.TableResponseProperties;
import com.azure.data.tables.models.TableEntity;
import com.azure.data.tables.models.TableItem;

import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
* Used to access internal methods on models.
*/
public final class ModelHelper {
private static Function<Map<String, Object>, TableEntity> entityCreator;
private static Function<TableResponseProperties, TableItem> itemCreator;

static {
// Force classes' static blocks to execute
try {
Class.forName(TableEntity.class.getName(), true, TableEntity.class.getClassLoader());
Class.forName(TableItem.class.getName(), true, TableItem.class.getClassLoader());
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(new ClientLogger(ModelHelper.class).logThrowableAsError(e));
}
}

/**
* Sets the entity creator.
*
* @param creator The entity creator.
* @throws IllegalStateException if the creator has already been set.
*/
public static void setEntityCreator(Function<Map<String, Object>, TableEntity> creator) {
Objects.requireNonNull(creator, "'creator' cannot be null.");

if (ModelHelper.entityCreator != null) {
throw new ClientLogger(ModelHelper.class).logExceptionAsError(new IllegalStateException(
"'entityCreator' is already set."));
}

entityCreator = creator;
}

/**
* Sets the item creator.
*
* @param creator The item creator.
* @throws IllegalStateException if the creator has already been set.
*/
public static void setItemCreator(Function<TableResponseProperties, TableItem> creator) {
Objects.requireNonNull(creator, "'creator' cannot be null.");

if (ModelHelper.itemCreator != null) {
throw new ClientLogger(ModelHelper.class).logExceptionAsError(new IllegalStateException(
"'itemCreator' is already set."));
}

itemCreator = creator;
}

/**
* Creates a {@link TableEntity}.
*
* @param properties The properties used to construct the entity
* @return The created TableEntity
*/
public static TableEntity createEntity(Map<String, Object> properties) {
if (entityCreator == null) {
throw new ClientLogger(ModelHelper.class).logExceptionAsError(
new IllegalStateException("'entityCreator' should not be null."));
}

return entityCreator.apply(properties);
}

/**
* Creates a {@link TableItem}.
*
* @param properties The TableResponseProperties used to construct the table
* @return The created TableItem
*/
public static TableItem createItem(TableResponseProperties properties) {
if (itemCreator == null) {
throw new ClientLogger(ModelHelper.class).logExceptionAsError(
new IllegalStateException("'itemCreator' should not be null."));
}

return itemCreator.apply(properties);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,21 @@
// Licensed under the MIT License.
package com.azure.data.tables.implementation;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* Constants for Tables service.
*/
public final class TablesConstants {

/**
* Name in the Map to get the table name.
*/
public static final String TABLE_NAME_KEY = "TableName";

/**
* Name in the Map to get the partition key.
*/
Expand All @@ -32,10 +43,31 @@ public final class TablesConstants {
public static final String ODATA_METADATA_KEY = "odata.metadata";

/**
* Name in the map for the entity's URL.
* Name in the map for the table or entity's URL.
*/
public static final String ODATA_EDIT_LINK_KEY = "odata.editLink";

/**
* Name in the map for the table or entity's type.
*/
public static final String ODATA_TYPE_KEY = "odata.type";

/**
* Name in the map for the table or entity's ID.
*/
public static final String ODATA_ID_KEY = "odata.id";

/**
* Set of keys returned in OData metadata.
*/
public static final Set<String> METADATA_KEYS = Stream.of(
ODATA_EDIT_LINK_KEY,
ODATA_ETAG_KEY,
ODATA_ID_KEY,
ODATA_METADATA_KEY,
ODATA_TYPE_KEY
).collect(Collectors.toCollection(HashSet::new));

/**
* Private constructor so this class cannot be instantiated.
*/
Expand Down
Loading