Example usage for com.google.api.client.googleapis.batch BatchRequest execute

List of usage examples for com.google.api.client.googleapis.batch BatchRequest execute

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.batch BatchRequest execute.

Prototype

public void execute() throws IOException 

Source Link

Document

Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.

Usage

From source file:calendariotaller.CalendarSample.java

License:Apache License

private static void addCalendarsUsingBatch() throws IOException {
    View.header("Add Calendars using Batch");
    BatchRequest batch = client.batch();

    // Create the callback.
    JsonBatchCallback<Calendar> callback = new JsonBatchCallback<Calendar>() {

        @Override// w  w  w  . j  ava2  s.c o m
        public void onSuccess(Calendar calendar, HttpHeaders responseHeaders) {
            View.display(calendar);
            addedCalendarsUsingBatch.add(calendar);
        }

        @Override
        public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
            System.out.println("Error Message: " + e.getMessage());
        }
    };

    // Create 2 Calendar Entries to insert.
    Calendar entry1 = new Calendar().setSummary("Calendar for Testing 1");
    client.calendars().insert(entry1).queue(batch, callback);

    Calendar entry2 = new Calendar().setSummary("Calendar for Testing 2");
    client.calendars().insert(entry2).queue(batch, callback);

    batch.execute();
}

From source file:calendariotaller.CalendarSample.java

License:Apache License

private static void deleteCalendarsUsingBatch() throws IOException {
    View.header("Delete Calendars Using Batch");
    BatchRequest batch = client.batch();
    for (Calendar calendar : addedCalendarsUsingBatch) {
        client.calendars().delete(calendar.getId()).queue(batch, new JsonBatchCallback<Void>() {

            @Override/*from w w w.  j a  va 2s  .c  o m*/
            public void onSuccess(Void content, HttpHeaders responseHeaders) {
                System.out.println("Delete is successful!");
            }

            @Override
            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
                System.out.println("Error Message: " + e.getMessage());
            }
        });
    }

    batch.execute();
}

From source file:calendar_cmdline_sample.CalendarSample.java

License:Apache License

@SuppressWarnings("unused")
private static void addCalendarsUsingBatch() throws IOException {
    View.header("Add Calendars using Batch");
    BatchRequest batch = client.batch();

    // Create the callback.
    JsonBatchCallback<Calendar> callback = new JsonBatchCallback<Calendar>() {

        @Override//from w w w. ja v a2 s .com
        public void onSuccess(Calendar calendar, HttpHeaders responseHeaders) {
            View.display(calendar);
            addedCalendarsUsingBatch.add(calendar);
        }

        @Override
        public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
            System.out.println("Error Message: " + e.getMessage());
        }
    };

    // Create 2 Calendar Entries to insert.
    Calendar entry1 = new Calendar().setSummary("Calendar for Testing 1");
    client.calendars().insert(entry1).queue(batch, callback);

    Calendar entry2 = new Calendar().setSummary("Calendar for Testing 2");
    client.calendars().insert(entry2).queue(batch, callback);

    batch.execute();
}

From source file:calendar_cmdline_sample.CalendarSample.java

License:Apache License

@SuppressWarnings("unused")
private static void deleteCalendarsUsingBatch() throws IOException {
    View.header("Delete Calendars Using Batch");
    BatchRequest batch = client.batch();
    for (Calendar calendar : addedCalendarsUsingBatch) {
        client.calendars().delete(calendar.getId()).queue(batch, new JsonBatchCallback<Void>() {

            @Override//from  w  ww  .  ja va  2s. c om
            public void onSuccess(Void content, HttpHeaders responseHeaders) {
                System.out.println("Delete is successful!");
            }

            @Override
            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
                System.out.println("Error Message: " + e.getMessage());
            }
        });
    }

    batch.execute();
}

From source file:ch.cyberduck.core.googledrive.DriveBatchDeleteFeature.java

License:Open Source License

@Override
public void delete(final List<Path> files, final LoginCallback prompt, final Callback callback)
        throws BackgroundException {
    final BatchRequest batch = session.getClient().batch();
    final List<BackgroundException> failures = new ArrayList<>();
    for (Path file : files) {
        try {/* w w  w  .  ja v  a2  s .  c o m*/
            session.getClient().files().delete(new DriveFileidProvider(session).getFileid(file)).queue(batch,
                    new JsonBatchCallback<Void>() {
                        @Override
                        public void onFailure(final GoogleJsonError e, final HttpHeaders responseHeaders)
                                throws IOException {
                            log.warn(String.format("Failure deleting %s. %s", file, e.getMessage()));
                            failures.add(new HttpResponseExceptionMappingService()
                                    .map(new HttpResponseException(e.getCode(), e.getMessage())));
                        }

                        @Override
                        public void onSuccess(final Void aVoid, final HttpHeaders responseHeaders)
                                throws IOException {
                            callback.delete(file);
                        }
                    });
        } catch (IOException e) {
            throw new DriveExceptionMappingService().map("Cannot delete {0}", e, file);
        }
    }
    try {
        batch.execute();
    } catch (IOException e) {
        throw new DriveExceptionMappingService().map(e);
    }
    for (BackgroundException e : failures) {
        throw e;
    }
}

From source file:com.bibibig.yeon.navitest.CalendarList.AsyncBatchInsertCalendarList.java

License:Apache License

@Override
protected void doInBackground() throws IOException {
    BatchRequest batch = client.batch();
    for (Calendar calendar : calendars) {
        client.calendars().insert(calendar).setFields(BasicInfo.CALFIELDS).queue(batch,
                new JsonBatchCallback<Calendar>() {

                    public void onSuccess(Calendar calendar, HttpHeaders headers) {
                        model.add(calendar);
                    }/*from   w  ww.j  a  v  a 2s.  c  om*/

                    @Override
                    public void onFailure(GoogleJsonError err, HttpHeaders headers) throws IOException {
                        Utils.logAndShowError(activity, MainActivity.TAG, err.getMessage());
                    }
                });
    }
    batch.execute();
}

From source file:com.example.eventgooglecalendar.asynctasks.AsyncBatchInsertCalendars.java

License:Apache License

@Override
protected void doInBackground() throws IOException {
    BatchRequest batch = client.batch();
    for (Calendar calendar : calendars) {
        client.calendars().insert(calendar).setFields(CalendarInfo.FIELDS).queue(batch,
                new JsonBatchCallback<Calendar>() {

                    public void onSuccess(Calendar calendar, HttpHeaders headers) {
                        model.add(calendar);
                    }/* w  w w  . j a va 2s.co  m*/

                    @Override
                    public void onFailure(GoogleJsonError err, HttpHeaders headers) throws IOException {
                        Utils.logAndShowError(activity, CalendarSampleActivity.TAG, err.getMessage());
                    }
                });
    }
    batch.execute();
}

From source file:com.farlo.meetupsample.servlet.MainServlet.java

License:Apache License

/**
 * Do stuff when buttons on index.jsp are clicked
 *///  w  ww  . j  av  a 2  s  . co  m
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String userId = AuthUtil.getUserId(req);
    Credential credential = AuthUtil.newAuthorizationCodeFlow().loadCredential(userId);
    String message = "";

    if (req.getParameter("operation").equals("insertSubscription")) {

        // subscribe (only works deployed to production)
        try {
            MirrorClient.insertSubscription(credential, WebUtil.buildUrl(req, "/notify"), userId,
                    req.getParameter("collection"));
            message = "Application is now subscribed to updates.";
        } catch (GoogleJsonResponseException e) {
            LOG.warning("Could not subscribe " + WebUtil.buildUrl(req, "/notify") + " because "
                    + e.getDetails().toPrettyString());
            message = "Failed to subscribe. Check your log for details";
        }

    } else if (req.getParameter("operation").equals("deleteSubscription")) {

        // subscribe (only works deployed to production)
        MirrorClient.deleteSubscription(credential, req.getParameter("subscriptionId"));

        message = "Application has been unsubscribed.";

    } else if (req.getParameter("operation").equals("insertItem")) {
        LOG.fine("Inserting Timeline Item");
        TimelineItem timelineItem = new TimelineItem();

        if (req.getParameter("message") != null) {
            timelineItem.setText(req.getParameter("message"));
        }

        // Triggers an audible tone when the timeline item is received
        timelineItem.setNotification(new NotificationConfig().setLevel("DEFAULT"));

        if (req.getParameter("imageUrl") != null) {
            // Attach an image, if we have one
            URL url = new URL(req.getParameter("imageUrl"));
            String contentType = req.getParameter("contentType");
            MirrorClient.insertTimelineItem(credential, timelineItem, contentType, url.openStream());
        } else {
            MirrorClient.insertTimelineItem(credential, timelineItem);
        }

        message = "A timeline item has been inserted.";

    } else if (req.getParameter("operation").equals("insertItemWithAction")) {
        LOG.fine("Inserting Timeline Item");
        TimelineItem timelineItem = new TimelineItem();
        timelineItem.setText("Tell me what you had for lunch :)");

        List<MenuItem> menuItemList = new ArrayList<MenuItem>();
        // Built in actions
        menuItemList.add(new MenuItem().setAction("REPLY"));
        menuItemList.add(new MenuItem().setAction("READ_ALOUD"));

        // And custom actions
        List<MenuValue> menuValues = new ArrayList<MenuValue>();
        menuValues.add(new MenuValue().setIconUrl(WebUtil.buildUrl(req, "/static/images/drill.png"))
                .setDisplayName("Drill In"));
        menuItemList.add(new MenuItem().setValues(menuValues).setId("drill").setAction("CUSTOM"));

        timelineItem.setMenuItems(menuItemList);
        timelineItem.setNotification(new NotificationConfig().setLevel("DEFAULT"));

        MirrorClient.insertTimelineItem(credential, timelineItem);

        message = "A timeline item with actions has been inserted.";

    } else if (req.getParameter("operation").equals("insertContact")) {
        if (req.getParameter("iconUrl") == null || req.getParameter("name") == null) {
            message = "Must specify iconUrl and name to insert contact";
        } else {
            // Insert a contact
            LOG.fine("Inserting contact Item");
            Contact contact = new Contact();
            contact.setId(req.getParameter("name"));
            contact.setDisplayName(req.getParameter("name"));
            contact.setImageUrls(Lists.newArrayList(req.getParameter("iconUrl")));
            MirrorClient.insertContact(credential, contact);

            message = "Inserted contact: " + req.getParameter("name");
        }

    } else if (req.getParameter("operation").equals("deleteContact")) {

        // Insert a contact
        LOG.fine("Deleting contact Item");
        MirrorClient.deleteContact(credential, req.getParameter("id"));

        message = "Contact has been deleted.";

    } else if (req.getParameter("operation").equals("insertItemAllUsers")) {
        if (req.getServerName().contains("glass-java-starter-demo.appspot.com")) {
            message = "This function is disabled on the demo instance.";
        }

        // Insert a contact
        List<String> users = AuthUtil.getAllUserIds();
        LOG.info("found " + users.size() + " users");
        if (users.size() > 10) {
            // We wouldn't want you to run out of quota on your first day!
            message = "Total user count is " + users.size() + ". Aborting broadcast " + "to save your quota.";
        } else {
            TimelineItem allUsersItem = new TimelineItem();
            allUsersItem.setText("Hello Everyone!");

            BatchRequest batch = MirrorClient.getMirror(null).batch();
            BatchCallback callback = new BatchCallback();

            // TODO: add a picture of a cat
            for (String user : users) {
                Credential userCredential = AuthUtil.getCredential(user);
                MirrorClient.getMirror(userCredential).timeline().insert(allUsersItem).queue(batch, callback);
            }

            batch.execute();
            message = "Successfully sent cards to " + callback.success + " users (" + callback.failure
                    + " failed).";
        }

    } else {
        String operation = req.getParameter("operation");
        LOG.warning("Unknown operation specified " + operation);
        message = "I don't know how to do that";
    }
    WebUtil.setFlash(req, message);
    res.sendRedirect(WebUtil.buildUrl(req, "/"));
}

From source file:com.google.cloud.dataflow.sdk.util.GcsUtil.java

License:Apache License

private static void executeBatches(List<BatchRequest> batches) throws IOException {
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(
            MoreExecutors.getExitingExecutorService(new ThreadPoolExecutor(MAX_CONCURRENT_BATCHES,
                    MAX_CONCURRENT_BATCHES, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())));

    List<ListenableFuture<Void>> futures = new LinkedList<>();
    for (final BatchRequest batch : batches) {
        futures.add(executor.submit(new Callable<Void>() {
            public Void call() throws IOException {
                batch.execute();
                return null;
            }//from w w  w .j av  a  2  s.c o m
        }));
    }

    try {
        Futures.allAsList(futures).get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException("Interrupted while executing batch GCS request", e);
    } catch (ExecutionException e) {
        throw new IOException("Error executing batch GCS request", e);
    } finally {
        executor.shutdown();
    }
}

From source file:com.google.gcloud.spi.DefaultStorageRpc.java

License:Open Source License

@Override
public BatchResponse batch(BatchRequest request) throws StorageException {
    com.google.api.client.googleapis.batch.BatchRequest batch = storage.batch();
    final Map<StorageObject, Tuple<Boolean, StorageException>> deletes = Maps.newConcurrentMap();
    final Map<StorageObject, Tuple<StorageObject, StorageException>> updates = Maps.newConcurrentMap();
    final Map<StorageObject, Tuple<StorageObject, StorageException>> gets = Maps.newConcurrentMap();
    try {//  ww w. j  a v a2 s .co m
        for (final Tuple<StorageObject, Map<Option, ?>> tuple : request.toDelete) {
            deleteRequest(tuple.x(), tuple.y()).queue(batch, new JsonBatchCallback<Void>() {
                @Override
                public void onSuccess(Void ignore, HttpHeaders responseHeaders) {
                    deletes.put(tuple.x(), Tuple.<Boolean, StorageException>of(Boolean.TRUE, null));
                }

                @Override
                public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
                    deletes.put(tuple.x(), Tuple.<Boolean, StorageException>of(null, translate(e)));
                }
            });
        }
        for (final Tuple<StorageObject, Map<Option, ?>> tuple : request.toUpdate) {
            patchRequest(tuple.x(), tuple.y()).queue(batch, new JsonBatchCallback<StorageObject>() {
                @Override
                public void onSuccess(StorageObject storageObject, HttpHeaders responseHeaders) {
                    updates.put(tuple.x(), Tuple.<StorageObject, StorageException>of(storageObject, null));
                }

                @Override
                public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
                    updates.put(tuple.x(), Tuple.<StorageObject, StorageException>of(null, translate(e)));
                }
            });
        }
        for (final Tuple<StorageObject, Map<Option, ?>> tuple : request.toGet) {
            getRequest(tuple.x(), tuple.y()).queue(batch, new JsonBatchCallback<StorageObject>() {
                @Override
                public void onSuccess(StorageObject storageObject, HttpHeaders responseHeaders) {
                    gets.put(tuple.x(), Tuple.<StorageObject, StorageException>of(storageObject, null));
                }

                @Override
                public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
                    gets.put(tuple.x(), Tuple.<StorageObject, StorageException>of(null, translate(e)));
                }
            });
        }
        batch.execute();
    } catch (IOException ex) {
        throw translate(ex);
    }
    return new BatchResponse(deletes, updates, gets);
}