使用Java的Azure表存储时间戳不能为null

时间:2019-07-04 13:29:42

标签: java azure storage

我想将实体插入Azure表存储,但是每次我插入或替换时,都会出现一个异常“ IllegalArgumentException:该参数不能为null。参数名称:Timestamp”。

据我所知,我不应该设置时间戳,只需设置分区和行键,即可自动设置时间戳。我也在扩展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;
}

}

1 个答案:

答案 0 :(得分:0)

最后的问题:使用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()
    );
}

}