I want to upload a file to a Google drive folder, if the file name is same i want to skip. With the code below i able upload file to Google Drive. But how to get the filename inside a folder?
File newFile = GoogleDriveHelper.uploadFile(service, dir, directoryId);
I'm referring to google REST document when I pass in all the param, it will return the Id in Google Drive.
Thx for Advice!
Check here pass the fileId to this function. The fileId can be get at here
public static void printFile(DriveService service,String fileId)
{
try
{
File file = service.Files.Get(fileId).Execute();
Console.WriteLine("Title: " + file.Title);
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
Related
I want to change the creation date on a Google Drive PDF file. So, how can I achieve this?
public static File SetLastModified(string fileID, DateTime lastModified)
{
File file = DriveService.Files.Get(fileID).Fetch();
file.ModifiedDate = lastModified.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'");
try
{
FilesResource.UpdateRequest request = DriveService.Files.Update(file, fileID);
request.SetModifiedDate = true;
file = request.Fetch();
}
catch (Exception e)
{
throw;
}
return file;
}
It is not possible to change the creation date of a file using Files:update() method
If you will check the request body for Files:update() , you can only modify the parameters listed in the table provided in the document. createdTime property is not included in the list.
The one being modified in your sample code is the modifiedTime property which is included in the list of editable properties.
If you want to have a file with a specified createdTime, you need to create a new file using Files:create(). createdTime can be modified as part of the request body
Additional Reference:
Drive API Quickstart - Setup Drive API for different platforms
Drive API - How to create Files
I'm using the export Google Drive API to retrieve a Google Doc as Pdf: https://developers.google.com/drive/v3/reference/files/export
I'm having the following problem: for documents bigger than a certain size (I don't know exactly the threshold, but it happens even with relatively small files around 1,5 MB) the API return a 200 response code with a blank result (normally it should contains the pdf data as byte stream), as you can see in the following screenshot:
I can successfully export the file via GoogleDrive/GoogleDoc UI with the "File -> Download as.. -> Pdf" command, despite it takes a bit of time.
Here is the file used for test (1.180 KB exported from Google Doc), I shared it so you can access to try export:
https://docs.google.com/document/d/18Cz7kHfEiDLeTWHyyoOi6U4kFQDMeg0D-CCJzILMMCk/edit?usp=sharing
Here is the (Java) code I'm using to perform the operation:
#Override
public GoogleDriveDocumentContent downloadFileContentAsPDF(String executionGoogleUser, String fileId) {
GoogleDriveDocumentContent documentContent = new GoogleDriveDocumentContent();
String conversionMimeType = "application/pdf";
try {
getLogger().info("GDrive APIs - Downloading file content in PDF format ...");
InputStream gDriveFileData = getDriveService(executionGoogleUser).files()
.export(fileId, conversionMimeType)
.executeMediaAsInputStream();
getLogger().info("GDrive APIs - File content as PDF format downloaded.");
documentContent.setFileName(null);
documentContent.setMimeType(conversionMimeType);
documentContent.setData(gDriveFileData);
} catch (IOException e) {
throw new RuntimeException(e);
}
return documentContent;
}
Does anyone has the same issue and know how to solve it?
The goal is to generate a pdf from a Google Doc.
Thanks
I think you should try using media downloadeder you will have to alter it for Google drive rather than storage service.
{
// Create the service using the client credentials.
var storageService = new StorageService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "APP_NAME_HERE"
});
// Get the client request object for the bucket and desired object.
var getRequest = storageService.Objects.Get("BUCKET_HERE", "OBJECT_HERE");
using (var fileStream = new System.IO.FileStream(
"FILE_PATH_HERE",
System.IO.FileMode.Create,
System.IO.FileAccess.Write))
{
// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
getRequest.MediaDownloader.ProgressChanged += Download_ProgressChanged;
getRequest.Download(fileStream);
}
}
static void Download_ProgressChanged(IDownloadProgress progress)
{
Console.WriteLine(progress.Status + " " + progress.BytesDownloaded);
}
Code ripped from here
How to find URL of google spreadsheet using spreadsheet ID using google java client? I don't want to build a string. I want to make call to google REST API and find out.
Files: list with search parm using the mime type for a sheet
mimeType = 'application/vnd.google-apps.spreadsheet'
Code from the documentation.
/**
* Retrieve a list of File resources.
*
* #param service Drive API service instance.
* #return List of File resources.
*/
private static List<File> retrieveAllFiles(Drive service) throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}
response contains:
Remember unless the user has access to the files the link wont work for them
"selfLink": "https://www.googleapis.com/drive/v2/files/1-0ReBjBqKh_Q9r1BDsC_BB9JgkeLoFPkDIXFcXiqQZ",
"alternateLink": "https://docs.google.com/spreadsheets/d/1-0ReBjBqKh_Q9r1BDsC_BB9JgkeLoFPkDIXFcXiqQZ/edit?usp=drivesdk",
"embedLink": "https://docs.google.com/spreadsheets/d/1-0ReBjBqKh_Q9r1BDsC_BB9JgkeLoFPkDIXFcXiqQZ/htmlembed",
I have been working on the following project, some background:
I am an intern currently developing a new search system for my organization. The current setup is microsoft sharepoint 2013 in which the users upload files etc.. and on the other hand is the system I am developing which indexes all data being uploaded to apache SOLR.
I have been succesfull in mapping the sharepoint content repository to a network drive, and I can manually start my program to start indexing the conent of this network drive to SOLR using the Solrj api.
The problem I am facing however is that I am unable to poll events from this network drive. In my test build which ran local I used a watcher service to launch code (reindex documents, delete indexes) on file create, file modify and file delete.
This does not work unfortunantly with a url pointing to a network drive :(.
So the big question: Is there any API / library available for polling events from network drives?
Any help would be extemely appreciated !
So I fnally figured this one out, tried looking at .net's variant of the watcher service (system.io.filesystemwatcher) and i was having the same problem. I finally got it working by using java.io.FileAlterationMonitor / observer.
Code:
public class UNCWatcher {
// A hardcoded path to a folder you are monitoring .
public static final String FOLDER =
"A:\\Department";
public static void main(String[] args) throws Exception {
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 5 * 1000;
File folder = new File(FOLDER);
if (!folder.exists()) {
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor =
new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
#Override
public void onFileCreate(File file) {
try {
// "file" is the reference to the newly created file
System.out.println("File created: "
+ file.getCanonicalPath());
if(file.getName().endsWith(".docx")){
System.out.println("Uploaded resource is of type docx, preparing solr for indexing.");
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
// Is triggered when a file is deleted from the monitored folder
#Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("File removed: "
+ file.getCanonicalPath());
// "file" does not exists anymore in the location
System.out.println("File still exists in location: "
+ file.exists());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
System.out.println("Starting monitor service");
monitor.start();
}
}
I want to design a web project, when users upload file to hadoop hdfs,users can see their upload status via web. Is there any simple java api?
Can anyone help?
Right now I only know the way,how to use api to upload file to hdfs.
public synchronized static void upload(FileSystem fs, String local,
String remote) {
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
Path dst = new Path(workDir + "/" + remote);
Path src = new Path(local);
try {
fs.copyFromLocalFile(false, true, src, dst);
log.info("upload " + local + " to " + remote + " successed. ");
} catch (Exception e) {
log.error("upload " + local + " to " + remote + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
You might find FileStatus class useful. Through this class you can get almost all the necessary information which your user might wanna know, like getting the access time of the file, modification time of the file, length of the file etc etc.
And, since you are talking about a web app, I would recommend you to have a look at the WebHDFS REST API. It allows you to submit a GET HTTP request which will send a FileStatus JSON object in response. You could then easily use this JSON object to present the status to your user through a web page.
HTH