Search in sources :

Example 1 with InvalidTokenException

use of org.datatransferproject.spi.transfer.types.InvalidTokenException in project data-transfer-project by google.

the class GooglePhotosExporterTest method exportAlbumFirstSet.

@Test
public void exportAlbumFirstSet() throws IOException, InvalidTokenException, PermissionDeniedException {
    setUpSingleAlbum();
    when(albumListResponse.getNextPageToken()).thenReturn(ALBUM_TOKEN);
    // Run test
    ExportResult<PhotosContainerResource> result = googlePhotosExporter.exportAlbums(null, Optional.empty(), uuid);
    // Check results
    // Verify correct methods were called
    verify(photosInterface).listAlbums(Optional.empty());
    verify(albumListResponse).getAlbums();
    // Check pagination token
    ContinuationData continuationData = result.getContinuationData();
    StringPaginationToken paginationToken = (StringPaginationToken) continuationData.getPaginationData();
    assertThat(paginationToken.getToken()).isEqualTo(ALBUM_TOKEN_PREFIX + ALBUM_TOKEN);
    // Check albums field of container
    Collection<PhotoAlbum> actualAlbums = result.getExportedData().getAlbums();
    assertThat(actualAlbums.stream().map(PhotoAlbum::getId).collect(Collectors.toList())).containsExactly(ALBUM_ID);
    // Check photos field of container (should be empty, even though there is a photo in the
    // original album)
    Collection<PhotoModel> actualPhotos = result.getExportedData().getPhotos();
    assertThat(actualPhotos).isEmpty();
    // Should be one container in the resource list
    List<ContainerResource> actualResources = continuationData.getContainerResources();
    assertThat(actualResources.stream().map(a -> ((IdOnlyContainerResource) a).getId()).collect(Collectors.toList())).containsExactly(ALBUM_ID);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ALBUM_TOKEN_PREFIX(org.datatransferproject.datatransfer.google.photos.GooglePhotosExporter.ALBUM_TOKEN_PREFIX) GoogleMediaItem(org.datatransferproject.datatransfer.google.mediaModels.GoogleMediaItem) ExportResult(org.datatransferproject.spi.transfer.provider.ExportResult) PhotoAlbum(org.datatransferproject.types.common.models.photos.PhotoAlbum) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) PhotosContainerResource(org.datatransferproject.types.common.models.photos.PhotosContainerResource) PermissionDeniedException(org.datatransferproject.spi.transfer.types.PermissionDeniedException) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) AlbumListResponse(org.datatransferproject.datatransfer.google.mediaModels.AlbumListResponse) MediaMetadata(org.datatransferproject.datatransfer.google.mediaModels.MediaMetadata) TemporaryPerJobDataStore(org.datatransferproject.spi.cloud.storage.TemporaryPerJobDataStore) ArgumentCaptor(org.mockito.ArgumentCaptor) StringPaginationToken(org.datatransferproject.types.common.StringPaginationToken) PhotoModel(org.datatransferproject.types.common.models.photos.PhotoModel) InputStreamWrapper(org.datatransferproject.spi.cloud.storage.TemporaryPerJobDataStore.InputStreamWrapper) GoogleCredentialFactory(org.datatransferproject.datatransfer.google.common.GoogleCredentialFactory) Before(org.junit.Before) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) ContainerResource(org.datatransferproject.types.common.models.ContainerResource) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) UUID(java.util.UUID) PaginationData(org.datatransferproject.types.common.PaginationData) Truth.assertThat(com.google.common.truth.Truth.assertThat) Photo(org.datatransferproject.datatransfer.google.mediaModels.Photo) Collectors(java.util.stream.Collectors) IdOnlyContainerResource(org.datatransferproject.types.common.models.IdOnlyContainerResource) Mockito.verify(org.mockito.Mockito.verify) PHOTO_TOKEN_PREFIX(org.datatransferproject.datatransfer.google.photos.GooglePhotosExporter.PHOTO_TOKEN_PREFIX) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Monitor(org.datatransferproject.api.launcher.Monitor) MediaItemSearchResponse(org.datatransferproject.datatransfer.google.mediaModels.MediaItemSearchResponse) TempPhotosData(org.datatransferproject.spi.transfer.types.TempPhotosData) Optional(java.util.Optional) ContinuationData(org.datatransferproject.spi.transfer.types.ContinuationData) GoogleAlbum(org.datatransferproject.datatransfer.google.mediaModels.GoogleAlbum) InvalidTokenException(org.datatransferproject.spi.transfer.types.InvalidTokenException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) InputStream(java.io.InputStream) PhotosContainerResource(org.datatransferproject.types.common.models.photos.PhotosContainerResource) PhotosContainerResource(org.datatransferproject.types.common.models.photos.PhotosContainerResource) ContainerResource(org.datatransferproject.types.common.models.ContainerResource) IdOnlyContainerResource(org.datatransferproject.types.common.models.IdOnlyContainerResource) PhotoModel(org.datatransferproject.types.common.models.photos.PhotoModel) IdOnlyContainerResource(org.datatransferproject.types.common.models.IdOnlyContainerResource) ContinuationData(org.datatransferproject.spi.transfer.types.ContinuationData) PhotoAlbum(org.datatransferproject.types.common.models.photos.PhotoAlbum) StringPaginationToken(org.datatransferproject.types.common.StringPaginationToken) Test(org.junit.Test)

Example 2 with InvalidTokenException

use of org.datatransferproject.spi.transfer.types.InvalidTokenException in project data-transfer-project by google.

the class KoofrPhotosImporter method importSinglePhoto.

private String importSinglePhoto(PhotoModel photo, UUID jobId, IdempotentImportExecutor idempotentImportExecutor, KoofrClient koofrClient) throws IOException, InvalidTokenException, DestinationMemoryFullException {
    monitor.debug(() -> String.format("Import single photo %s", photo.getTitle()));
    BufferedInputStream inputStream = null;
    try {
        if (photo.isInTempStore()) {
            inputStream = new BufferedInputStream(jobStore.getStream(jobId, photo.getFetchableUrl()).getStream());
        } else if (photo.getFetchableUrl() != null) {
            HttpURLConnection conn = imageStreamProvider.getConnection(photo.getFetchableUrl());
            inputStream = new BufferedInputStream(conn.getInputStream());
        } else {
            throw new IllegalStateException("Don't know how to get the inputStream for " + photo.getTitle());
        }
        final byte[] bytes = IOUtils.toByteArray(inputStream);
        Date dateCreated = getDateCreated(photo, bytes);
        String title = buildPhotoTitle(jobId, photo.getTitle(), dateCreated);
        String description = KoofrClient.trimDescription(photo.getDescription());
        String parentPath = idempotentImportExecutor.getCachedValue(photo.getAlbumId());
        String fullPath = parentPath + "/" + title;
        if (koofrClient.fileExists(fullPath)) {
            monitor.debug(() -> String.format("Photo already exists %s", photo.getTitle()));
            return fullPath;
        }
        final ByteArrayInputStream inMemoryInputStream = new ByteArrayInputStream(bytes);
        String response = koofrClient.uploadFile(parentPath, title, inMemoryInputStream, photo.getMediaType(), dateCreated, description);
        try {
            if (photo.isInTempStore()) {
                jobStore.removeData(jobId, photo.getFetchableUrl());
            }
        } catch (Exception e) {
            // Swallow the exception caused by Remove data so that existing flows continue
            monitor.info(() -> format("Exception swallowed while removing data for jobId %s, localPath %s", jobId, photo.getFetchableUrl()), e);
        }
        return response;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Date(java.util.Date) DestinationMemoryFullException(org.datatransferproject.spi.transfer.types.DestinationMemoryFullException) IOException(java.io.IOException) InvalidTokenException(org.datatransferproject.spi.transfer.types.InvalidTokenException)

Example 3 with InvalidTokenException

use of org.datatransferproject.spi.transfer.types.InvalidTokenException in project data-transfer-project by google.

the class KoofrClient method uploadFile.

@SuppressWarnings("unchecked")
public String uploadFile(String parentPath, String name, InputStream inputStream, String mediaType, Date modified, String description) throws IOException, InvalidTokenException, DestinationMemoryFullException {
    String url;
    try {
        URIBuilder builder = getUriBuilder().setPath(CONTENT_API_PATH_PREFIX + "/mounts/primary/files/put").setParameter("path", parentPath).setParameter("filename", name).setParameter("autorename", "true").setParameter("info", "true");
        if (description != null && description.length() > 0) {
            builder.setParameter("tags", "description=" + description);
        }
        if (modified != null) {
            builder.setParameter("modified", Long.toString(modified.getTime()));
        }
        url = builder.build().toString();
    } catch (URISyntaxException e) {
        throw new IllegalStateException("Could not produce url.", e);
    }
    Request.Builder requestBuilder = getRequestBuilder(url);
    RequestBody uploadBody = new InputStreamRequestBody(MediaType.parse(mediaType), inputStream);
    requestBuilder.post(uploadBody);
    // We need to reset the input stream because the request could already read some data
    try (Response response = getResponse(fileUploadClient, requestBuilder, () -> inputStream.reset())) {
        int code = response.code();
        ResponseBody body = response.body();
        if (code == 413) {
            throw new DestinationMemoryFullException("Koofr quota exceeded", new Exception("Koofr file upload response code " + code));
        }
        if (code < 200 || code > 299) {
            throw new IOException("Got error code: " + code + " message: " + response.message() + " body: " + body.string());
        }
        Map<String, Object> responseData = objectMapper.readValue(body.bytes(), Map.class);
        String newName = (String) responseData.get("name");
        Preconditions.checkState(!Strings.isNullOrEmpty(newName), "Expected name value to be present in %s", responseData);
        return parentPath + "/" + newName;
    }
}
Also used : DestinationMemoryFullException(org.datatransferproject.spi.transfer.types.DestinationMemoryFullException) Request(okhttp3.Request) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) DestinationMemoryFullException(org.datatransferproject.spi.transfer.types.DestinationMemoryFullException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) InvalidTokenException(org.datatransferproject.spi.transfer.types.InvalidTokenException) URIBuilder(org.apache.http.client.utils.URIBuilder) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) RequestBody(okhttp3.RequestBody)

Example 4 with InvalidTokenException

use of org.datatransferproject.spi.transfer.types.InvalidTokenException in project data-transfer-project by google.

the class KoofrClientTest method testFileExistsRefreshTokenNotFound.

@Test
public void testFileExistsRefreshTokenNotFound() throws Exception {
    when(credentialFactory.refreshCredential(credential)).then((InvocationOnMock invocation) -> {
        throw new InvalidTokenException("Unable to refresh token.", null);
    });
    server.enqueue(new MockResponse().setResponseCode(401));
    InvalidTokenException caughtExc = null;
    try {
        client.fileExists("/path/to/file");
    } catch (InvalidTokenException exc) {
        caughtExc = exc;
    }
    Assert.assertNotNull(caughtExc);
    Assert.assertEquals("Unable to refresh token.", caughtExc.getMessage());
    Assert.assertEquals(1, server.getRequestCount());
    RecordedRequest recordedRequest = server.takeRequest();
    Assert.assertEquals("GET", recordedRequest.getMethod());
    Assert.assertEquals("/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath());
    Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization"));
    Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) InvalidTokenException(org.datatransferproject.spi.transfer.types.InvalidTokenException) MockResponse(okhttp3.mockwebserver.MockResponse) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Aggregations

InvalidTokenException (org.datatransferproject.spi.transfer.types.InvalidTokenException)4 IOException (java.io.IOException)3 DestinationMemoryFullException (org.datatransferproject.spi.transfer.types.DestinationMemoryFullException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)1 Truth.assertThat (com.google.common.truth.Truth.assertThat)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 HttpURLConnection (java.net.HttpURLConnection)1 URISyntaxException (java.net.URISyntaxException)1 Collection (java.util.Collection)1 Date (java.util.Date)1 List (java.util.List)1 Optional (java.util.Optional)1 UUID (java.util.UUID)1 Collectors (java.util.stream.Collectors)1 Request (okhttp3.Request)1 RequestBody (okhttp3.RequestBody)1 Response (okhttp3.Response)1