Search in sources :

Example 61 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project beam by apache.

the class BigQueryServicesImplTest method testGetErrorInfo.

@Test
public void testGetErrorInfo() throws IOException {
    ErrorInfo info = new ErrorInfo();
    List<ErrorInfo> infoList = new ArrayList<>();
    infoList.add(info);
    info.setReason("QuotaExceeded");
    GoogleJsonError error = new GoogleJsonError();
    error.setErrors(infoList);
    HttpResponseException.Builder builder = mock(HttpResponseException.Builder.class);
    IOException validException = new GoogleJsonResponseException(builder, error);
    IOException invalidException = new IOException();
    assertEquals(info.getReason(), DatasetServiceImpl.getErrorInfo(validException).getReason());
    assertNull(DatasetServiceImpl.getErrorInfo(invalidException));
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) ErrorInfo(com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo) ArrayList(java.util.ArrayList) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError) HttpResponseException(com.google.api.client.http.HttpResponseException) IOException(java.io.IOException) Test(org.junit.Test)

Example 62 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project HearthStats.net-Uploader by HearthStats.

the class UploadVideo method main.

/**
 * Upload the user-selected video to the user's YouTube channel. The code
 * looks for the video in the application's project folder and uses OAuth
 * 2.0 to authorize the API request.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadvideo-sample").build();
        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();
        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);
        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();
        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);
        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, UploadVideo.class.getResourceAsStream("/sample-video.mp4"));
        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();
        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) Credential(com.google.api.client.auth.oauth2.Credential) MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) VideoStatus(com.google.api.services.youtube.model.VideoStatus) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) MediaHttpUploaderProgressListener(com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) InputStreamContent(com.google.api.client.http.InputStreamContent)

Example 63 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project collect by opendatakit.

the class InstanceGoogleSheetsUploader method uploadOneSubmission.

@Override
public String uploadOneSubmission(Instance instance, String spreadsheetUrl) throws UploadException {
    File instanceFile = new File(instance.getInstanceFilePath());
    if (!instanceFile.exists()) {
        throw new UploadException(FAIL + "instance XML file does not exist!");
    }
    // Get corresponding blank form and verify there is exactly 1
    List<Form> forms = new FormsRepositoryProvider(Collect.getInstance()).get().getAllByFormIdAndVersion(instance.getFormId(), instance.getFormVersion());
    try {
        if (forms.size() != 1) {
            throw new UploadException(getLocalizedString(Collect.getInstance(), R.string.not_exactly_one_blank_form_for_this_form_id));
        }
        Form form = forms.get(0);
        if (form.getBASE64RSAPublicKey() != null) {
            submissionComplete(instance, false);
            throw new UploadException(getLocalizedString(Collect.getInstance(), R.string.google_sheets_encrypted_message));
        }
        String formFilePath = PathUtils.getAbsoluteFilePath(new StoragePathProvider().getOdkDirPath(StorageSubdirectory.FORMS), form.getFormFilePath());
        TreeElement instanceElement = getInstanceElement(formFilePath, instanceFile);
        setUpSpreadsheet(spreadsheetUrl);
        sheetsHelper.updateSpreadsheetLocaleForNewSpreadsheet(spreadsheet.getSpreadsheetId(), spreadsheet.getSheets().get(0).getProperties().getTitle());
        if (hasRepeatableGroups(instanceElement)) {
            createSheetsIfNeeded(instanceElement);
        }
        String key = getInstanceID(getChildElements(instanceElement, false));
        if (key == null) {
            key = PropertyUtils.genUUID();
        }
        insertRows(instance, instanceElement, null, key, instanceFile, spreadsheet.getSheets().get(0).getProperties().getTitle());
    } catch (UploadException e) {
        submissionComplete(instance, false);
        throw e;
    } catch (GoogleJsonResponseException e) {
        submissionComplete(instance, false);
        throw new UploadException(getErrorMessageFromGoogleJsonResponseException(e));
    }
    submissionComplete(instance, true);
    // Google Sheets can't provide a custom success message
    return null;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) StoragePathProvider(org.odk.collect.android.storage.StoragePathProvider) Form(org.odk.collect.forms.Form) UploadException(org.odk.collect.android.upload.UploadException) FormsRepositoryProvider(org.odk.collect.android.utilities.FormsRepositoryProvider) LocalizedApplicationKt.getLocalizedString(org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString) File(java.io.File) TreeElement(org.javarosa.core.model.instance.TreeElement) AbstractTreeElement(org.javarosa.core.model.instance.AbstractTreeElement)

Example 64 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project collect by opendatakit.

the class InstanceGoogleSheetsUploader method insertRow.

private void insertRow(Instance instance, TreeElement element, String parentKey, String key, File instanceFile, String sheetTitle) throws UploadException {
    try {
        List<List<Object>> sheetCells = getSheetCells(sheetTitle);
        boolean newSheet = sheetCells == null || sheetCells.isEmpty();
        List<Object> columnTitles = getColumnTitles(element, newSheet);
        ensureNumberOfColumnsIsValid(columnTitles.size());
        if (!newSheet) {
            // we are editing an existed sheet
            if (isAnyColumnHeaderEmpty(sheetCells.get(0))) {
                // Insert a header row again to fill empty headers
                sheetsHelper.updateRow(spreadsheet.getSpreadsheetId(), sheetTitle + "!A1", new ValueRange().setValues(Collections.singletonList(columnTitles)));
                // read sheet cells again to update
                sheetCells = getSheetCells(sheetTitle);
            }
            disallowMissingColumns(sheetCells.get(0), columnTitles);
            addAltitudeAndAccuracyTitles(sheetCells.get(0), columnTitles);
            // Call again to ensure valid number of columns
            ensureNumberOfColumnsIsValid(columnTitles.size());
        } else {
            // new sheet
            Integer sheetId = getSheetId(sheetTitle);
            if (sheetId != null) {
                sheetsHelper.resizeSpreadSheet(spreadsheet.getSpreadsheetId(), sheetId, columnTitles.size());
            }
            sheetsHelper.insertRow(spreadsheet.getSpreadsheetId(), sheetTitle, new ValueRange().setValues(Collections.singletonList(columnTitles)));
            // read sheet cells again to update
            sheetCells = getSheetCells(sheetTitle);
        }
        HashMap<String, String> answers = getAnswers(instance, element, columnTitles, instanceFile, parentKey, key);
        if (shouldRowBeInserted(answers)) {
            sheetsHelper.insertRow(spreadsheet.getSpreadsheetId(), sheetTitle, new ValueRange().setValues(Collections.singletonList(prepareListOfValues(sheetCells.get(0), columnTitles, answers))));
        }
    } catch (GoogleJsonResponseException e) {
        throw new UploadException(getErrorMessageFromGoogleJsonResponseException(e));
    } catch (IOException e) {
        throw new UploadException(e);
    }
}
Also used : ValueRange(com.google.api.services.sheets.v4.model.ValueRange) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) UploadException(org.odk.collect.android.upload.UploadException) ArrayList(java.util.ArrayList) List(java.util.List) LocalizedApplicationKt.getLocalizedString(org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString) IOException(java.io.IOException)

Example 65 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project collect by opendatakit.

the class InstanceGoogleSheetsUploader method setUpSpreadsheet.

private void setUpSpreadsheet(String urlString) throws UploadException, GoogleJsonResponseException {
    if (spreadsheet == null || spreadsheet.getSpreadsheetUrl() == null || !urlString.equals(spreadsheet.getSpreadsheetUrl())) {
        try {
            spreadsheet = sheetsHelper.getSpreadsheet(UrlUtils.getSpreadsheetID(urlString));
            spreadsheet.setSpreadsheetUrl(urlString);
        } catch (GoogleJsonResponseException e) {
            Timber.i(e);
            throw e;
        } catch (IOException | BadUrlException e) {
            Timber.i(e);
            throw new UploadException(e);
        }
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) UploadException(org.odk.collect.android.upload.UploadException) IOException(java.io.IOException) BadUrlException(org.odk.collect.android.exception.BadUrlException)

Aggregations

GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)94 IOException (java.io.IOException)48 YouTube (com.google.api.services.youtube.YouTube)26 Credential (com.google.api.client.auth.oauth2.Credential)25 ArrayList (java.util.ArrayList)13 Operation (com.google.api.services.compute.model.Operation)12 Test (org.junit.Test)12 Compute (com.google.api.services.compute.Compute)11 Storage (com.google.api.services.storage.Storage)10 GcpResourceException (com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)8 GcsOptions (org.apache.beam.sdk.extensions.gcp.options.GcsOptions)7 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)5 InputStreamContent (com.google.api.client.http.InputStreamContent)5 BackOff (com.google.api.client.util.BackOff)5 HashMap (java.util.HashMap)5 Objects (com.google.api.services.storage.model.Objects)4 GoogleCloudStorage (com.google.cloud.hadoop.gcsio.GoogleCloudStorage)4 HalException (com.netflix.spinnaker.halyard.core.error.v1.HalException)4 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3