如何在来自另一个国家的客户端机器上运行战争文件,而不会出现与时钟/签名相关的错误?



I have eclispe maven project based on Azure services.我想在来自另一个国家的客户的机器上运行它,所以有不同的时区。

当我在他们的机器上安装 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等。因为当您在另一个国家的服务器中上传战争时,您的代码必须足够"聪明"才能理解该国家的时区!

所以这是你可以做的:

第 1 步:

在代码的第三部分,尝试将"UTC"替换为客户端计算机的时区,如GMT,EST等。

如果这有效(我几乎可以肯定它会正常工作),请继续

第 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"等值。这个逻辑必须有效。如果有任何错误,请在编辑中发布。希望这会奏效。

没有代码很难说,但是客户端或服务器上的时间可能不是 UTC 或错误转换的。

检查机器的时间和时区。如果它们匹配,请检查您的代码是否使用了 UTC 时间或本地时间。

根据我的经验,该问题是由方法中的错误代码引起的private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy通过Calendar获取 UTC 时间。

作为参考,这是我使用Calendar获取 UTC 时间的示例代码。

Calendar cal = Calendar.getInstance() ;  
// Get the time zone offset
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);  
// Get the daylight-saving time offset 
int dstOffset = cal.get(Calendar.DST_OFFSET);  
// Reduce these offsets above from local time to get UTC time
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
System.out.println(cal.getTime());

然后,添加过期时间秒数以获取最终日期时间。

最新更新