Creation Date PDF Google Drive - google-api

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

Related

How do I delete a spreadsheet that I have created from testing?

I have the most recent version of the Java Google Api client. I am successfully able to Authenticate and create a Spreadsheet.
How can I delete the spreadsheets that I have created after each JUNIT test.
I would like to be able to use the api to delete the Spreadsheet
There's not a lot here to tell if you'll need multiple scopes. If you plan on doing any spreadsheet actions using the same flow, then yes.
Drive actions use DriveScopes.DRIVE.
But if all you want to do is read the list of files you only need the Drive scope.
So:
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME).build();
// parse through the retrieved list of files to find a match with the name you gave the
// sheet. Since you can create multiple sheets with the same name, I parse the entire
// and delete all the files with that name.
FileList result = service
.files()
.list()
.setPageSize(100)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
for (File file : files) {
if (file.getName().trim().compareTo(getTitle().trim()) == 0) {
Delete d = fileService.files().delete(file.getId());
d.execute();
}
}

Google Drive Api Pdf export from Google Doc generate empty response

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 update Atlassian Confluence Wiki using JMeter and the REST API

I wanted a way to update a wiki status page and upload a file after a JMeter test was done running. This is something that you could conditionally kick off depending on the results of your Jenkins job.
I did this with these steps:
in a setup thread group, added a BeanShell Sampler to locate the most recent report file in my results folder.
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
log.info("GET MOST RECENT RESULTS REPORT FOR THE APP TESTED");
String dir_path = props.get("test_results_path");
File theNewestFile = null;
try {
File dir = new File(dir_path);
FileFilter fileFilter = new WildcardFileFilter("Results_${testApp}*.*");
File[] files = dir.listFiles(fileFilter);
if (files.length > 0) {
/** The newest file comes first **/
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
theNewestFile = files[0];
String fileName = files[0].getName().toString();
log.info("fileName: "+fileName);
print("fileName: "+fileName);
props.put("varResultsReportFile",fileName);
}
return theNewestFile;
}
catch (Throwable ex) {
log.error("Failed in Beanshell", ex);
throw ex;
}
login with a wiki/confluence system account
GET rest/api/content?title=${testApp}&spaceKey=${testSpaceKey}&expand=version,history
Use a JSON Extractors to extract page Version number(results..version.number) and page id(results..id)
Use a BeanShell PostProcessor to add 1 to the page version number and store that value in a variable. You will need this when you PUT your update into the wiki
GET rest/api/content?title=${testApp}&spaceKey=${testSpaceKey}&expand=body.storage
Use JSON Extractor to extact page body value(results..body.storage.value)
Using a CSS/JQuery Extractor on the JMeter Variable you created in step 7, Extract all the table values. For example,CSS/JQuery Expression=td and Match No= 1 to extract first column value.
PUT rest/api/content/${varPageId} and in the JSON body, update the single table value that you need to update and restore the values you extracted that you dont need updated.
POST rest/api/content/${varResultsPageId}/child/attachment For the Files upload tab, File Path=${__P(test_results_path)}${__P(varResultsReportFile)}, Parameter Name=file, MIME Type=text/csv
logout

Define download path dotnetbrowser

I use dotnetbrowser to display a web browser on a old windows framework.
have you an idea to define the download path ?
My dotnetbroser is enable, i can show my webpage but i don't found in documentation or exemple how define this simple download path.
The only exemple that i've found is about the download event detection.
I use WPF in C#
Thanks.
The DotNetBrowser.DownloadItem.DestinationFile property is writable and can be used to configure the path to store the file.
To set this property in your application, you need to subclass the DotNetBrowser.DefaultDownloadHandler and implement its AllowDownload(DownloadItem) method. Then you need to configure your download handler as shown in the documentation article: File Download
You can also configure and use DotNetBrowser.WPF.WPFDefaultDownloadHandler instance to show file chooser and select the path to store the file.
This is a solution
Défine your browser like variable :
BrowserView myBrowserView;
Browser myBrowser;
Create the browser properly :
this.myBrowser = BrowserFactory.Create();
this.myBrowserView = new WPFBrowserView(this.myBrowser);
Create event detection for download
this.myDowloadHandler = new SampleDownloadHandler();
this.myBrowser.DownloadHandler = myDowloadHandler;
Add it to a container, here, a grid
grid_navigateur.Children.Add((UIElement)myBrowserView.GetComponent());
Now we are going to use our "SampleDownloadHandler" class
class SampleDownloadHandler : DownloadHandler
{
public bool AllowDownload(DownloadItem download)
{
download.DestinationFile = "exemple\of\path\whith\file\name";
download.DownloadEvent += delegate(object sender, DownloadEventArgs e)
{
DownloadItem downloadItem = e.Item;
if (downloadItem.Completed)
{
System.Windows.MessageBox.Show("Download complete");
}
};
return true;
}
My personalisated class define path and name of the file who is download and pop a message when is over.
(to found the file name, you do to cut the string download.DestinationFile after the last )

NotifyFilter of FileSystemWatcher not working

I have a windows service (and verified the code by creating a similar WinForms application) where the NotifyFilter doesn't work. As soon as I remove that line of code, the service works fine and I can see the event-handler fire in the WinForms application.
All I'm doing is dropping a text file into the input directory for the FileSystemWatcher to kick off the watcher_FileChanged delegate. When I have the _watcher.NotifyFilter = NotifyFilters.CreationTime; in there, it doesn't work. When I pull it out, it works fine.
Can anyone tell me if I'm doing something wrong with this filter?
Here is the FSW code for the OnStart event.
protected override void OnStart(string[] args)
{
_watcher = new FileSystemWatcher(#"C:\Projects\Data\Test1");
_watcher.Created += new FileSystemEventHandler(watcher_FileChanged);
_watcher.NotifyFilter = NotifyFilters.CreationTime;
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
_watcher.Error += new ErrorEventHandler(OnError);
}
private void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
// Folder with new files - one or more files
string folder = #"C:\Projects\Data\Test1";
System.Console.WriteLine(#"C:\Projects\Data\Test1");
//Console.ReadKey(true);
// Folder to delete old files - one or more files
string output = #"C:\Temp\Test1\";
System.Console.WriteLine(#"C:\Temp\Test1\");
//Console.ReadKey(true);
// Create name to call new zip file by date
string outputFilename = Path.Combine(output, string.Format("Archive{0}.zip", DateTime.Now.ToString("MMddyyyy")));
System.Console.WriteLine(outputFilename);
//Console.ReadKey(true);
// Save new files into a zip file
using (ZipFile zip = new ZipFile())
{
// Add all files in directory
foreach (var file in Directory.GetFiles(folder))
{
zip.AddFile(file);
}
// Save to output filename
zip.Save(outputFilename);
}
DirectoryInfo source = new DirectoryInfo(output);
// Get info of each file into the output directory to see whether or not to delete
foreach (FileInfo fi in source.GetFiles())
{
if (fi.CreationTime < DateTime.Now.AddDays(-1))
fi.Delete();
}
}
I've been having trouble with this behavior too. If you step through the code (and if you look at MSDN documenation, you'll find that NotifyFilter starts off with a default value of:
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
So when you say .NotifyFilter = NotifyFilters.CreationTime, you're wiping out those other values, which explains the difference in behavior. I'm not sure why NotifyFilters.CreationTime is not catching the new file... seems like it should, shouldn't it!
You can probably just use the default value for NotifyFilter if it's working for you. If you want to add NotifyFilters.CreationTime, I'd recommend doing something like this to add the new value and not replace the existing ones:
_watcher.NotifyFilter = _watcher.NotifyFilter | NotifyFilters.CreationTime;
I know this is an old post but File Creation time is not always reliable. I came across a problem where a Log file was being moved to an archive folder and a new file of the same name was created in it's place however the file creation date did not change, in fact the meta data was retained from the previous file (the one that was moved to the archive) .
Windows has this cache on certain attributes of a file, file creation date is included. You can read the article on here: https://support.microsoft.com/en-us/kb/172190.

Resources