Получение исключения в методе getServingUrl в java для облачного хранилища Google - PullRequest
0 голосов
/ 24 апреля 2020

Java файл класса выглядит следующим образом

public class GoogleCloudStorageTest {

    static String bucketName = "test-bucket";
    static String blobName = "ImageName.JPG";
    public static void main(String... args) throws Exception {
        String fileName = "E:\\ImageName.JPG";
        String jsonPath = "E:\\Json_File.json";

        Credentials credentials = GoogleCredentials. fromStream(new FileInputStream(jsonPath));

        Storage storage = StorageOptions.newBuilder().setCredentials(credentials)
                  .setProjectId("xxx-xxx").build().getService();

        Path imageFile = Paths.get(fileName);

        uploadFileToGoogleCloud(storage, imageFile);
        String servingUrl = servingurl(java.nio.file.Files.readAllBytes(imageFile));
        System.out.println(servingUrl);
    }

    //method to upload file to google cloud
    public static String uploadFileToGoogleCloud(Storage storage, Path zipFile) throws IOException {

        Hasher hasher = Hashing.crc32c().newHasher();
        byte[] bufferHash = new byte[1024];
        try(InputStream input = Files.newInputStream(zipFile)){
            int limit;
            while((limit = input.read(bufferHash))>=0) {
                hasher.putBytes(ByteBuffer.wrap(bufferHash,0,limit));

            }
        }
        BlobInfo blob = BlobInfo.newBuilder(bucketName,blobName).setContentType("APPLICATION/OCTET-STREAM")
                .setCrc32c(BaseEncoding.base64().encode(Ints.toByteArray(hasher.hash().asInt())))
                 .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Acl.Role.READER))))
                .build();

        try(WriteChannel writer = storage.writer(blob,Storage.BlobWriteOption.crc32cMatch())){
            byte[] buffer = new byte[1024];
            try (InputStream input = Files.newInputStream(zipFile)) {
                int limit;
                while((limit = input.read(buffer))>=0) {
                    try {
                        writer.write(ByteBuffer.wrap(buffer, 0, limit));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            writer.close();
        }
        return storage.get(bucketName).get(blobName).getMediaLink();

        }


    **public static String servingurl(byte[] imageBytes) throws IOException{
        ImagesService images = ImagesServiceFactory.getImagesService();
        ServingUrlOptions options = ServingUrlOptions.Builder
                .withGoogleStorageFileName("/gs/" + bucketName + "/"+blobName)
                .imageSize(150)
                .crop(true)
                .secureUrl(true);

        String url = images.getServingUrl(options);   //getting error at this line
        return url;
    }**
}

Это трассировка стека исключений

com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'blobstore' or call 'CreateEncodedGoogleStorageKey()' was not found.
    at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:109)
    at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:64)
    at com.google.appengine.api.blobstore.BlobstoreServiceImpl.createGsBlobKey(BlobstoreServiceImpl.java:304)
    at com.google.appengine.api.images.ImagesServiceImpl.getServingUrl(ImagesServiceImpl.java:266)
    at com.xxx.cloudStorage.GoogleCloudStorageTest.resizeImage(GoogleCloudStorageTest.java:100)
    at com.xxx.cloudStorage.GoogleCloudStorageTest.main(GoogleCloudStorageTest.java:51)

здесь я могу загрузить файл изображения в облако Google, но я не Кто-нибудь, пожалуйста, дайте мне знать, что какая-либо конфигурация отсутствует?

1 Ответ

0 голосов
/ 05 мая 2020

Ошибка указывает на то, что нет вызова для создания ключа хранилища. Попробуйте это:

String key = ""; // path to the image "/gs/mybucket/myfile.jpg"
ImagesService images = ImagesServiceFactory.getImagesService();
BlobstoreService blobstore = BlobstoreServiceFactory.getBlobstoreService();
BlobKey blobKey = blobstore.createGsBlobKey(key);
ServingUrlOptions opts = ServingUrlOptions.Builder
        .withBlobKey(blobKey)
        .imageSize(150)
        .crop(true)
        .secureUrl(true);
...