How to check the file name in the filepath in plain javascript? - file-exists

var fileName = 'file:src/test/resources/config.json';
if(fileName.exists()){
karate.callSingle('file:src/test/java/org/features/preRequisites/HooksPreRequisite.feature');
}
else
{
karate.callonce('file:src/test/java/org/features/preRequisites/secretCredentials.feature');
karate.callSingle('file:src/test/java/org/features/preRequisites/HooksPreRequisite.feature');
}
Trying to check the config.json file in the above given path (file:src/test/resources/config.json).If condition is not working "if(fileName.exists())" . could you please guide us for proper solution

Related

How to download file from Sanity via HTTP?

I would like to know if there is possibility to download file from Sanity with HTTP request?
I only have reference ID:
{
file: {
asset: {
_ref: "file-fxxxxxxxxxxxxxxxxxxxx-xlsx"
_type: "reference"
}
}
}
I would like to do this is this scenario:
<a href="https://cdn.sanity.io/assets/clientID/dataset/file-xxxxxxxxxxx-xlsx">
Download File
</a>
You can, indeed 🎉 With a bit of custom code you can do it just from the _ref, which is the file document's _id
Creating the URL from the _ref/_id of the file
The _ref/_id structure is something like this: file-{ID}-{EXTENSION} (example: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3).
With this, you can generate the downloadable URL, which has the following structure: https://cdn.sanity.io/files/{PROJECT_ID}/{DATASET}/{ID_OF_FILE}.{EXTENSION}. Here's some pseudo Javascript code for the operation:
const getUrlFromId = ref => {
// Example ref: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3
// We don't need the first part, unless we're using the same function for files and images
const [_file, id, extension] = ref.split('-');
return `https://cdn.sanity.io/files/${PROJECT_ID}/${DATASET}/${id}.${extension}`
}
Querying the URL directly
However, if you can query for the file's document with GROQ that'd be easier:
*[(YOUR FILTER HERE)] {
file->{ url } // gets the URL from the referenced file
}
You can do the same with images, too.

App script conversion of DOC to PDF ruins formatting

I created a simple script to convert all DOC files in a directory to PDF files. The script assumes the folder in driver does not have any other files. It also recursively iterates over the sub-directories and convert DOC to PDF as expected. Here's the script:
function convertDocToPdf(root) {
if(!root) {
root = DriveApp.getFoldersByName('conversion-test');
}
if(root.hasNext()) {
var rootFolder = root.next();
var files = rootFolder.getFiles();
var folders = rootFolder.getFolders();
while(files.hasNext()) {
var file = files.next();
if(!file) continue ;
convert(file, rootFolder);
}
while(folders.hasNext()) {
convertDocToPdf(folders);
}
}
}
function convert(file, rootFolder) {
var blob = file.getBlob();
var tmp = Drive.Files.insert({}, blob, {convert:true});
var id = tmp["id"];
var doc = DocumentApp.openById(id);
var text = doc.getBody().getText();
var filename = file.getName();
var name = filename.split('.')[0];
rootFolder.createFile(name + '.pdf', text);
Drive.Files.remove(id);
}
I tested this with simple files that only contains one line of text and it works. However, when I tried to convert a DOC file with images and other formatting (columns, tables) it removes all formatting and after download, the the file looks empty.
Are there any ways of preserving the format? What am I missing in my code?
I believe your goal and your current situation as follows.
You want to convert Google Document files to the PDF files.
In your script, you can retrieve the Google Document files from the folder.
Modification points:
In the function of convert(file, rootFolder), when file of convert(file, rootFolder) is Google Document, blob of var blob = file.getBlob(); has already been the converted PDF format. But your script converts the PDF format to Google Document again and retrieve only the text data, and then, the text data is created as a PDF file. By this, the PDF file with only text data is created. I think that this is the reason of your issue.
In order to remove this issue and convert the Google Document to the PDF file, I would like to modify as follows.
Modified script:
In this modification, I modified convert.
function convert(file, rootFolder) {
if (file.getMimeType() != MimeType.GOOGLE_DOCS) return;
var blob = file.getBlob();
var filename = file.getName();
var name = filename.split('.')[0];
rootFolder.createFile(blob.setName(name + '.pdf'));
}
Note:
In this case, the Google Document is converted to the PDF format with file.getBlob(). But when you want to use the Drive API for this, you can also use the following script. Ref
From
var blob = file.getBlob();
To
var url = `https://www.googleapis.com/drive/v3/files/${file.getId()}/export?mimeType=${MimeType.PDF}`;
var blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob();
Reference:
getBlob()

Laravel 5 issues uploading/saving pdf

I'm using Laravel 5.6, jQuery 3.3.1, bootstrap 3.3.7, and PHP 7.1.4
I need to be able to allow users to upload files and pictures, basically jpg, gif, png, and pdf. I am using the public disk and storing the files in storage/app/public/folder_name where folder_name is defined in an env file
FILESYSTEM_DRIVER=public
PO_FILE_FOLDER=purchase_orders
INSURANCE_FILE_FOLDER=insurance
NOTE_FILE_FOLDER=notes
RENTAL_AGREEMENT_FILE_FOLDER=rental_agreements
SIGNATURES=signatures
They are then defined in config/app
'insurance_file_folder' => env('INSURANCE_FILE_FOLDER', ''),
'po_file_folder' => env('PO_FILE_FOLDER', ''),
'note_file_folder' => env('NOTE_FILE_FOLDER', ''),
'rental_agreement_file_folder' => env('RENTAL_AGREEMENT_FILE_FOLDER', ''),
'max_image_width' => env('MAX_IMAGE_WIDTH', 500),
'filesystem_driver' => env('FILESYSTEM_DRIVER', 'local'),
When I upload image files they upload to the appropriate folder but when I try to upload pdf files the system creates a new folder named as what I'm naming the file and the pdf is in the new folder with a random name. I'm using the exact same code to upload both images and pdf files so I can't figure out why it works for one but not the other.
Here is my controller code
public function store(PurchaseOrderRequest $poRequest, Customer $customer)
{
$purchaseOrder = $customer->purchaseOrders()->create($poRequest->except('attachment'));
if ($poRequest->hasFile('attachment')) {
$purchaseOrder->saveFile(config('app.po_file_folder', ''), $poRequest->file('attachment'));
}
return redirect()->action('CustomerController#edit', $customer)->with('alert', 'Purchase Order created.');
}
My model PurchaseOrder saveFile code
public function saveFile($folder_name, $file)
{
// if file submited then check if file already exists, if so delete file and create new file
$file_name = $this->createFileName();
File::removeFiles($folder_name.'/'.$file_name, FALSE);
$file_name = $file_name.'.'.$file->getClientOriginalExtension();
$file = File::resize($file);
$this->attachment_path = $folder_name.'/'.$file_name;
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
$this->save();
}
public function createFileName()
{
$file_name = 'po_'.$this->customer->code.'-'.$this->customer->id.'_'.$this->po_number.'-'.$this->id;
return $file_name;
}
My File helper code
public static function resize($file)
{
$resized_file = $file;
if (strtolower($resized_file->getClientOriginalExtension()) != 'pdf') {
// resize file if it is not pdf (file is photo)
// get image size then resize largest size to size limit - dont upsize if image is smaller than max size
list($width, $height) = getimagesize($resized_file);
if ($width > $height) {
$resized_file = Image::make($resized_file)->resize(config('app.max_image_width', ''), null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
} else {
$resized_file = Image::make($resized_file)->resize(null, config('app.max_image_width', ''),function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
}
}
return $resized_file;
}
public static function removeFiles($file_name, $ext_included = FALSE)
{
if ($ext_included == TRUE) {
// remove specific file
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name)) {
Storage::delete($file_name);
}
} else {
// remove file with any extension
$ext = array('.pdf', '.jpg', '.jpeg', '.gif', '.png');
for ($cnt = 0; $cnt <= 4; ++$cnt) {
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name.$ext[$cnt])) {
Storage::delete($file_name.$ext[$cnt]);
}
}
}
}
I realize the code may be a little confusing use the env variables but I'm trying to limit the pain in the event I need to change the folder name or move the files outside of the app. The application will have very few users maybe 3 or 4 and I don't anticipate a lot of files being uploaded which is why I'm storing the files in the application structure.
This is my first Laravel app and I put this code together using the docs and many a many different tutorials. It took a while but eventually I got it to work for images. So if you see things that don't look standard or good practice I welcome any pointers.
Thanks for taking the time to read this, any help is appreciated!
I had to use two different approaches to saving files in the system based on if the file was an image or pdf. I do some processing (resizing) on images before putting them into my storage folders with Intervention Image. This in turn returns a different object type than the raw uploaded file, because of this some of the commands to add the file (after processing) will not work.
So if I'm storing a pdf file I use:
$file->storeAs($folder_name, $file_name, config('app.filesystem_driver', ''));
If I'm storing an image that I have used Intervention Image on then I use:
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
I couldn't find one command that worked for both so I just check the extension before storing. Not sure if this is the "right way" but it got the job done.

writing content of local file to blob using javascript

I am trying to upload an excel file(named test1.xls) present in my computer in c drive at location->C:\test\test1.xls to google site(https://sites.google.com/xyz).To do so, I am using Google script editor and code shown below. The issue is that I am not able to pass the contents of file test1.txt at location C:\test\test1.txt instead of the text ("Here is some data")shown in code line shown below(var blob = Utilities.newBlob("Here is some data", "text/plain", "test1.xls");).Also what needs to be given instead of "text/plain" as it is excel file.Please let me know how to do that with code as I am new to google scripting/api coding,many thanks in advance.
CODE->
function doPost(e) {
var site = SitesApp.getSiteByUrl("https://sites.google.com/xyz"); Logger.log(site.getName());
var page = site.getChildren()[0];
// Create a new blob and attach it. Many useful functions also return
// blobs file uploads, URLFetch
var blob = Utilities.newBlob("Here is some data", "text/plain", "test1.xls");
try {
// Note that the filename must be unique or this call will fail
page.addHostedAttachment(blob);
}
catch(e){
Logger.log('Hosted attachment error msg:' +e.message);
}
}

Is possible to know the permission in a folder in google docs api

I just want to know if is possible to get the permission that a user has in a folder or shared folder,
am getting the folders with this url
"https://docs.google.com/feeds/default/private/full/-/folder"
but how can i get the permission of the folders whit the DocumentListEntry entry object ?
this is my code:
query = new DocumentQuery(new URL(
"https://docs.google.com/feeds/default/private/full/-/folder"));
feed = client.getFeed(query, DocumentListFeed.class);
// Create a new list of tags with the values of google docs
for (DocumentListEntry entry : feed.getEntries()) {
entry.getCanEdit() // this always return true even if i don't have permission in the folder
}
i hope some one han help me, thanks in advance.
In the DocsList API, you have the class Folder which has the following methods: getEditors(), getOwners(), getViewers(); each of them returns an array of users.
Now I don't think you can get the actual folder object by URL, but you could use the: getFolderById() method.
Here is a simple example:
First you need to find out what's the ID of the folder, there are at least three ways, but the simplest is to click on the actual folder in Google Docs and analyze it's URL:
https://docs.google.com/a/appsbroker.com/?tab=mo#folders/0B7_GXypCeAAdYmM1ZjJjYzktMWM1OS00ZDBiLTk5MDQtNjhiY2U4Zjc2YjZk
In the example above, the folder Id is:
0B7_GXypCeAAdYmM1ZjJjYzktMWM1OS00ZDBiLTk5MDQtNjhiY2U4Zjc2YjZk
After that you can write a simple script:
function myFunction() {
//replace ... with your folder id
var folder = DocsList.getFolderById("...");
var owner = folder.getOwner();
var editors = folder.getEditors();
var viewers = folder.getViewers();
//add code to go through the arrays and display them
}