如何在不具有涉及时钟/签名错误请从其他国家的客户端的机器上war文件?(How to run war

2019-09-30 16:13发布

我有一个基于Azure的服务Eclispe的Maven项目。 我想客户端的机器谁是来自另一个国家的运行,所以有不同的时区。

当我安装Eclipse他们的机器上并运行的所有服务,这些作品的罚款。 但是,当我加入战争到Apache文件夹,运行它,它给错误,如后:

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

我来到这个环节,我想我有几乎相同类型的错误:

StorageException与Java蔚蓝的blob

请告诉我怎么解决这个问题以及如何使在提供的链接的答复中提到时钟“缓慢”。

下面是代码:( 参见从第一种方法否则循环的代码它的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;

    }

什么样的变化,我应该在这里做?

Answer 1:

我以前曾经面临类似的问题。 什么,你需要做的是,让你的代码舒适的所有时区像GMT,IST,EST等。因为当你在其他国家的服务器上传的战争,你的代码必须是“聪明”不够了解那个国家的时区!

因此,这里是你可以做什么:

第1步:

在你的代码的第三部分,尝试通过客户端计算机的时区格林尼治标准时间一样,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”等这样的逻辑必须工作。 如果有任何错误,它张贴在编辑。 希望将工作。



Answer 2:

没有它,是很难说的代码,但是有一个机会,在客户端或服务器的时间不UTC或者错误地转换。

检查时间和机器的时区。 如果它们匹配,检查你的代码,如果使用UTC时间还是本地时间。



Answer 3:

每我的经验,这个问题是由该方法不正确的代码导致private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy获得通过UTC时间Calendar

作为参考,下面是我的示例代码使用来获得UTC时间Calendar

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());

接着,添加到期时间秒得到最终的日期时间。



文章来源: How to run war file on machine of client from another country without having error related to clock/ signature?