com.google.api.client.http.FileContent Java Examples
The following examples show how to use
com.google.api.client.http.FileContent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IndexingServiceTest.java From connector-sdk with Apache License 2.0 | 6 votes |
@Test public void indexItemAndContent_largeFileContentIsUploaded() throws Exception { this.transport.addUploadItemsReqResp( SOURCE_ID, GOOD_ID, new UploadItemRef().setName(testName.getMethodName())); File largeFile = temporaryFolder.newFile(); Files.asCharSink(largeFile, UTF_8).write("Longer text that triggers an upload"); Item item = new Item().setName(GOOD_ID); FileContent content = new FileContent("text/html", largeFile); when(contentUploadService.uploadContent(testName.getMethodName(), content)) .thenReturn(Futures.immediateFuture(null)); this.indexingService.indexItemAndContent( item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS); assertEquals( new ItemContent() .setContentDataRef(new UploadItemRef().setName(testName.getMethodName())) .setContentFormat("TEXT"), item.getContent()); verify(quotaServer, times(2)).acquire(Operations.DEFAULT); }
Example #2
Source File: GoogleDriveUtil.java From algorithms-sedgewick-wayne with MIT License | 6 votes |
public static void updateWebPage(String webPageId, List<String> data) { try { Drive.Files driveFiles = driveService.files(); File currentFile = driveFiles.get(webPageId).execute(); String fileName = currentFile.getName(); // Create file in staging area String filePath = STAGING_AREA_DIRECTORY_PATH + fileName; FileUtil.writeFile(filePath, data); java.io.File fileInStagingArea = new java.io.File(STAGING_AREA_DIRECTORY_PATH + fileName); FileContent fileContent = new FileContent(TEXT_PLAIN_TYPE, fileInStagingArea); driveFiles.update(webPageId, new File(), fileContent).execute(); // Delete file from staging area FileUtil.deleteFile(filePath); } catch (IOException exception) { StdOut.println("There was an error when trying to update the web page with id " + webPageId + "."); } }
Example #3
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
private void insertFile(java.io.File localFile, String packageId) throws IOException { FileContent content = new FileContent(MIME_TYPE, localFile); File file = new File(); file.setTitle(localFile.getName()); file.setParents(Collections.singletonList(new ParentReference().setId(packageId))); driveApi .files() .insert(file, content) .execute(); }
Example #4
Source File: GoogleDriveUtils.java From components with Apache License 2.0 | 5 votes |
public File putResource(GoogleDrivePutParameters parameters) throws IOException { String folderId = parameters.getDestinationFolderId(); File putFile = new File(); putFile.setParents(Collections.singletonList(folderId)); Files.List fileRequest = drive.files().list() .setQ(format(QUERY_NOTTRASHED_NAME_NOTMIME_INPARENTS, parameters.getResourceName(), MIME_TYPE_FOLDER, folderId)); LOG.debug("[putResource] `{}` Exists in `{}` ? with `{}`.", parameters.getResourceName(), parameters.getDestinationFolderId(), fileRequest.getQ()); FileList existingFiles = fileRequest.execute(); if (existingFiles.getFiles().size() > 1) { throw new IOException(messages.getMessage("error.file.more.than.one", parameters.getResourceName())); } if (existingFiles.getFiles().size() == 1) { if (!parameters.isOverwriteIfExist()) { throw new IOException(messages.getMessage("error.file.already.exist", parameters.getResourceName())); } LOG.debug("[putResource] {} will be overwritten...", parameters.getResourceName()); drive.files().delete(existingFiles.getFiles().get(0).getId()).execute(); } putFile.setName(parameters.getResourceName()); String metadata = "id,parents,name"; if (!StringUtils.isEmpty(parameters.getFromLocalFilePath())) { // Reading content from local fileName FileContent fContent = new FileContent(null, new java.io.File(parameters.getFromLocalFilePath())); putFile = drive.files().create(putFile, fContent).setFields(metadata).execute(); // } else if (parameters.getFromBytes() != null) { AbstractInputStreamContent content = new ByteArrayContent(null, parameters.getFromBytes()); putFile = drive.files().create(putFile, content).setFields(metadata).execute(); } return putFile; }
Example #5
Source File: OnlinePredictionSample.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); Discovery discovery = new Discovery.Builder(httpTransport, jsonFactory, null).build(); RestDescription api = discovery.apis().getRest("ml", "v1").execute(); RestMethod method = api.getResources().get("projects").getMethods().get("predict"); JsonSchema param = new JsonSchema(); String projectId = "YOUR_PROJECT_ID"; // You should have already deployed a model and a version. // For reference, see https://cloud.google.com/ml-engine/docs/deploying-models. String modelId = "YOUR_MODEL_ID"; String versionId = "YOUR_VERSION_ID"; param.set( "name", String.format("projects/%s/models/%s/versions/%s", projectId, modelId, versionId)); GenericUrl url = new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true)); System.out.println(url); String contentType = "application/json"; File requestBodyFile = new File("input.txt"); HttpContent content = new FileContent(contentType, requestBodyFile); System.out.println(content.getLength()); List<String> scopes = new ArrayList<>(); scopes.add("https://www.googleapis.com/auth/cloud-platform"); GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(scopes); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential)); HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content); String response = request.execute().parseAsString(); System.out.println(response); }
Example #6
Source File: GoogleDriveUtil.java From algorithms-sedgewick-wayne with MIT License | 5 votes |
public static String createWebPage(String webPageName, List<String> data) { File fileMetadata = new File(); fileMetadata.setName(webPageName); // Create file in staging area String filePath = STAGING_AREA_DIRECTORY_PATH + webPageName; FileUtil.writeFile(filePath, data); java.io.File fileInStagingArea = new java.io.File(filePath); FileContent fileContent = new FileContent(TEXT_PLAIN_TYPE, fileInStagingArea); File file; try { file = driveService.files() .create(fileMetadata, fileContent) .setFields("id") .execute(); } catch (IOException exception) { StdOut.println("There was an error when trying to create the new web page."); return null; } // Delete file from staging area FileUtil.deleteFile(filePath); return file.getId(); }
Example #7
Source File: StorageResourceController.java From pubsub with Apache License 2.0 | 5 votes |
/** Uploads a given file to Google Storage. */ private void uploadFile(Path filePath) throws IOException { try { byte[] md5hash = Base64.decodeBase64( storage .objects() .get(bucketName(project), filePath.getFileName().toString()) .execute() .getMd5Hash()); try (InputStream inputStream = Files.newInputStream(filePath, StandardOpenOption.READ)) { if (Arrays.equals(md5hash, DigestUtils.md5(inputStream))) { log.info("File " + filePath.getFileName() + " is current, reusing."); return; } } log.info("File " + filePath.getFileName() + " is out of date, uploading new version."); storage.objects().delete(bucketName(project), filePath.getFileName().toString()).execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() != HttpStatus.SC_NOT_FOUND) { throw e; } } storage .objects() .insert( bucketName(project), null, new FileContent("application/octet-stream", filePath.toFile())) .setName(filePath.getFileName().toString()) .execute(); log.info("File " + filePath.getFileName() + " created."); }
Example #8
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
@Override public long updateExperimentProto( java.io.File localFile, DriveFile serverExperimentProtoMetadata, String packageId, String experimentTitle) throws IOException { FileContent content = new FileContent(MIME_TYPE, localFile); // We can't re-use the file metadata that we already have, for some opaque reason about fields // that are already defined in the metadata we have, and can't be defined for an update. File file = new File(); file.setTitle(serverExperimentProtoMetadata.getTitle()); file.setId(serverExperimentProtoMetadata.getId()); driveApi .files() .update(serverExperimentProtoMetadata.getId(), file, content) .execute(); File drivePackage = new File(); drivePackage.setId(packageId); drivePackage.setTitle(experimentTitle); driveApi .files() .patch(packageId, drivePackage) .execute(); return getExperimentProtoMetadata(packageId).getVersion(); }
Example #9
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
@Override public long insertExperimentProto( java.io.File localFile, String packageId, String experimentTitle) throws IOException { FileContent content = new FileContent(MIME_TYPE, localFile); File file = new File(); file.setTitle(EXPERIMENT_PROTO_FILE); file.setParents(Collections.singletonList(new ParentReference().setId(packageId))); driveApi .files() .insert(file, content) .execute(); File drivePackage = new File(); drivePackage.setId(packageId); drivePackage.setTitle(experimentTitle); driveApi .files() .patch(packageId, drivePackage) .execute(); FileVersion versionProto = FileVersion.newBuilder().setMinorVersion(MINOR_VERSION).setVersion(VERSION).build(); ByteArrayContent versionBytes = new ByteArrayContent(MIME_TYPE, versionProto.toByteArray()); File version = new File(); version.setParents(Collections.singletonList(new ParentReference().setId(packageId))); version.setTitle(VERSION_PROTO_FILE); driveApi.files().insert(version, versionBytes).execute(); return getExperimentProtoMetadata(packageId).getVersion(); }
Example #10
Source File: IndexingServiceTest.java From connector-sdk with Apache License 2.0 | 5 votes |
@Test public void indexItemAndContent_emptyFileContentIsInlined() throws Exception { File emptyFile = temporaryFolder.newFile(); Item item = new Item().setName(GOOD_ID); FileContent content = new FileContent("text/html", emptyFile); this.indexingService.indexItemAndContent( item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS); assertEquals( new ItemContent().encodeInlineContent(new byte[0]).setContentFormat("TEXT"), item.getContent()); verify(quotaServer).acquire(Operations.DEFAULT); }
Example #11
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
private void updateFile(File serverFile, java.io.File localFile) throws IOException { FileContent content = new FileContent(MIME_TYPE, localFile); File file = new File(); file.setTitle(serverFile.getTitle()); file.setId(serverFile.getId()); driveApi .files() .update(serverFile.getId(), file, content) .execute(); }
Example #12
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
@Override public void updateExperimentLibraryFile(java.io.File libraryFile, String fileId) throws IOException { File file = new File(); file.setId(fileId); FileContent content = new FileContent(MIME_TYPE, libraryFile); driveApi .files() .update(fileId, file, content) .execute(); }
Example #13
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
@Override public void insertExperimentLibraryFile(java.io.File libraryFile) throws IOException { File file = new File(); file.setTitle(EXPERIMENT_LIBRARY_PROTO); file.setParents(Collections.singletonList(new ParentReference().setId(APP_DATA_FOLDER))); FileContent content = new FileContent(MIME_TYPE, libraryFile); driveApi .files() .insert(file, content) .execute(); }
Example #14
Source File: GDriveCloudProvider.java From dbsync with Apache License 2.0 | 5 votes |
@Override public int uploadFile(File tempFile) { com.google.api.services.drive.model.File fileMetadata; String md5sumCurrent; try { Log.i(TAG, "start upload of DB file temp:" + tempFile.getName()); // Check collision fileMetadata = mDriveService.files() .get(mNewDriveID) .setFields("md5Checksum") .execute(); md5sumCurrent = fileMetadata.getMd5Checksum(); Log.i(TAG, "md5Checksum to check " + md5sumCurrent); if (!md5sumCurrent.equals(md5Sum)) { Log.w(TAG, "conflict detected"); return UPLOAD_CONFLICT; } mDriveService .files() .update(mNewDriveID, null, new FileContent("text/json", tempFile)) .execute(); Log.i(TAG, "file uploaded "); return UPLOAD_OK; } catch (Exception e) { Log.e(TAG, "uploadFile: " + e.getMessage()); throw new SyncException(SyncStatus.Code.ERROR_UPLOAD_CLOUD, "Error writing file to GDrive message:" + e.getMessage()); } }
Example #15
Source File: GoogleDriveWorkitemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@Before public void setUp() { try { InputStream testInputStream = IOUtils.toInputStream("test doc content", "UTF-8"); MediaHttpUploader mediaHttpUploader = PowerMockito.mock(MediaHttpUploader.class); MediaHttpDownloader mediaHttpDownloader = PowerMockito.mock(MediaHttpDownloader.class); Drive.Files.Insert gdriveFilesInsert = PowerMockito.mock(Drive.Files.Insert.class); Drive.Files.Get gdriveFilesGet = PowerMockito.mock(Drive.Files.Get.class); when(auth.getDriveService(anyString(), anyString())).thenReturn(gdriveService); when(gdriveService.files()).thenReturn(gdriveFiles); when(gdriveFiles.insert(any(File.class), any(FileContent.class))).thenReturn(gdriveFilesInsert); when(gdriveFiles.get(anyString())).thenReturn(gdriveFilesGet); when(gdriveFilesInsert.getMediaHttpUploader()).thenReturn(mediaHttpUploader); when(gdriveFilesInsert.execute()).thenReturn(new File()); when(gdriveFilesGet.getMediaHttpDownloader()).thenReturn(mediaHttpDownloader); when(gdriveFilesGet.executeMediaAsInputStream()).thenReturn(testInputStream); } catch (Exception e) { fail(e.getMessage()); } }
Example #16
Source File: GpgsClient.java From gdx-gamesvcs with Apache License 2.0 | 5 votes |
/** * Blocking version of {@link #saveGameState(String, byte[], long, ISaveGameStateResponseListener)} * * @param fileId * @param gameState * @param progressValue * @throws IOException */ public void saveGameStateSync(String fileId, byte[] gameState, long progressValue) throws IOException { java.io.File file = java.io.File.createTempFile("games", "dat"); new FileHandle(file).writeBytes(gameState, false); // no type since it is binary data FileContent mediaContent = new FileContent(null, file); // find file on server File remoteFile = findFileByNameSync(fileId); // file exists then update it if (remoteFile != null) { // just update content, leave metadata intact. GApiGateway.drive.files().update(remoteFile.getId(), null, mediaContent).execute(); Gdx.app.log(TAG, "File updated ID: " + remoteFile.getId()); } // file doesn't exists then create it else { File fileMetadata = new File(); fileMetadata.setName(fileId); // app folder is a reserved keyyword for current application private folder. fileMetadata.setParents(Collections.singletonList("appDataFolder")); remoteFile = GApiGateway.drive.files().create(fileMetadata, mediaContent) .setFields("id") .execute(); Gdx.app.log(TAG, "File created ID: " + remoteFile.getId()); } }
Example #17
Source File: MediaUploadWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 4 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { Document docToUpload = (Document) workItem.getParameter("DocToUpload"); String docMimeType = (String) workItem.getParameter("DocMimeType"); String uploadPath = (String) workItem.getParameter("UploadPath"); try { RequiredParameterValidator.validate(this.getClass(), workItem); Drive drive = auth.getDriveService(appName, clientSecret); File fileMetadata = new File(); fileMetadata.setTitle(docToUpload.getName()); fileMetadata.setAlternateLink(docToUpload.getLink()); if (docToUpload.getLastModified() != null) { fileMetadata.setModifiedDate(new DateTime(docToUpload.getLastModified())); } java.io.File tempDocFile = java.io.File.createTempFile(FilenameUtils.getBaseName(docToUpload.getName()), "." + FilenameUtils.getExtension(docToUpload.getName())); FileOutputStream fos = new FileOutputStream(tempDocFile); fos.write(docToUpload.getContent()); fos.close(); FileContent mediaContent = new FileContent(docMimeType, tempDocFile); Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent); MediaHttpUploader uploader = insert.getMediaHttpUploader(); uploader.setDirectUploadEnabled(true); uploader.setProgressListener(new MediaUploadProgressListener()); insert.execute(); workItemManager.completeWorkItem(workItem.getId(), null); } catch (Exception e) { handleException(e); } }
Example #18
Source File: App.java From java-play-store-uploader with MIT License | 4 votes |
/** * Perform apk upload an release on given track * * @throws Exception Upload error */ private void upload() throws Exception { // configure proxy if (this.proxyHost != null && !this.proxyHost.isEmpty()) { System.setProperty("https.proxyHost", this.proxyHost); } if (this.proxyPort != null && !this.proxyPort.isEmpty()) { System.setProperty("https.proxyPort", this.proxyPort); } // load key file credentials System.out.println("Loading account credentials..."); Path jsonKey = FileSystems.getDefault().getPath(this.jsonKeyPath).normalize(); GoogleCredential cred = GoogleCredential.fromStream(new FileInputStream(jsonKey.toFile())); cred = cred.createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER)); // load apk file info System.out.println("Loading apk file information..."); Path apkFile = FileSystems.getDefault().getPath(this.apkPath).normalize(); ApkFile apkInfo = new ApkFile(apkFile.toFile()); ApkMeta apkMeta = apkInfo.getApkMeta(); final String applicationName = this.appName == null ? apkMeta.getName() : this.appName; final String packageName = apkMeta.getPackageName(); System.out.println(String.format("App Name: %s", apkMeta.getName())); System.out.println(String.format("App Id: %s", apkMeta.getPackageName())); System.out.println(String.format("App Version Code: %d", apkMeta.getVersionCode())); System.out.println(String.format("App Version Name: %s", apkMeta.getVersionName())); apkInfo.close(); // load release notes System.out.println("Loading release notes..."); List<LocalizedText> releaseNotes = new ArrayList<LocalizedText>(); if (this.notesPath != null) { Path notesFile = FileSystems.getDefault().getPath(this.notesPath).normalize(); String notesContent = new String(Files.readAllBytes(notesFile)); releaseNotes.add(new LocalizedText().setLanguage(Locale.US.toString()).setText(notesContent)); } else if (this.notes != null) { releaseNotes.add(new LocalizedText().setLanguage(Locale.US.toString()).setText(this.notes)); } // init publisher System.out.println("Initialising publisher service..."); AndroidPublisher.Builder ab = new AndroidPublisher.Builder(cred.getTransport(), cred.getJsonFactory(), cred); AndroidPublisher publisher = ab.setApplicationName(applicationName).build(); // create an edit System.out.println("Initialising new edit..."); AppEdit edit = publisher.edits().insert(packageName, null).execute(); final String editId = edit.getId(); System.out.println(String.format("Edit created. Id: %s", editId)); try { // upload the apk System.out.println("Uploading apk file..."); AbstractInputStreamContent apkContent = new FileContent(MIME_TYPE_APK, apkFile.toFile()); Apk apk = publisher.edits().apks().upload(packageName, editId, apkContent).execute(); System.out.println(String.format("Apk uploaded. Version Code: %s", apk.getVersionCode())); // create a release on track System.out.println(String.format("On track:%s. Creating a release...", this.trackName)); TrackRelease release = new TrackRelease().setName("Automated upload").setStatus("completed") .setVersionCodes(Collections.singletonList((long) apk.getVersionCode())) .setReleaseNotes(releaseNotes); Track track = new Track().setReleases(Collections.singletonList(release)); track = publisher.edits().tracks().update(packageName, editId, this.trackName, track).execute(); System.out.println(String.format("Release created on track: %s", this.trackName)); // commit edit System.out.println("Commiting edit..."); edit = publisher.edits().commit(packageName, editId).execute(); System.out.println(String.format("Success. Commited Edit id: %s", editId)); // Success } catch (Exception e) { // error message String msg = "Operation Failed: " + e.getMessage(); // abort System.err.println("Opertaion failed due to an error!, Deleting edit..."); try { publisher.edits().delete(packageName, editId).execute(); } catch (Exception e2) { // log abort error as well msg += "\nFailed to delete edit: " + e2.getMessage(); } // forward error with message throw new IOException(msg, e); } }
Example #19
Source File: RestClient.java From apigee-deploy-maven-plugin with Apache License 2.0 | 4 votes |
/** * Import a bundle into the Apigee gateway. * * @param bundleFile reference to the local bundle file * @param bundle the bundle descriptor to use * * @return the revision of the uploaded bundle * * @throws IOException exception if something went wrong communicating with the rest endpoint */ public Long uploadBundle(String bundleFile, Bundle bundle) throws IOException { FileContent fContent = new FileContent("application/octet-stream", new File(bundleFile)); //testing log.debug("URL parameters API Version {}", (profile.getApi_version())); log.debug("URL parameters URL {}", (profile.getHostUrl())); log.debug("URL parameters Org {}", (profile.getOrg())); log.debug("URL parameters App {}", bundle.getName()); StringBuilder url = new StringBuilder(); url.append(format("%s/%s/organizations/%s/%s?action=import&name=%s", profile.getHostUrl(), profile.getApi_version(), profile.getOrg(), bundle.getType().getPathName(), bundle.getName())); if (getProfile().isValidate()) { url.append("&validate=true"); } HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent); restRequest.setReadTimeout(0); HttpHeaders headers = new HttpHeaders(); headers.setAccept("application/json"); restRequest.setHeaders(headers); Long result; try { HttpResponse response = executeAPI(profile, restRequest); AppConfig apiResult = response.parseAs(AppConfig.class); result = apiResult.getRevision(); if (log.isInfoEnabled()) log.info(PrintUtil.formatResponse(response, gson.toJson(apiResult))); applyDelay(); } catch (HttpResponseException e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage(), e); } return result; }
Example #20
Source File: RestClient.java From apigee-deploy-maven-plugin with Apache License 2.0 | 4 votes |
/** * Update a revsion of a bunlde with the supplied content. * * @param bundleFile reference to the local bundle file * @param bundle the bundle descriptor to use * * @return the revision of the uploaded bundle * * @throws IOException exception if something went wrong communicating with the rest endpoint */ public Long updateBundle(String bundleFile, Bundle bundle) throws IOException { FileContent fContent = new FileContent("application/octet-stream", new File(bundleFile)); //System.out.println("\n\n\nFile path: "+ new File(bundleFile).getCanonicalPath().toString()); log.debug("URL parameters API Version {}", profile.getApi_version()); log.debug("URL parameters URL {}", profile.getHostUrl()); log.debug("URL parameters Org {}", profile.getOrg()); log.debug("URL parameters App {}", bundle.getName()); StringBuilder url = new StringBuilder(); url.append(format("%s/%s/organizations/%s/%s/%s/revisions/%d", profile.getHostUrl(), profile.getApi_version(), profile.getOrg(), bundle.getType().getPathName(), bundle.getName(), bundle.getRevision())); if (getProfile().isValidate()) { url.append("?validate=true"); } HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent); restRequest.setReadTimeout(0); HttpHeaders headers = new HttpHeaders(); headers.setAccept("application/json"); restRequest.setHeaders(headers); Long result; try { HttpResponse response = executeAPI(profile, restRequest); AppConfig appconf = response.parseAs(AppConfig.class); result = appconf.getRevision(); if (log.isInfoEnabled()) log.info(PrintUtil.formatResponse(response, gson.toJson(appconf))); applyDelay(); } catch (HttpResponseException e) { log.error(e.getMessage()); throw new IOException(e.getMessage()); } return result; }