how can I check for an existing web folder - webclient

I work as software tester entry level and I was given a task to save my log files to the specific folder on my company website and this website only can be accessed internally by the company employees. So far I know how to save file onto the site, but how would I check which specific folder is already there before I save the file to it?
private void SaveLogsTogWeb(string file)
{
try
{
//create WebClient object
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
client.UploadFile(#"http://myCompnay/MyProjects/TestLogs/" + file, "PUT", file);
client.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Thanks in advance for the helps

Use this code:
if(!Directory.Exists({path}))
{
//create the directory
}
It checks to see if the directory doesn't exist. And if it doesn't then you can create it!

One way would be to put a dummy file in that folder (dummy.txt) and do an HTTP GET of the file. If you can successfully do that, you can then assume the folder exists (barring any virtual folders, etc.)

Related

How to Return File from SvelteKit Endpoint

I am trying to serve a PDF file that my SvelteKit app generates and allow a user to download it from an endpoint.
My project structure looks like this:
---------------------
/src/routes/downloads
---------------------
[file].ts
ABC.pdf
XYZ.pdf
My [file].ts endpoint looks like this:
import fs from 'fs'
// ----- GET -----
export async function get({ params }){
//console.log(params.file) -> ABC
var pdf = fs.readFileSync('./src/routes/downloads/'+params.file+'.pdf')
return{
status:200,
headers: {
"Content-type" : "application/pdf",
"Content-Disposition": "attachment; filename="+params.file+".pdf"
},
body: pdf
}
}
So then when I hit http://localhost:3000/downloads/ABC, the PDF file named ABC.pdf downloads.
But my readFileSync path isn't something that's going to work on production. As far as I know, there is no /src/routes folder.
How do I serve my file from a http://localhost:3000 url? Everything I've tried yields a 404 and it can't find the file. I'm also open to a different way of handling this scenario. This is just my best guess of how to do this in SvelteKit.
The recommended way to do this, for adapter-node, is to place your application data in a new folder under your project's root directory (ie. alongside /src and /static). You can then read files with a relative path: fs.readFile('./my-app-data/foo.txt').
For deployment, you just have to make sure to execute node build from the project root, as this guarantees that you have the same working directory during both development and production.
The static folder works, but it is not meant to carry application data—files in this folder represent new routes that are served directly to users, so this is not desirable if your generated files must be protected in any way. Even if they're meant to be public files, it still blurs what is supposed to be production and source data: should a new deploy overwrite all the files in static? If you're not careful, a naming clash could mean overwriting production data.
You can use import.meta.glob for this.
export async function get({ params }){
const file = `./${params.file}.pdf`;
const pdfs = import.meta.glob(('./*.pdf', { as: 'raw' });
const pdf = pdfs[file];
return {
status:200,
headers: {
"Content-type" : "application/pdf",
"Content-Disposition": "attachment; filename="+params.file+".pdf"
},
body: pdf
}
}
The import.meta.glob in combination with the as: 'raw' option will effectively embed the contents of each file in your resulting code. (this is purely server side so no worries about shipping to much to the client)
Note that this of course means that only files present during build can be served this way.
As #Stephane suggest, put your files under statics folder. This way you can serve directly through a reverse proxy, like Nginx

Vaadin Flow: How to consume dragged file

I have a section (DropTarget) where the user can drop several items from within my application.
This works fine.
Now I would also like to allow the user to drag files to that DropTarget.
The drop listener that I registered gets notified when I drag a file to the DropTarget, but - as far as I see - does not offer any possibility to consume the dragged file.
Anybody knows how to get this running?
Using Vaadin flow 22.0.7
When you create an Upload component, you can specify a Receiver. You can pass one as a constructor parameter or via upload.setReceiver(Receiver). There are different types of Receivers depending on your use case; you can use a MemoryBuffer if you are ok with putting all of the data in your server memory, but there are other options, like FileBuffer, as can be seen here: https://vaadin.com/docs/latest/ds/components/upload/#handling-uploaded-files-java-only ; you can implement your own Receiver as well.
The Receiver gives you access to the actual streaming content of the file. Typically, you want to access the data in some stage of the upload process, which you can do through different upload listeners. If you just want to deal with it once the upload is fully complete, you can use a SucceededListener:
MemoryBuffer memoryBuffer = new MemoryBuffer();
Upload upload = new Upload(memoryBuffer);
upload.addSucceededListener(event -> {
InputStream fileData = memoryBuffer.getInputStream();
String fileName = event.getFileName();
File targetFile = new File("C:/tmp/" + fileName );
OutputStream outStream = null;
try {
outStream = new FileOutputStream(targetFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
outStream.write(fileData.readAllBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
Implementing your own Receiver gives you more flexibility on how you want to handle the OutputStream from the upload, and of course you might not want to save the upload as a physical file, but put it directly in a database for example.

CQ5 workflow content inbox | Approve folder content wrong url

We have created a workflow to send approval mail to approver. The payload is jcr:content of a folder or a PDF.
After the coding, the behaviour is for:
A pdf : It generate right URL as http:///damadmin.html#/content/ab/cd/abc.pdf
A folder : It generate the wrong url as http:///damadmin.html#/content/folder-name/jcr:content
So, for folder, we have updated the code to change the payload as the folder-path instead of folder-path/jcr:content
for that we used,
WorkflowData wfData = wfSession.newWorkflowData("JCR_PATH", folder_node_path);
wfSession.updateWorkflowData(workItem.getWorkflow(), wfData);
After the code change, When a user modify any dam content like a pdf, the url is correct as http:///damadmin.html#/
but when the user modify a folder properties, the mail sent to approver has the wrong url as http:///
means /damadmin.html# is missing.
We need that the correct link should be added for both PDF and Folder.
Thanks in advance.
Issue is resolved.I am using CQ 5.5.
Sharing my experience.We don't need to change the payload. The payload can remain as jcr:content
We need to do two things:
Make sure the folder-path/jcr:content has the value in property jcr:title. It will be shown in content column of the inbox page.
For the folder link in inbox page, it must be as /content//jcr:content. The problem is because /damadmin.html# is not added before the url.
This problem is not coming for any Asset or Page.
Solution is:
You need add the following code in /libs/cq/workflow/components/inbox/list/json.jsp
A=>
Add private method
private String handleDamPathForFolder(Logger log, String payloadUrl, Session session, WorkItem wi)
{
try
{
if(isFolderNode(session, wi))
{
return ("/damadmin.html#"+payloadUrl);
}
}catch (Exception e)
{
log.error("Unable to handle path creation for work item: " + wi.getId(), e);
}
return payloadUrl;
}
We have to write the method isFolderNode which will return true if the node is a folder.
B=>Replace
JSONWriterUtil.write(writer, "payload", pathBuilder.getPath(wi),JSONWriterUtil.WriteMode.BOTH, xss);
by the follwoing
JSONWriterUtil.write(writer,"payload",handleDamPathForFolder(log,pathBuilder.getPath(wi), session, wi), JSONWriterUtil.WriteMode.BOTH, xss);
<br/>

Multiple s3 buckets in Filepicker.io

I need to upload to multiple s3 buckets with filepicker.io. I found a tweet that indicated that there was a hacky, but possible, way to do this. Support hasn't gotten back to me yet, so I'm hoping that someone here already knows the answer!
Have you tried generating a second application/API key? It looks like they lock your S3/AWS credentials to an application/API key rather than directly to the account.
Support just got back to me. There's no way to do this besides creating multiple applications, which is okay if you are just switching between prod/staging/dev, but not a good solution if you have to upload to arbitrary buckets.
My solution is to execute a PUT request with the x-amz-copy-source header after the file has been uploaded, which copies it to the correct bucket.
This is pretty hacky as it request two extra requests per file -- one filepicker.stat and one more call to s3 (or your server).
#Ben
I am developing code with same issue of files needing to go into many buckets. I'm working in ASP.net.
What I have done is have one Filepicker 'application' with it's own S3 bucket.
I already had a callback to the server in the javascript onSuccess() function (which is passed as a parameter to filepicker.store()). This callback needed to be there to do some book-keeping anyway.
So I have just added in an extra bit to the server-side callback code which uses the AWS SDK to copy the object from the bucket filepicker uploades it to, to it's final destination bucket.
This is my C# code for moving, or rather copying, an object between buckets:
public bool MoveObject(string bucket1, string key1, string bucket2, string key2 = null)
{
bool success = false;
if (key2 == null) key2 = key1;
Logger logger = new Logger(); // my logging system
try
{
RegionEndpoint region = RegionEndpoint.EUWest1; // use your region here
using (AmazonS3Client s3Client = new AmazonS3Client(region))
{
// TODO: CheckForBucketFunction
CopyObjectRequest request = new CopyObjectRequest();
request.SourceBucket = bucket1;
request.SourceKey = key1;
request.DestinationBucket = bucket2;
request.DestinationKey = key2;
S3Response response = s3Client.CopyObject(request);
logger.Info2Log("response xml = \n{0}\n", response.ResponseXml);
response.Dispose();
success = true;
}
}
catch (AmazonS3Exception ex)
{
logger.Info2Log("Error copying file between buckets: {0} - {1}",
ex.ErrorCode, ex.Message);
success = false;
}
return success;
}
There are AWS SDKs for other server languages and the good news is Amazon doesn't charge for copying objects between buckets in the same region.
Now I just have to decide how to delete the object from the filepicker application bucket. I could do it on the server using more AWS SDK code but that will be messy as it leaves links to the object in the filepicker console. Or I could do it from the browser using filepicker code.

How to mkdirs on gwt when fileupload on client

i mode development in eclipse. the fileupload works just fine. but i will make directory to /var/wms/year/month/file.jpg on linux. this my source code from client:
add component to form
fileUpload = new SingleUploader(FileInputType.LABEL);
fileUpload.setFileInputPrefix("PJ");
fileUpload.addOnFinishUploadHandler(onFinishUploaderHandler);
layoutContainerItemRight.add(fileUpload, formData);
method is addOnFinishUploadHandler
private IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
public void onFinish(IUploader uploader) {
if (uploader.getStatus() == gwtupload.client.IUploadStatus.Status.SUBMITING) {
String month = VisionProperties.getBulan();
String year = DateTimeFormat.getFormat( "d-M-yyyy" ).format( new Date() ).split( "-")[2];
String strDirectoy = "/var/wms/" + year + "/" + month + "/";
File file = new File(strDirectoy);
if (!file.exists()) {
file.mkdirs();
}
}
if (uploader.getStatus() == gwtupload.client.IUploadStatus.Status.SUCCESS) {
String msg = uploader.getServerInfo().message;
fileName = msg.toString();
if(selectWindow != 2){
img.setUrl("servlet.gupld?show=&fieldname=" + fileName);
itemPanel.render(img.getElement());
}else{
tb.setVisible(true);
tb.setText("Download File "+uploader.getFileName());
}
}
}
};
how to make directory file when upload file process?
You are trying to use to use java.io.File in the client side which is not supported by the set of packages in the GWT jre emulation.
If you want to do this in client side you have to use the javascript File Api which is not supported by old browsers, and is not implemented in gwt-core. Using elemental you could use the Api only with Chrome, but I'm not positive. So it is better to wrap it via jsni, it is planned in gwtupload, but there is no a timeframe yet. Be aware that using js File Api, you dont have access to your real filesystem, but a virtual one inside your browser. To save created files in the local filesystem you have to download it using and iframe so as it asks the user where to save it.
Otherwise, If you wanted to do this work at server side, do it overriding the executeAction in your servlet if you are extending UploadAction.
You cannot do this on client side. You can perform this on server side in the following ways
before you upload the files to server by another rpc/http call.
after you upload the files to server when the file upload servlet is being executed on the srever side.
HTML5 FILE API are restricted to readonly behavior in even modern browser.
Reference -
1. Basic File upload in GWT
2. How to retrieve file from GWT FileUpload component?