首页 > 解决方案 > 使用 Java 的 Azure 表存储时间戳不能为空

问题描述

我想将实体插入 Azure 表存储,但每次 insertOrReplace 时,都会收到异常“IllegalArgumentException:参数不得为空。参数名称:时间戳”。

据我所知,我不应该设置时间戳,只设置分区和行键,时间戳是自动设置的。我还在扩展 TableServiceEntity 并设置 Partition 和 Row 键。

没有调用 Person 中的构造函数,因为我从 GSON 创建了类,这就是我创建 SetPartitionAndRowKey 接口的原因,以便在插入人员之前对其进行设置。

我的数据库插入类

public class TableStorageCRUD<T extends TableServiceEntity & SetPartitionAndRowKey> extends AzureTableStorage {

public TableStorageCRUD(ExecutionContext context, AzureTableConstants tableName) {
    super(context);
    try {
        cloudTable = tableClient.getTableReference(tableName.getTableName());
    } catch (URISyntaxException | StorageException e) {
        e.printStackTrace();
    }
}

public T insertEntity(T azureEntity) {
    azureEntity.setPartitionAndRowKey();
    context.getLogger().info("Class: " + azureEntity.toString());
    context.getLogger().info("Partition Key: " + azureEntity.getPartitionKey());
    context.getLogger().info("Row Key: " + azureEntity.getRowKey());

    TableOperation tableInsertOperation = TableOperation.insertOrReplace(azureEntity);
    TableResult tableResult;

    try {
        tableResult = cloudTable.execute(tableInsertOperation);
        context.getLogger().info("Azure Table Storage HTTP Code: " + tableResult.getHttpStatusCode());
        return tableResult.getResultAsType();
    } catch (StorageException e) {
        e.printStackTrace();
    }
    return null;

}

}

public class AzureTableStorage {

private final String CONNECTION_STRING = "<<MY_WORKING_CONNECTION_STRING>>";

// Azure context
protected ExecutionContext context = null;

// Retrieve storage account from connection-string.
protected CloudStorageAccount storageAccount = null;

// Create the table client.
protected CloudTableClient tableClient = null;

// Create object for table
protected CloudTable cloudTable = null;

public AzureTableStorage(ExecutionContext context) {
    this.context = context;
    try {
        storageAccount = CloudStorageAccount.parse(CONNECTION_STRING);
        tableClient = storageAccount.createCloudTableClient();
    } catch (URISyntaxException | InvalidKeyException e) {
        e.printStackTrace();
    }
}

}

尝试插入的 Person 类

public class Person extends TableServiceEntity implements SetPartitionAndRowKey {
private String teamName;
private String name;
private String surname;
private String email;
private int permissionLevel;

public Person(String teamName, String name, String surname, String email, int permissionLevel) {
    super(teamName, PermissionHelper.isAdmin(permissionLevel) ? "admin_" + email : "member_" + email);
    this.partitionKey = teamName;
    this.rowKey = PermissionHelper.isAdmin(permissionLevel) ? "admin_" + email : "member_" + email;
    this.teamName = teamName;
    this.name = name;
    this.surname = surname;
    this.email = email;
    this.permissionLevel = permissionLevel;
}

@Override
public String toString() {
    return "Person{" +
            "teamName='" + teamName + '\'' +
            ", name='" + name + '\'' +
            ", surname='" + surname + '\'' +
            ", email='" + email + '\'' +
            ", permissionLevel=" + permissionLevel +
            ", partitionKey='" + partitionKey + '\'' +
            ", rowKey='" + rowKey + '\'' +
            ", etag='" + etag + '\'' +
            ", timeStamp=" + timeStamp +
            '}';
}

public String getTeamName() {
    return teamName;
}

public void setTeamName(String teamName) { this.teamName = teamName; }

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) { this.email = email; }

public int getPermissionLevel() {
    return permissionLevel;
}

public void setPermissionLevel(int permissionLevel) {
    this.permissionLevel = permissionLevel;
}

@Override
public void setPartitionAndRowKey() {
    this.partitionKey = this.teamName;
    this.rowKey = PermissionHelper.isAdmin(permissionLevel) ? "admin_" + email : "member_" + email;
}

我得到的例外

    Result: Failure
Exception: IllegalArgumentException: The argument must not be null. Argument name: Timestamp.
Stack: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.microsoft.azure.functions.worker.broker.JavaMethodInvokeInfo.invoke(JavaMethodInvokeInfo.java:22)
at com.microsoft.azure.functions.worker.broker.JavaMethodExecutor.execute(JavaMethodExecutor.java:54)
at com.microsoft.azure.functions.worker.broker.JavaFunctionBroker.invokeMethod(JavaFunctionBroker.java:51)
at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:33)
at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:10)
at com.microsoft.azure.functions.worker.handler.MessageHandler.handle(MessageHandler.java:45)
at com.microsoft.azure.functions.worker.JavaWorkerClient$StreamingMessagePeer.lambda$onNext$0(JavaWorkerClient.java:92)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: The argument must not be null. Argument name: Timestamp.
at com.microsoft.azure.storage.core.Utility.assertNotNull(Utility.java:368)
at com.microsoft.azure.storage.table.TableEntitySerializer.writeJsonEntity(TableEntitySerializer.java:137)
at com.microsoft.azure.storage.table.TableEntitySerializer.writeSingleEntityToStream(TableEntitySerializer.java:63)
at com.microsoft.azure.storage.table.TableOperation.insertImpl(TableOperation.java:381)
at com.microsoft.azure.storage.table.TableOperation.performInsert(TableOperation.java:362)
at com.microsoft.azure.storage.table.TableOperation.execute(TableOperation.java:682)
at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:529)
at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:496)
at entelect.ticket.system.table_storage.TableStorageCRUD.insertEntity(TableStorageCRUD.java:34)
at entelect.ticket.system.services.PersonService.createJwtAndSavePerson(PersonService.java:26)
at entelect.ticket.system.Create_person.run(Create_person.java:33)
... 16 more

Azure 提供的 TableServiceEntity 类

public class TableServiceEntity implements TableEntity {
private static final int DEFAULT_CONCURRENCY_MULTIPLIER = 4;
private static final float DEFAULT_LOAD_FACTOR = 0.75F;
private static final int DEFAULT_INITIAL_CAPACITY = 31;
private static boolean disableReflectedEntityCache = false;
protected String partitionKey = null;
protected String rowKey = null;
protected String etag = null;
protected Date timeStamp = new Date();
private static ConcurrentHashMap<Class<?>, HashMap<String, PropertyPair>> reflectedEntityCache = initialize();

public static void readEntityWithReflection(Object instance, HashMap<String, EntityProperty> properties, OperationContext opContext) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    HashMap<String, PropertyPair> props = PropertyPair.generatePropertyPairs(instance.getClass());
    Iterator var4 = properties.entrySet().iterator();

    while(var4.hasNext()) {
        Entry<String, EntityProperty> p = (Entry)var4.next();
        if (props.containsKey(p.getKey())) {
            ((PropertyPair)props.get(p.getKey())).consumeEntityProperty((EntityProperty)p.getValue(), instance);
        }
    }

}

public static HashMap<String, EntityProperty> writeEntityWithReflection(Object instance) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    HashMap<String, PropertyPair> props = PropertyPair.generatePropertyPairs(instance.getClass());
    HashMap<String, EntityProperty> retVal = new HashMap();
    Iterator var3 = props.entrySet().iterator();

    while(var3.hasNext()) {
        Entry<String, PropertyPair> p = (Entry)var3.next();
        retVal.put(((PropertyPair)p.getValue()).effectiveName, ((PropertyPair)p.getValue()).generateEntityProperty(instance));
    }

    return retVal;
}

public TableServiceEntity() {
}

public TableServiceEntity(String partitionKey, String rowKey) {
    this.partitionKey = partitionKey;
    this.rowKey = rowKey;
}

public String getEtag() {
    return this.etag;
}

public String getPartitionKey() {
    return this.partitionKey;
}

public String getRowKey() {
    return this.rowKey;
}

public Date getTimestamp() {
    return this.timeStamp;
}

public static boolean isReflectedEntityCacheDisabled() {
    return disableReflectedEntityCache;
}

public static void setReflectedEntityCacheDisabled(boolean disableReflectedEntityCache) {
    if (reflectedEntityCache != null && disableReflectedEntityCache) {
        reflectedEntityCache.clear();
    }

    TableServiceEntity.disableReflectedEntityCache = disableReflectedEntityCache;
}

public void readEntity(HashMap<String, EntityProperty> properties, OperationContext opContext) throws StorageException {
    try {
        readEntityWithReflection(this, properties, opContext);
    } catch (IllegalArgumentException var4) {
        throw new StorageException("InvalidDocument", "The response received is invalid or improperly formatted.", 306, (StorageExtendedErrorInformation)null, var4);
    } catch (IllegalAccessException var5) {
        throw new StorageException("InvalidDocument", "The entity threw an exception during deserialization.", 306, (StorageExtendedErrorInformation)null, var5);
    } catch (InvocationTargetException var6) {
        throw new StorageException("InternalError", "The entity threw an exception during deserialization.", 306, (StorageExtendedErrorInformation)null, var6);
    }
}

public void setEtag(String etag) {
    this.etag = etag;
}

public void setPartitionKey(String partitionKey) {
    this.partitionKey = partitionKey;
}

public void setRowKey(String rowKey) {
    this.rowKey = rowKey;
}

public void setTimestamp(Date timeStamp) {
    this.timeStamp = timeStamp;
}

public HashMap<String, EntityProperty> writeEntity(OperationContext opContext) throws StorageException {
    try {
        return writeEntityWithReflection(this);
    } catch (IllegalAccessException var3) {
        throw new StorageException("InternalError", "An attempt was made to access an inaccessible member of the entity during serialization.", 306, (StorageExtendedErrorInformation)null, var3);
    } catch (InvocationTargetException var4) {
        throw new StorageException("InternalError", "The entity threw an exception during serialization.", 306, (StorageExtendedErrorInformation)null, var4);
    }
}

private static ConcurrentHashMap<Class<?>, HashMap<String, PropertyPair>> initialize() {
    Runtime runtime = Runtime.getRuntime();
    int numberOfProcessors = runtime.availableProcessors();
    return new ConcurrentHashMap(31, 0.75F, numberOfProcessors * 4);
}

protected static ConcurrentHashMap<Class<?>, HashMap<String, PropertyPair>> getReflectedEntityCache() {
    return reflectedEntityCache;
}

}

标签: javaazurestorage

解决方案


最后我的问题:当使用 GSON 从 API 调用反序列化我的 json 时,GSON 不会调用我的父类的构造函数来在时间戳上创建新日期。

我的问题有两个解决方案:

  1. 创建一个默认构造函数,它也调用父构造函数。(这应该是我第一次去也是最简单的,但我没有想到这个)
  2. 为调用构造函数的类创建一个自定义反序列化器,如下面的代码所示。

自定义解串器

public class PersonDeserializer implements JsonDeserializer<Person> {
@Override
public Person deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    return new Person(
            jsonObject.get("teamName").getAsString(),
            jsonObject.get("name").getAsString(),
            jsonObject.get("surname").getAsString(),
            jsonObject.get("email").getAsString(),
            jsonObject.get("permissionLevel").getAsInt()
    );
}

}


推荐阅读