gpt4 book ai didi

java - 如何在来自其他国家/地区的客户端计算机上运行 war 文件而不出现与时钟/签名相关的错误?

转载 作者:行者123 更新时间:2023-11-30 06:37:53 28 4
gpt4 key购买 nike

我有基于Azure服务的eclispe maven项目。我想在来自另一个国家的客户计算机上运行它,因此有不同的时区。

当我在他们的机器上安装 eclipse 并运行所有服务时,这些工作正常。但是当我将 war 添加到 apache 文件夹时,运行它后,它会给出如下错误:

Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:)

我来到此链接,我认为我遇到了几乎相同类型的错误:

StorageException for azure blob with java

请告诉我如何解决这个问题以及如何使时钟“变慢”,如提供的链接的答案中所述。

这是代码:(请参阅第一个方法中 else 循环中的代码。这是与 blob 相关的代码。)

@Override
public JSONObject syncFiles(JSONObject jsonInput) throws InvalidKeyException, URISyntaxException {
if (jsonInput.containsKey("accountName")) {
CloudFileClient fileClient = null;
String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
+ jsonInput.get("accountName") + ";" + "AccountKey=" + jsonInput.get("accountKey");
System.out.println(storageConnectionString);
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
JSONObject jsonOutput = new JSONObject();
ArrayList fileList = new ArrayList<>();
try {
// fileClient =
// FileClientProvider.getFileClientReference(jsonOutput);
fileClient = storageAccount.createCloudFileClient();
String directoryName = jsonInput.get("directoryStructure").toString();

String[] directoryNameArray = directoryName.split("\\s*/\\s*");
System.out.println(directoryNameArray.length);

CloudFileShare share = fileClient.getShareReference(directoryNameArray[0].toLowerCase()
.replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
if (share.createIfNotExists()) {
System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
.replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
}
CloudFileDirectory rootDir = share.getRootDirectoryReference();
for (int i = 0; i < directoryNameArray.length; i++) {
String directoryToCreate = directoryNameArray[i];
CloudFileDirectory directory = rootDir.getDirectoryReference(directoryToCreate);

String directoryNameToListFiles = directory.getName();
if (i == directoryNameArray.length - 1) {
for (ListFileItem fileItem : directory.listFilesAndDirectories()) {
boolean isDirectory;
if (isDirectory = fileItem.getClass() == CloudFileDirectory.class) {
System.out.println("Directory Exists Here");
} else {
System.out.println("Name with files :" + fileItem.getUri().toString());
String downloadLocation = "/home/zcon/AzureDownloadedFiles";
String fileName[] = fileItem.getUri().toString().split("\\s*/\\s*");
for (int j = 0; j < fileName.length; j++) {
if (j == fileName.length - 1) {
String fileNameWithExtension = fileName[j];
File f = new File(downloadLocation + "/" + fileNameWithExtension);
String DownloadTo = f.toString();
f.createNewFile();
CloudFile cloudFile = directory
.getFileReference(fileNameWithExtension.replaceAll("%20", " "));
System.out.println("fileName===========" + fileNameWithExtension);
String tokenKey = testFileSAS(share, cloudFile);
cloudFile.downloadToFile(DownloadTo);
fileList.add(fileItem.getUri().toString() + "?" + tokenKey);
f.delete();
}
}
}
}
}
rootDir = directory;
}
ArrayList fileNamesList = new ArrayList<>();
for (int i = 0; i < fileList.size(); i++) {
String fileName[] = fileList.get(i).toString().split("\\s*/\\s*");
for (int j = 0; j < fileName.length; j++) {
if (j == fileName.length - 1) {
String fileNameReturn = fileName[j];
String[] fileNameReturnArray = fileNameReturn.split("\\.");
fileNamesList.add(fileNameReturnArray[0].replace("%20", " "));
}
}
}
jsonOutput.put("fileNamesList", fileNamesList);
jsonOutput.put("fileList", fileList);
jsonOutput.put("status", "successful");
} catch (Exception e) {
System.out.println("Exception is " + e.toString());
jsonOutput.put("status", "unsuccessful");
jsonOutput.put("exception", e.toString());
e.printStackTrace();
}
return jsonOutput;
} else {

CloudBlobClient blobClient = null;
String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
+ jsonInput.get("blobAccountName") + ";" + "AccountKey=" + jsonInput.get("blobAccountKey");
System.out.println(storageConnectionString);
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
JSONObject jsonOutput = new JSONObject();
ArrayList fileList = new ArrayList<>();
ArrayList fileNamesList = new ArrayList<>();
ArrayList blobItemList = new ArrayList<>();

try {
blobClient = storageAccount.createCloudBlobClient();
String directoryName = jsonInput.get("directoryStructure").toString();
String[] directoryNameArray = directoryName.split("\\s*/\\s*");
CloudBlobContainer container = blobClient.getContainerReference(directoryNameArray[0].toLowerCase()
.replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
if (container.createIfNotExists()) {
System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
.replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
}
// CloudBlockBlob blob =
// container.getBlockBlobReference(jsonInput.get("directoryStructure")+"/"+jsonInput.get("fileToCopy"));
CloudBlobDirectory directoryOfFile = container
.getDirectoryReference(jsonInput.get("directoryStructure").toString());
for (ListBlobItem blobItem : directoryOfFile.listBlobs()) {
// System.out.println(blobItem.getUri());
// fileList.add(blobItem.getUri());
blobItemList.add(blobItem);

}

for(int q= 0; q<blobItemList.size(); q++){
if(blobItemList.get(q).getClass()==CloudBlobDirectory.class)
{
blobItemList.remove(q);
}
}
System.out.println(blobItemList);
for (int l = 0; l < blobItemList.size(); l++) {
CloudBlob blob = (CloudBlob) blobItemList.get(l);
if (blob.getUri().toString().contains("Temp.txt")) {
System.out.println("Temp file was skipped");
} else {
String tokenKey = testBlobSaS(blob, container);
fileList.add(blob.getUri().toString() + "?" + tokenKey);
}
}
System.out.println("size of blobItemList is=============" + blobItemList.size());

for (int k = 0; k < fileList.size(); k++) {
String fileItem = fileList.get(k).toString();
String fileName[] = fileItem.split("\\s*/\\s*");

for (int j = 0; j < fileName.length; j++) {
if (j == fileName.length - 1) {
String fileNameWithExtension = fileName[j];
String[] parts = fileNameWithExtension.split("\\?");
System.out.println("fileName===========" + fileNameWithExtension);
fileNamesList.add(parts[0].replace("%20", " "));
}
}
}
jsonOutput.put("fileList", fileList);
jsonOutput.put("fileNamesList", fileNamesList);
jsonOutput.put("status", "successful");
System.out.println(fileList);
return jsonOutput;
} catch (Exception e) {
System.out.println("Exception is " + e.toString());
jsonOutput.put("status", "unsuccessful");
jsonOutput.put("exception", e.toString());
e.printStackTrace();
}
return jsonOutput;
}

}

创建 BlobSAS 的方法:

@Test
// @Category(SlowTests.class)
public String testBlobSaS(CloudBlob blob, CloudBlobContainer container) throws InvalidKeyException,
IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
SharedAccessBlobPolicy sp = createSharedAccessBlobPolicy(
EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 100);
BlobContainerPermissions perms = new BlobContainerPermissions();

perms.getSharedAccessPolicies().put("readperm", sp);
container.uploadPermissions(perms);
// Thread.sleep(30000);
String sas = blob.generateSharedAccessSignature(sp, null);

CloudBlockBlob sasBlob = new CloudBlockBlob(
new URI(blob.getUri().toString() + "?" + blob.generateSharedAccessSignature(null, "readperm")));
sasBlob.download(new ByteArrayOutputStream());

// do not give the client and check that the new blob's client has the
// correct perms
CloudBlob blobFromUri = new CloudBlockBlob(
PathUtility.addToQuery(blob.getStorageUri(), blob.generateSharedAccessSignature(null, "readperm")));
assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
blobFromUri.getServiceClient().getCredentials().getClass().toString());

// create credentials from sas
StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
blob.generateSharedAccessSignature(null, "readperm"));
CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

CloudBlockBlob blobFromClient = bClient.getContainerReference(blob.getContainer().getName())
.getBlockBlobReference(blob.getName());
assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
blobFromClient.getServiceClient().getCredentials().getClass().toString());
assertEquals(bClient, blobFromClient.getServiceClient());
return sas;

}

创建共享访问 blob 策略的方法:

private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
int expireTimeInSeconds) {

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
cal.setTime(new Date());
cal.add(Calendar.YEAR, expireTimeInSeconds);
SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
policy.setPermissions(sap);
policy.setSharedAccessExpiryTime(cal.getTime());
return policy;

}

我应该在这里进行哪些更改?

最佳答案

我以前也遇到过类似的问题。你需要做的是,让你的代码适合所有时区,如 GMT、IST、EST 等。因为当你在另一个国家的服务器上上传 war 时,你的代码必须足够“聪明”才能理解该国家的时区!

因此,您可以执行以下操作:

第 1 步:

在代码的第三部分,尝试用客户端计算机的时区(例如 GMT、EST 等)替换“UTC”。

如果有效(而且我非常确定它会正常工作),请继续

第 2 步:

首先,我们将编写一些代码,以字符串形式为您提供当前时区,例如“印度标准时间”或“欧洲标准时间”等。

然后,我们将从所有单词中仅选取第一个字母,并创建一个类似“IST”或“EST”的字符串。

最后,我们将在代码第三部分中写入“UTC”的位置传递此字符串。

所以,这是代码:

private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
int expireTimeInSeconds) {
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
System.out.println("Current TimeZone is : " + timeZone.getDisplayName());
String x = timeZone.getDisplayName();
String[] myName = x.split(" ");
String s = "";
ArrayList zoneArray = new ArrayList<>();
char zone = 0;
for (int i = 0; i < myName.length; i++) {
s = myName[i];
System.out.print(s.charAt(0));
zone = s.charAt(0);
zoneArray.add(zone);
}
String timeZoneCurrent = s;
String timeZoneDynamic = zoneArray.toString().replace(",", "").replace(" ", "").replace("[", "").replace("]",
"");
System.out.println("Value of S==========" + timeZoneDynamic);
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(timeZoneDynamic));
cal.setTime(new Date());
cal.add(Calendar.YEAR, expireTimeInSeconds);
SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
policy.setPermissions(sap);
policy.setSharedAccessExpiryTime(cal.getTime());
return policy;
}

在此,timeZoneDynamic 具有“IST”、“GMT”等值。此逻辑必须有效。如果有任何错误,请在编辑中发布。希望这会起作用。

关于java - 如何在来自其他国家/地区的客户端计算机上运行 war 文件而不出现与时钟/签名相关的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44906619/

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