gpt4 book ai didi

java - 使用 Java 的 Azure 表存储时间戳不得为 null

转载 作者:行者123 更新时间:2023-12-02 03:30:25 27 4
gpt4 key购买 nike

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

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

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

我的数据库插入类

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;
}

}

最佳答案

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

}

关于java - 使用 Java 的 Azure 表存储时间戳不得为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56889066/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com