Search in sources :

Example 1 with IdempotentImportExecutor

use of org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor in project data-transfer-project by google.

the class GoogleBloggerImporter method insertActivity.

private void insertActivity(IdempotentImportExecutor idempotentExecutor, SocialActivityActor actor, SocialActivityModel activity, String blogId, TokensAndUrlAuthData authData) throws Exception {
    String content = activity.getContent() == null ? "" : activity.getContent();
    Collection<SocialActivityAttachment> linkAttachments = activity.getAttachments().stream().filter(attachment -> attachment.getType() == SocialActivityAttachmentType.LINK).collect(Collectors.toList());
    Collection<SocialActivityAttachment> imageAttachments = activity.getAttachments().stream().filter(attachment -> attachment.getType() == SocialActivityAttachmentType.IMAGE).collect(Collectors.toList());
    // don't know how they were laid out in the originating service.
    for (SocialActivityAttachment attachment : linkAttachments) {
        content = "<a href=\"" + attachment.getUrl() + "\">" + attachment.getName() + "</a>\n</hr>\n" + content;
    }
    if (!imageAttachments.isEmpty()) {
        // Store any attached images in Drive in a new folder.
        Drive driveInterface = getOrCreateDriveService(authData);
        String folderId = idempotentExecutor.executeOrThrowException("MainAlbum", "Photo Album", () -> createAlbumFolder(driveInterface));
        for (SocialActivityAttachment image : imageAttachments) {
            try {
                String newImgSrc = idempotentExecutor.executeAndSwallowIOExceptions(image.toString(), "Image", () -> uploadImage(image, driveInterface, folderId));
                content += "\n<hr/><img src=\"" + newImgSrc + "\">";
            } catch (RuntimeException e) {
                throw new IOException("Couldn't import: " + imageAttachments, e);
            }
        }
    }
    String title = "";
    if (activity.getTitle() != null && !Strings.isNullOrEmpty(activity.getTitle())) {
        title = activity.getTitle();
    }
    Post post = new Post().setTitle("Imported post: " + title).setContent(content);
    if (actor != null) {
        Post.Author author = new Post.Author();
        if (!Strings.isNullOrEmpty(actor.getName())) {
            author.setDisplayName(actor.getName());
        }
        if (!Strings.isNullOrEmpty(actor.getUrl())) {
            author.setUrl(actor.getUrl());
        }
        post.setAuthor(author);
    }
    if (activity.getPublished() != null) {
        post.setPublished(new DateTime(activity.getPublished().toEpochMilli()));
    }
    idempotentExecutor.executeAndSwallowIOExceptions(title, title, () -> getOrCreateBloggerService(authData).posts().insert(blogId, post).setIsDraft(true).execute().getId());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Blogger(com.google.api.services.blogger.Blogger) ImportResult(org.datatransferproject.spi.transfer.provider.ImportResult) SocialActivityAttachment(org.datatransferproject.types.common.models.social.SocialActivityAttachment) Drive(com.google.api.services.drive.Drive) SocialActivityContainerResource(org.datatransferproject.types.common.models.social.SocialActivityContainerResource) Permission(com.google.api.services.drive.model.Permission) GoogleStaticObjects(org.datatransferproject.datatransfer.google.common.GoogleStaticObjects) Strings(com.google.common.base.Strings) DateTime(com.google.api.client.util.DateTime) ImmutableList(com.google.common.collect.ImmutableList) Post(com.google.api.services.blogger.model.Post) ResultType(org.datatransferproject.spi.transfer.provider.ImportResult.ResultType) BlogList(com.google.api.services.blogger.model.BlogList) File(com.google.api.services.drive.model.File) SocialActivityActor(org.datatransferproject.types.common.models.social.SocialActivityActor) Credential(com.google.api.client.auth.oauth2.Credential) Importer(org.datatransferproject.spi.transfer.provider.Importer) GoogleCredentialFactory(org.datatransferproject.datatransfer.google.common.GoogleCredentialFactory) ImageStreamProvider(org.datatransferproject.transfer.ImageStreamProvider) IdempotentImportExecutor(org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor) Collection(java.util.Collection) SocialActivityType(org.datatransferproject.types.common.models.social.SocialActivityType) IOException(java.io.IOException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Stream(java.util.stream.Stream) TokensAndUrlAuthData(org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData) InputStreamContent(com.google.api.client.http.InputStreamContent) LocalDate(java.time.LocalDate) SocialActivityAttachmentType(org.datatransferproject.types.common.models.social.SocialActivityAttachmentType) SocialActivityModel(org.datatransferproject.types.common.models.social.SocialActivityModel) InputStream(java.io.InputStream) Post(com.google.api.services.blogger.model.Post) Drive(com.google.api.services.drive.Drive) SocialActivityAttachment(org.datatransferproject.types.common.models.social.SocialActivityAttachment) IOException(java.io.IOException) DateTime(com.google.api.client.util.DateTime)

Example 2 with IdempotentImportExecutor

use of org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor in project data-transfer-project by google.

the class MicrosoftContactsImporter method importItem.

@Override
public ImportResult importItem(UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokenAuthData authData, ContactsModelWrapper wrapper) {
    JCardReader reader = new JCardReader(wrapper.getVCards());
    try {
        List<VCard> cards = reader.readAll();
        List<String> problems = new ArrayList<>();
        int[] id = new int[] { 1 };
        List<Map<String, Object>> requests = cards.stream().map(card -> {
            TransformResult<LinkedHashMap> result = transformerService.transform(LinkedHashMap.class, card);
            problems.addAll(result.getProblems());
            LinkedHashMap contact = result.getTransformed();
            Map<String, Object> request = createRequest(id[0], CONTACTS_URL, contact);
            id[0]++;
            return request;
        }).collect(toList());
        if (!problems.isEmpty()) {
        // TODO log problems
        }
        return batchRequest(authData, requests, baseUrl, client, objectMapper).getResult();
    } catch (IOException e) {
        // TODO log
        e.printStackTrace();
        return new ImportResult(e);
    }
}
Also used : VCard(ezvcard.VCard) IdempotentImportExecutor(org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor) ImportResult(org.datatransferproject.spi.transfer.provider.ImportResult) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) UUID(java.util.UUID) RequestHelper.createRequest(org.datatransferproject.transfer.microsoft.common.RequestHelper.createRequest) TokenAuthData(org.datatransferproject.types.transfer.auth.TokenAuthData) ArrayList(java.util.ArrayList) TransformerService(org.datatransferproject.transfer.microsoft.transformer.TransformerService) LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) OkHttpClient(okhttp3.OkHttpClient) TransformResult(org.datatransferproject.transfer.microsoft.transformer.TransformResult) Map(java.util.Map) JCardReader(ezvcard.io.json.JCardReader) ContactsModelWrapper(org.datatransferproject.types.common.models.contacts.ContactsModelWrapper) Importer(org.datatransferproject.spi.transfer.provider.Importer) RequestHelper.batchRequest(org.datatransferproject.transfer.microsoft.common.RequestHelper.batchRequest) TransformResult(org.datatransferproject.transfer.microsoft.transformer.TransformResult) ImportResult(org.datatransferproject.spi.transfer.provider.ImportResult) ArrayList(java.util.ArrayList) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) JCardReader(ezvcard.io.json.JCardReader) VCard(ezvcard.VCard) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 3 with IdempotentImportExecutor

use of org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor in project data-transfer-project by google.

the class WorkerMain method initialize.

public void initialize() {
    Monitor monitor = loadMonitor();
    SettingsExtension settingsExtension = getSettingsExtension();
    settingsExtension.initialize();
    WorkerExtensionContext extensionContext = new WorkerExtensionContext(settingsExtension, monitor);
    // TODO this should be moved into a service extension
    extensionContext.registerService(HttpTransport.class, new NetHttpTransport());
    extensionContext.registerService(OkHttpClient.class, new OkHttpClient.Builder().build());
    extensionContext.registerService(JsonFactory.class, new JacksonFactory());
    ServiceLoader.load(ServiceExtension.class).iterator().forEachRemaining(serviceExtension -> serviceExtension.initialize(extensionContext));
    // TODO: verify that this is the cloud extension that is specified in the configuration
    CloudExtension cloudExtension = getCloudExtension();
    cloudExtension.initialize(extensionContext);
    monitor.info(() -> "Using CloudExtension: " + cloudExtension.getClass().getName());
    JobStore jobStore = cloudExtension.getJobStore();
    extensionContext.registerService(JobStore.class, jobStore);
    extensionContext.registerService(TemporaryPerJobDataStore.class, jobStore);
    AppCredentialStore appCredentialStore = cloudExtension.getAppCredentialStore();
    extensionContext.registerService(AppCredentialStore.class, appCredentialStore);
    List<TransferExtension> transferExtensions = getTransferExtensions(monitor);
    // Load security extension and services
    SecurityExtension securityExtension = SecurityExtensionLoader.getSecurityExtension(extensionContext);
    monitor.info(() -> "Using SecurityExtension: " + securityExtension.getClass().getName());
    IdempotentImportExecutor idempotentImportExecutor = IdempotentImportExecutorLoader.load(extensionContext);
    monitor.info(() -> "Using IdempotentImportExecutor: " + idempotentImportExecutor.getClass().getName());
    // TODO: make configurable
    SymmetricKeyGenerator symmetricKeyGenerator = new AesSymmetricKeyGenerator(monitor);
    JobHooks jobHooks = loadJobHooks();
    Injector injector = null;
    try {
        injector = Guice.createInjector(new WorkerModule(extensionContext, cloudExtension, transferExtensions, securityExtension, idempotentImportExecutor, symmetricKeyGenerator, jobHooks));
    } catch (Exception e) {
        monitor.severe(() -> "Unable to initialize Guice in Worker", e);
        throw e;
    }
    worker = injector.getInstance(Worker.class);
    // Reset the JobMetadata in case set previously when running SingleVMMain
    JobMetadata.reset();
}
Also used : AppCredentialStore(org.datatransferproject.spi.cloud.storage.AppCredentialStore) JobHooks(org.datatransferproject.spi.transfer.hooks.JobHooks) JobHooksLoader.loadJobHooks(org.datatransferproject.spi.transfer.hooks.JobHooksLoader.loadJobHooks) JobStore(org.datatransferproject.spi.cloud.storage.JobStore) SecurityExtension(org.datatransferproject.spi.transfer.security.SecurityExtension) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) IdempotentImportExecutor(org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor) SettingsExtension(org.datatransferproject.config.extension.SettingsExtension) SettingsExtensionLoader.getSettingsExtension(org.datatransferproject.config.extension.SettingsExtensionLoader.getSettingsExtension) MonitorLoader.loadMonitor(org.datatransferproject.launcher.monitor.MonitorLoader.loadMonitor) Monitor(org.datatransferproject.api.launcher.Monitor) CloudExtension(org.datatransferproject.spi.cloud.extension.CloudExtension) CloudExtensionLoader.getCloudExtension(org.datatransferproject.spi.cloud.extension.CloudExtensionLoader.getCloudExtension) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) SymmetricKeyGenerator(org.datatransferproject.security.SymmetricKeyGenerator) AesSymmetricKeyGenerator(org.datatransferproject.security.AesSymmetricKeyGenerator) Injector(com.google.inject.Injector) TransferExtension(org.datatransferproject.spi.transfer.extension.TransferExtension) AesSymmetricKeyGenerator(org.datatransferproject.security.AesSymmetricKeyGenerator)

Example 4 with IdempotentImportExecutor

use of org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor in project data-transfer-project by google.

the class GoogleVideosImporter method importItem.

@Override
public ImportResult importItem(UUID jobId, IdempotentImportExecutor executor, TokensAndUrlAuthData authData, VideosContainerResource data) throws Exception {
    if (data == null) {
        // Nothing to do
        return ImportResult.OK;
    }
    PhotosLibraryClient client;
    if (clientsMap.containsKey(jobId)) {
        client = clientsMap.get(jobId);
    } else {
        PhotosLibrarySettings settings = PhotosLibrarySettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(UserCredentials.newBuilder().setClientId(appCredentials.getKey()).setClientSecret(appCredentials.getSecret()).setAccessToken(new AccessToken(authData.getAccessToken(), new Date())).setRefreshToken(authData.getRefreshToken()).build())).build();
        client = PhotosLibraryClient.initialize(settings);
        clientsMap.put(jobId, client);
    }
    long bytes = 0L;
    // Uploads videos
    final Collection<VideoModel> videos = data.getVideos();
    if (videos != null && videos.size() > 0) {
        Stream<VideoModel> stream = videos.stream().filter(video -> shouldImport(video, executor)).map(this::transformVideoName);
        // We partition into groups of 49 as 50 is the maximum number of items that can be created in
        // one call. (We use 49 to avoid potential off by one errors)
        // https://developers.google.com/photos/library/guides/upload-media#creating-media-item
        final UnmodifiableIterator<List<VideoModel>> batches = Iterators.partition(stream.iterator(), 49);
        while (batches.hasNext()) {
            long batchBytes = importVideoBatch(batches.next(), client, executor);
            bytes += batchBytes;
        }
    }
    final ImportResult result = ImportResult.OK;
    return result.copyWithBytes(bytes);
}
Also used : RandomAccessFile(java.io.RandomAccessFile) DestinationMemoryFullException(org.datatransferproject.spi.transfer.types.DestinationMemoryFullException) Error(com.google.photos.library.v1.upload.UploadMediaItemResponse.Error) ImportResult(org.datatransferproject.spi.transfer.provider.ImportResult) Date(java.util.Date) PhotosLibrarySettings(com.google.photos.library.v1.PhotosLibrarySettings) FixedCredentialsProvider(com.google.api.gax.core.FixedCredentialsProvider) HashMap(java.util.HashMap) AppCredentials(org.datatransferproject.types.transfer.auth.AppCredentials) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) TemporaryPerJobDataStore(org.datatransferproject.spi.cloud.storage.TemporaryPerJobDataStore) Strings(com.google.common.base.Strings) NewMediaItem(com.google.photos.library.v1.proto.NewMediaItem) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) Importer(org.datatransferproject.spi.transfer.provider.Importer) UploadMediaItemRequest(com.google.photos.library.v1.upload.UploadMediaItemRequest) NewMediaItemFactory(com.google.photos.library.v1.util.NewMediaItemFactory) Code(com.google.rpc.Code) ImageStreamProvider(org.datatransferproject.transfer.ImageStreamProvider) PhotosLibraryClient(com.google.photos.library.v1.PhotosLibraryClient) IdempotentImportExecutor(org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor) UploadErrorException(org.datatransferproject.spi.transfer.types.UploadErrorException) Collection(java.util.Collection) Status(com.google.rpc.Status) MediaObject(org.datatransferproject.types.common.models.MediaObject) IOException(java.io.IOException) NewMediaItemResult(com.google.photos.library.v1.proto.NewMediaItemResult) UUID(java.util.UUID) UserCredentials(com.google.auth.oauth2.UserCredentials) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) VideosContainerResource(org.datatransferproject.types.common.models.videos.VideosContainerResource) BatchCreateMediaItemsResponse(com.google.photos.library.v1.proto.BatchCreateMediaItemsResponse) List(java.util.List) Stream(java.util.stream.Stream) Monitor(org.datatransferproject.api.launcher.Monitor) TokensAndUrlAuthData(org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData) InvalidArgumentException(com.google.api.gax.rpc.InvalidArgumentException) VideoModel(org.datatransferproject.types.common.models.videos.VideoModel) Preconditions(com.google.common.base.Preconditions) UploadMediaItemResponse(com.google.photos.library.v1.upload.UploadMediaItemResponse) VisibleForTesting(com.google.common.annotations.VisibleForTesting) UnmodifiableIterator(com.google.common.collect.UnmodifiableIterator) AccessToken(com.google.auth.oauth2.AccessToken) InputStream(java.io.InputStream) ImportResult(org.datatransferproject.spi.transfer.provider.ImportResult) AccessToken(com.google.auth.oauth2.AccessToken) PhotosLibrarySettings(com.google.photos.library.v1.PhotosLibrarySettings) ArrayList(java.util.ArrayList) List(java.util.List) PhotosLibraryClient(com.google.photos.library.v1.PhotosLibraryClient) VideoModel(org.datatransferproject.types.common.models.videos.VideoModel) Date(java.util.Date)

Example 5 with IdempotentImportExecutor

use of org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor in project data-transfer-project by google.

the class DaybookPostsImporter method insertActivity.

private String insertActivity(IdempotentImportExecutor executor, SocialActivityModel activity, TokensAndUrlAuthData authData) throws IOException {
    Map<String, String> imageMap = new HashMap<>();
    Map<String, String> linkMap = new HashMap<>();
    String content = activity.getContent() == null ? "" : activity.getContent();
    String title = activity.getTitle() == null ? "" : activity.getTitle();
    String location = activity.getLocation() == null || activity.getLocation().getName() == null ? "" : activity.getLocation().getName();
    String published = activity.getPublished().toString() == null ? "" : activity.getPublished().toString();
    Request.Builder requestBuilder = new Request.Builder().url(baseUrl);
    requestBuilder.header("token", authData.getAccessToken());
    FormBody.Builder builder = new FormBody.Builder().add("type", "POSTS");
    builder.add("exporter", JobMetadata.getExportService());
    builder.add("content", content);
    builder.add("title", title);
    builder.add("location", location);
    builder.add("published", published);
    Collection<SocialActivityAttachment> linkAttachments = activity.getAttachments().stream().filter(attachment -> attachment.getType() == SocialActivityAttachmentType.LINK).collect(Collectors.toList());
    Collection<SocialActivityAttachment> imageAttachments = activity.getAttachments().stream().filter(attachment -> attachment.getType() == SocialActivityAttachmentType.IMAGE).collect(Collectors.toList());
    // don't know how they were laid out in the originating service.
    if (!linkAttachments.isEmpty()) {
        for (SocialActivityAttachment attachment : linkAttachments) {
            linkMap.put(attachment.getName(), attachment.getUrl());
        }
        try {
            String json = objectMapper.writeValueAsString(linkMap);
            builder.add("link", json);
        } catch (JsonProcessingException e) {
            monitor.info(() -> String.format("Error processing JSON: %s", e.getMessage()));
        }
    }
    if (!imageAttachments.isEmpty()) {
        for (SocialActivityAttachment image : imageAttachments) {
            imageMap.put(image.getName() != null ? image.getName() : image.getUrl(), image.getUrl());
        }
        try {
            String json = objectMapper.writeValueAsString(imageMap);
            builder.add("image", json);
        } catch (JsonProcessingException e) {
            monitor.info(() -> String.format("Error processing JSON: %s", e.getMessage()));
        }
    }
    FormBody formBody = builder.build();
    requestBuilder.post(formBody);
    try (Response response = client.newCall(requestBuilder.build()).execute()) {
        int code = response.code();
        // Though sometimes it returns error code for success requests
        if (code < 200 || code > 299) {
            throw new IOException(String.format("Error occurred in request for adding entry, message: %s", response.message()));
        }
        return response.message();
    }
}
Also used : IdempotentImportExecutor(org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor) ImportResult(org.datatransferproject.spi.transfer.provider.ImportResult) SocialActivityAttachment(org.datatransferproject.types.common.models.social.SocialActivityAttachment) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SocialActivityContainerResource(org.datatransferproject.types.common.models.social.SocialActivityContainerResource) SocialActivityType(org.datatransferproject.types.common.models.social.SocialActivityType) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) HashMap(java.util.HashMap) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Monitor(org.datatransferproject.api.launcher.Monitor) TokensAndUrlAuthData(org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData) okhttp3(okhttp3) JobMetadata(org.datatransferproject.transfer.JobMetadata) Map(java.util.Map) SocialActivityAttachmentType(org.datatransferproject.types.common.models.social.SocialActivityAttachmentType) Importer(org.datatransferproject.spi.transfer.provider.Importer) SocialActivityModel(org.datatransferproject.types.common.models.social.SocialActivityModel) HashMap(java.util.HashMap) SocialActivityAttachment(org.datatransferproject.types.common.models.social.SocialActivityAttachment) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

IdempotentImportExecutor (org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor)5 IOException (java.io.IOException)4 UUID (java.util.UUID)4 ImportResult (org.datatransferproject.spi.transfer.provider.ImportResult)4 Importer (org.datatransferproject.spi.transfer.provider.Importer)4 Collection (java.util.Collection)3 Map (java.util.Map)3 Monitor (org.datatransferproject.api.launcher.Monitor)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Strings (com.google.common.base.Strings)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 TokensAndUrlAuthData (org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 Credential (com.google.api.client.auth.oauth2.Credential)1 InputStreamContent (com.google.api.client.http.InputStreamContent)1 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)1 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)1 DateTime (com.google.api.client.util.DateTime)1