如何在没有来自时钟/签名相关错误的情况下在来自其他国家/地区的客户端计算机上运行war文件? [英] How to run war file on machine of client from another country without having error related to clock/ signature?

查看:73
本文介绍了如何在没有来自时钟/签名相关错误的情况下在来自其他国家/地区的客户端计算机上运行war文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have eclispe maven project based on Azure services. I want to run it on client's machine who is from another country, so have different time zone.

当我在他们的机器上安装eclipse并运行所有服务时,这些工作正常.但是,当我在apache文件夹中添加war之后,运行它后会出现类似

When I install eclipse on their machine and run all the services, those works fine. But when I added war to apache folder , after running it, it's giving error like :

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

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

I came to this link and I think I am having almost same type of error :

带有Java的天蓝色blob的StorageException

请告诉我如何解决此问题以及如何使时钟慢",如提供的链接的答案所述.

Please tell me how to solve this and how to make clock 'slow' as mentioned in the answer of provided link.

这是代码:(从第一种方法中查看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的方法:

Method to create 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策略的方法:

Method to create shared access blob policy :

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;

    }

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

What changes I should make here?

推荐答案

我之前也遇到过类似的问题.您需要做的是,使您的代码适应所有时区,例如GMT,IST,EST等.因为当您在其他国家/地区的服务器中上传战争信息时,您的代码必须足够聪明"才能理解该国家/地区的时区!

I have faced similar problem before. What you need to do is , make your code comfortable for all the time zones like GMT,IST,EST etc. Because when you upload war in server of another country, your code must be 'clever' enough to understand time zone of that country !

这就是您可以做的:

第1步:

在代码的第三部分中,尝试用客户端计算机所在的时区(例如GMT,EST等)替换"UTC".

In third part of your code , try replaceing "UTC" by your client machine's timezone like GMT,EST etc.

如果这行得通(并且我非常确定它将行得通),请继续

If that works (and I am pretty much sure that it will work fine) , go for

第2步:

首先,我们将编写一些代码,为您提供String中的当前时区,例如印度标准时间"或欧洲标准时间"等.

First of all we will code something that gives you current time zone in String like "Indian Standard Time" or "European Standard Time" etc.

然后,我们将仅从所有单词中选择第一个字母,并创建一个字符串,例如"IST"或"EST".

Then, we will pick only first letters from all words and make a String like "IST" or "EST".

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

At last, we will pass this String at place where you wrote "UTC" in third part of your code.

所以,这是代码:

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"等的值.此逻辑必须起作用.如果有任何错误,请将其发布在编辑中.希望能奏效.

In this, timeZoneDynamic has values like "IST" , "GMT" etc. This logic must work. If have any error, post it in edit. Hope that will work.

这篇关于如何在没有来自时钟/签名相关错误的情况下在来自其他国家/地区的客户端计算机上运行war文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆