How to create folder in root folder of the project? - java

In my project I'm trying to upload files to a drive in my system and when i try to access the file using browser it shows **Not allowed to load local resource: ** error. I think creating and uploading files to the project folder may solve the issue. How to do that programmatically in java?
private final String UPLOAD_DIRECTORY = "D:/dy/Stock";
File filee = new File(UPLOAD_DIRECTORY);
if (!filee.exists()) {
filee.mkdir();
}
name = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
This is the codeI used to create and upload files to folder.

It won't. As a general rule, doing file:// anything in a browser, these days, just does not work. Why not? It's complicated, but, to oversimplify: Security.
It has nothing whatsoever to do with the access rights of the process that asks the browser to load em. The browser just will not do this.
The solution, if you want to have resources open in a browser window from a locally running app, is to have your locally running app boot up a webserver (locally), and then ask the browser to load not, say:
file:///Users/alvin/proj/myfile.txt
but to ask the browser to load, say:
http://localhost:8192/myfile.txt
... which would work, if you start a webserver on 8192.

Related

Relative path of my Java server

I'm trying to create a file in my server. I have sent a image, and I want to create that Image in a folder of my server, but with relative path.
String filePath = "C:\\Users\\Administrador\\Desktop\\Proyecto\\clienteServidor\\Server\\folder\\image.jpg";
File imageFile = new File(filePath);
...
I'm doing with the absolute path.
Thanks
hard coding a directory is seldom good for coding. What happens if there is a typo in your code. Using a combination of ./ or ./*
or even using
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
This is explained here.
It is doable but, as Dmitry said, it might not work on every server. SecurityManager class should be consulted if your webapp has the privilege to write to that folder. or you will get an exception.
One way to do it is via ServletContext:
URL webAppRoot = this.getServletConfig().getServletContext()
.getResource("/images/new-image.jpg");
This will point to your ${tomcat}/webapps/mywebapp/images/new-image.jpg.
Another way is via ProtectionDomain:
URL runningClassLocation = this.getClass().getProtectionDomain()
.getCodeSource().getLocation();
But this will most likely give you jar:file://...myapp.jar!/my/package/servlet.class.
After you have the URL you convert it to File and append any relative path to your image folder.
UPDATE:
I agree with Jim, and emphasize that doing it like this is just for academic purposes.
Java is not like PHP so you shouldn't have uploads folder inside your web application's folder. Usually this is done by enabling an administrator-level user to specify a file path to a folder reserved for your application's storage needs.

How selenium can test if it has read access to a file

Our test-app runs on multiple Virtual Machines through Selenium Remote Control.
The App sits on a test controller Server.
The test-app is used to test a third party online application.
How can I test to see if on certain VM Selenium-RC has read access to a file or folder.
Is there anything like file.canRead(filepath) kind of thing for selenium too?
Before you respond:
File's canRead(filepath) will only test if the file is readable from a test controller server, not able to say anything if it is readable on VM where actual browsers are opening(testing) third-party-online-application.
Basically, I want to upload some file to the third-party-online-application through selenium.
Before doing an upload, I want to make sure that the file is available for upload (on VMs).
A solution would be to create a download link in the application and then attempt to download the file via Selenium. That way, you get a user-representative experience.
If you want to be really fancy, have the Application create a file with the current date and then let the test download the file (simple text file) and check if the file contains the date. Then you test application writing a file and user reading the file, which covers access rights as well.
Which scripting language you are using? If assuming that your file to upload resides under "./data" directory then in java you can check with following steps
File file = new File("./data/myfile.ext");
boolean canUpload = file.exists() && file.canRead();
String fileToUpload = file.getCanonicalPath(); //file name with full path
File file = new File("Folder_Location"); // Folder path if file name not known
boolean canUpload = file.listFiles()[index].canRead();
Note : For latest downloaded file use
int size=file.listFiles().length-1;
boolean canUpload = file.listFiles()[size].canRead();

Zipping a folder in remote machine running app server through J2EE app

I am working on a zipper J2EE application. This application requires the following:
The application has to zip a folder in remote machine where app server is running so that other applications can directly download this zipped folder instead of downloading each file one by one.
I am able to do this in my local machine using absolute path don't know how to go ahead with remote machine.
Code i'm using for zipping in local machine:
File file = new File(myFolderPath);
int index = myFolderPath.lastIndexOf("/");
String folderName =myFolderPath.substring(index);
String folderPath = myFolderPath.substring(0, index);
File outFolder = new File(folderPath + folderName + ".zip");
if (!outFolder.exists()) {
zip(file, outFolder);
}
Here myFolderPath is a string. But how should i go ahead if it is a URL?
Thanks in advance.
URLs don't allow directory listings, so this is not possible. You will need absolute paths on the server, too, or convert the URL to an absoltue path on the server, maybe by replacing a http://server/ with the root folder of the webapp.
My suggestion would be to use a message driven bean for this case. You have a MDB that listens to incoming msgs on a JMS queue. The message has the folder to zip. The message bean then will call a helper that would zip the folder that is provided to the MDB. I'm basing this on the details available in your question. There is a app server running and you want the zipping action to happen on that server machine. It will be much more efficient and clean in my opinion.
The application has to zip a folder in
remote machine where app server is
running
I guess you have fair idea about path to the directory you wanted to zip. So code same thing what you have done locally but in servlet, create zip fiel and write the content of the zip in output stream of HttpServletResponse in order to download it.

How can I create a new folder in my web-app (for upload photo album) with Grails on Tomcat?

i want to create a photo album.
But I want to organize on the server the albums so I want to create new folders :
/myapp
/myapp/albums
/myapp/albums/1
/myapp/albums/2
...
How can I do that on tomcat with Grails ? It create all new folder in tomcat/bin not in tomcat/webapps/myapp/
When I had to do something similar I defined a root path in my Config.groovy like
environments {
production {
rootPath="/home/user/reports"
}
development {
rootPath="c:\\reports"
}
test {
rootPath="c:\\reports"
}
Then create a directory like the following.
import org.codehaus.groovy.grails.commons.ConfigurationHolder as Conf
tempFile=new File(Conf.config.rootPath+"dirName")
tempFile.mkdir()
I don't do Grails, but since it runs on top of the Servlet API, you may find this answer (a steering in the right direction) useful as well.
First, get a handle of the ServletContext. Normally you would use the GenericServlet-inherited getServletContext() method for this. Then make use of the ServletContext#getRealPath() method to convert a relative web path to an absolute local disk file system path (because that's the only which java.io.File reliably understands).
String absolutePath = getServletContext().getRealPath("albums/1");
File file = new File (absolutePath);
// ...
If you use relative paths in java.io.File stuff, then it will become relative to the current working directory which depends on the way how you startup the server and which indeed may be Tomcat/bin as you experienced yourself.
That said, there's another major problem with this approach: if you create folders in an exploded webapp, they will get lost whenever you redeploy the webapp or even restart the server! Rather create folders outside the webapp's context, in a fixed path somewhere else at the disk file system. Or if you want better portability (but poorer metadata information), then consider storing it in a database instead.

JavaFX loading external resources problem

I've coded small JavaFX Applet in Netbeans 6.8 IDE. Everything works fine if the applet runs on my computer. But when I put the applet (and edited JNLP files containing changed paths to server) into server, it doesn't load any data from an server text file. Paths are correct - i look at it many times - they are ok. It also doesn't load images with external urls. What is wrong?
Haven't seen your code so I'm going to make a guess. If your resource is not bundled in your JAR file and you are using file:// to access it, then you will need to sign your applet. On NetBeans, right click on project node -> properties -> application. Select self signed.
If you don't want to sign your applet, then access your resource as REST. Use the HttpRequest.
If it is on the client machine, consider using JNLP APIs like so.
FileOpenService fos = (FileOpenService)ServiceManager
.lookup(“javax.jnlp.FileOpenService”);
//Open dialog pops up
FileContent fc = fos.openFileDialog(null, null);
The best way to diagnose the problem is to open the Java Console and see if there are any exceptions. Run $JAVA_HOME/bin/ControlPanel -> Advanced -> Java Console -> Show Console

Categories