本文整理汇总了Java中com.google.api.client.http.FileContent类的典型用法代码示例。如果您正苦于以下问题:Java FileContent类的具体用法?Java FileContent怎么用?Java FileContent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
FileContent类属于com.google.api.client.http包,在下文中一共展示了FileContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: uploadFileToDrive
import com.google.api.client.http.FileContent; //导入依赖的package包/类
private void uploadFileToDrive(java.io.File file) {
try {
// File's metadata.
final File body = new File();
body.setTitle(file.getName());
InputStream is = new BufferedInputStream(new FileInputStream(file));
body.setMimeType(URLConnection.guessContentTypeFromStream(is));
//TODO: Upload to specific folder!
// File's content.
final FileContent mediaContent = new FileContent(URLConnection.guessContentTypeFromStream(is), file);
new Thread() {
public void run() {
try {
File uploadedFile = DriveFiles.getDriveFileInstance().getDrive_files().insert(body, mediaContent).execute();
closeActionHandlerDialog();
new RefreshAction().updateAction(context);
}
catch(Exception ie){
closeActionHandlerDialog();
}
}
}.start();
} catch (Exception e) {
closeActionHandlerDialog();
}
}
示例2: createFile
import com.google.api.client.http.FileContent; //导入依赖的package包/类
@Override
public File createFile(String sParentID, String sName, java.io.File sFile, String sMimeType, Map<String, String> sProperties) throws IOException {
File aResult = null;
if (drive != null) {
File fileMetadata = new File();
fileMetadata.setTitle(sName);
ParentReference aParentReference = new ParentReference();
aParentReference.setId(sParentID);
fileMetadata.setParents(Arrays.asList(aParentReference));
FileContent mediaContent = new FileContent(sMimeType, sFile);
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
aResult = insert.execute();
setProperties(aResult.getId(), sProperties);
}
return aResult;
}
示例3: insertFile
import com.google.api.client.http.FileContent; //导入依赖的package包/类
private String insertFile(java.io.File dir, String filename) throws IOException {
String result = "File not updated: " + filename;
// File's binary content
java.io.File localFile = new java.io.File(dir, filename);
FileContent fileContent = new FileContent(DetectorActivity.OUTPUT_MIME_TYPE, localFile);
// File's metadata.
File file = new File();
file.setTitle(localFile.getName());
file.setMimeType(DetectorActivity.OUTPUT_MIME_TYPE);
File insertedFile = service.files().insert(file, fileContent).execute();
if (insertedFile != null) {
result = "File created: " + insertedFile.getTitle();
}
return result;
}
示例4: updateFile
import com.google.api.client.http.FileContent; //导入依赖的package包/类
private String updateFile(java.io.File dir, String filename, File file) throws IOException {
String result = "File not updated: " + filename;
// File's new content.
java.io.File localFile = new java.io.File(dir, filename);
FileContent fileContent = new FileContent(DetectorActivity.OUTPUT_MIME_TYPE, localFile);
// Send the request to the API.
File updatedFile = service.files().update(file.getId(), file, fileContent).execute();
if (updatedFile != null) {
result = ("File updated: " + updatedFile.getTitle());
}
return result;
}
示例5: saveGameStateSync
import com.google.api.client.http.FileContent; //导入依赖的package包/类
/**
* 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());
}
}
示例6: simpleUpload
import com.google.api.client.http.FileContent; //导入依赖的package包/类
public void simpleUpload(java.io.File filePath,String name,String mime) throws IOException{
driveService = getDriveService();
File fileMetadata = new File();
fileMetadata.setName(name);
fileMetadata.setMimeType(mime);
FileContent mediaContent = new FileContent(mime, filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
}
示例7: convertToSpreedSheet
import com.google.api.client.http.FileContent; //导入依赖的package包/类
public static boolean convertToSpreedSheet(Drive drive,
String path) {
com.google.api.services.drive.model.File fileMetaData = new com.google.api.services.drive.model.File();
java.io.File file = new java.io.File(path);
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
fileMetaData.setName(file.getName());
String googleSheetMimeType = "application/vnd.google-apps.spreadsheet";
fileMetaData.setMimeType(googleSheetMimeType);
FileContent mediaContent = new FileContent(mimeTypesMap.getContentType(file), file);
com.google.api.services.drive.model.File f = null;
Drive.Files.Create create = null;
try {
System.out.println("Uploading file " + file.getName());
create = drive.files().create(fileMetaData, mediaContent)
.setFields("id, parents, mimeType, webViewLink");
create.getMediaHttpUploader().setProgressListener(new FileUpdateProgressListener());
// Using default chunk size of 10MB.
create.getMediaHttpUploader().setChunkSize(MediaHttpUploader.DEFAULT_CHUNK_SIZE);
f = create.execute();
} catch (IOException e) {
e.printStackTrace();
return false;
}
System.out.println("File ID: " + f.getId() + " Parent: " + f.getParents().toString()
+ " MimeType: " + f.getMimeType() + " link: " + f.getWebViewLink());
return true;
}
示例8: insertFile
import com.google.api.client.http.FileContent; //导入依赖的package包/类
/**
* Insert new file.
*
* @param title Title of the file to insert, including the extension.
* @param description Description of the file to insert.
* @param parentId Optional parent folder's ID.
* @param mimeType MIME type of the file to insert.
* @param file The file to insert.
* @return Inserted file metadata if successful, {@code null} otherwise.
*/
private File insertFile(String title, String description, String parentId, String mimeType, java.io.File file)
throws IOException {
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
if (parentId != null && parentId.length() > 0) {
body.setParents(Collections.singletonList(new ParentReference().setId(parentId)));
}
FileContent mediaContent = new FileContent(mimeType, file);
return drive.files().insert(body, mediaContent).execute();
}
示例9: uploadFile
import com.google.api.client.http.FileContent; //导入依赖的package包/类
/**
* Uploads a given file to Google Storage.
*/
private void uploadFile(Path filePath) throws IOException {
try {
byte[] md5hash =
Base64.decodeBase64(
storage
.objects()
.get(projectName + "-cloud-pubsub-loadtest", 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(projectName + "-cloud-pubsub-loadtest", filePath.getFileName().toString())
.execute();
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() != NOT_FOUND) {
throw e;
}
}
storage
.objects()
.insert(
projectName + "-cloud-pubsub-loadtest",
null,
new FileContent("application/octet-stream", filePath.toFile()))
.setName(filePath.getFileName().toString())
.execute();
log.info("File " + filePath.getFileName() + " created.");
}
示例10: uploadTestFile
import com.google.api.client.http.FileContent; //导入依赖的package包/类
protected File uploadTestFile() {
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
FileContent mediaContent = new FileContent(null, UPLOAD_FILE);
final Map<String, Object> headers = new HashMap<String, Object>();
// parameter type is com.google.api.services.drive.model.File
headers.put("CamelGoogleDrive.content", fileMetadata);
// parameter type is com.google.api.client.http.AbstractInputStreamContent
headers.put("CamelGoogleDrive.mediaContent", mediaContent);
File result = requestBodyAndHeaders("google-drive://drive-files/insert", null, headers);
return result;
}
示例11: testUpdate1
import com.google.api.client.http.FileContent; //导入依赖的package包/类
@Test
public void testUpdate1() throws Exception {
// First retrieve the file from the API.
File testFile = uploadTestFile();
String fileId = testFile.getId();
// using String message body for single parameter "fileId"
final File file = requestBody("direct://GET", fileId);
// File's new metadata.
file.setTitle("camel.png");
// File's new content.
java.io.File fileContent = new java.io.File(TEST_UPLOAD_IMG);
FileContent mediaContent = new FileContent(null, fileContent);
// Send the request to the API.
final Map<String, Object> headers = new HashMap<String, Object>();
// parameter type is String
headers.put("CamelGoogleDrive.fileId", fileId);
// parameter type is com.google.api.services.drive.model.File
headers.put("CamelGoogleDrive.content", file);
// parameter type is com.google.api.client.http.AbstractInputStreamContent
headers.put("CamelGoogleDrive.mediaContent", mediaContent);
File result = requestBodyAndHeaders("direct://UPDATE_1", null, headers);
assertNotNull("update result", result);
LOG.debug("update: " + result);
}
示例12: main
import com.google.api.client.http.FileContent; //导入依赖的package包/类
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());
GoogleCredential credential = GoogleCredential.getApplicationDefault();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content);
String response = request.execute().parseAsString();
System.out.println(response);
}
示例13: putResource
import com.google.api.client.http.FileContent; //导入依赖的package包/类
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;
}
示例14: doInBackground
import com.google.api.client.http.FileContent; //导入依赖的package包/类
@Override
protected Exception doInBackground(String... photos) {
try {
// Get output Directory
// Create the PDF and set some metadata
Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN);
Resources resources = mContext.getResources();
document.addTitle(mFilename);
document.addAuthor(resources.getString(R.string.app_name));
document.addSubject(resources.getString(R.string.file_subject));
// Open the file that we will write the pdf to.
java.io.File fileContent = new java.io.File(ImageUtils.getAlbumStorageDir(MainActivity.ALBUM_NAME) + mFilename);
OutputStream outputStream = new FileOutputStream(fileContent);
PdfWriter.getInstance(document, outputStream);
document.open();
// Get the document's size
Rectangle pageSize = document.getPageSize();
float pageWidth = pageSize.getWidth() - (document.leftMargin() + document.rightMargin());
float pageHeight = pageSize.getHeight();
//Loop through images and add them to the document
for (String path : photos) {
Image image = Image.getInstance(path);
image.scaleToFit(pageWidth, pageHeight);
document.add(image);
document.newPage();
}
// Cleanup
document.close();
outputStream.close();
// Upload time!
FileContent mediaContent = new FileContent("application/pdf", fileContent);
File body = new File();
if (mFolder != null)
body.setParents(Arrays.asList(new ParentReference().setId(mFolder.getId())));
body.setTitle(mFilename);
body.setDescription(resources.getString(R.string.file_subject));
body.setMimeType("application/pdf");
Drive.Files.Insert insert = mService.files().insert(body, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
uploader.setProgressListener(new FileProgressListener());
File file = insert.execute();
Log.d("C2P", "File Id: " + file.getId());
/* Database Code */
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
//file.getFileSize().toString()
String parentFolder = mFolder != null ? mFolder.getId() : "root";
Long size = file.getFileSize();
String fileSizeString = humanReadableByteCount(size);
Upload upload = new Upload(-1, mFilename, mFolderPath, fileSizeString, parentFolder, format.format(date), mService.about().get().execute().getUser().getEmailAddress());
UploadDataAdapter mUploadDataAdapter = new UploadDataAdapter(mContext);
mUploadDataAdapter.open();
mUploadDataAdapter.addUpload(upload);
mUploadDataAdapter.close();
} catch (Exception e) {
Log.d("C2P", "ERROR", e);
return e;
}
return null;
}
示例15: upload
import com.google.api.client.http.FileContent; //导入依赖的package包/类
@Override
public Handle<?> upload(LogFilePath localPath) throws Exception {
final String gsBucket = mConfig.getGsBucket();
final String gsKey = localPath.withPrefix(mConfig.getGsPath()).getLogFilePath();
final File localFile = new File(localPath.getLogFilePath());
final boolean directUpload = mConfig.getGsDirectUpload();
LOG.info("uploading file {} to gs://{}/{}", localFile, gsBucket, gsKey);
final StorageObject storageObject = new StorageObject().setName(gsKey);
final FileContent storageContent = new FileContent(Files.probeContentType(localFile.toPath()), localFile);
final Future<?> f = executor.submit(new Runnable() {
@Override
public void run() {
try {
Storage.Objects.Insert request = mClient.objects().insert(gsBucket, storageObject, storageContent);
if (directUpload) {
request.getMediaHttpUploader().setDirectUploadEnabled(true);
}
request.getMediaHttpUploader().setProgressListener(new MediaHttpUploaderProgressListener() {
@Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
LOG.debug("[{} %] upload file {} to gs://{}/{}",
(int) uploader.getProgress() * 100, localFile, gsBucket, gsKey);
}
});
request.execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return new FutureHandle(f);
}