Creating a folder within web server under /public_html/ in Java - java

I am trying to create a folder within web server using Java File handling APIs in my RESTFul web service developed using JERSEY.
According to my understanding, when I target "xyz.com" , it by default points out /home/xyz/public_html/ in my server.
So when I try to create a folder as follows
String appFolderPath = "/xyz.com/appFolder/";
File userNameFolder = new File(appFolderPath + userName);
if (!userNameFolder.exists()) {
folderPath = userNameFolder.mkdir();
}
The above code fails, I am not getting any exception, and no folder is created.
How exactly I suppose to do it ? How to give path for public_html/ folder ?
Another point is, is it not happening because of permission issue ? , I actually tried another way , I manually created /appFolder under public_html/ and give full read write permission to that folder, but still I couldn't create any folder within that using above code.
Please let me know how to achieve it ? Any Sample code ?
Also if possible let me know if JERSEY does give me APIs to make it simple ?

To point to public web directory use
ServletContext context = request.getServletContext();
String path = context.getRealPath("/");
and append your path to the path (above resolved)

According to my understanding, when I target "xyz.com" , it by default points out /home/xyz/public_html/ in my server.
What makes you think so? You're operating files in the code snippet given, so your path means /xyz.com/appFolder/ and nothing more. And it's very likely you're facing a permission issue trying to create folders like this.
As for absense of exception, that's a design feature of Java file API not to throw exceptions on certain failures, but rather return erroneous error codes. Check what is returned by mkdir() call and you'll find false there, as a signal of failure.

Related

ZAP API context data isn't valid

I am trying to automize pentesting with ZAP using the Java API. In the desktop app of ZAP I created a context, which is saved in the contexts directory of the OWASZP ZAP folder it created during the installation. Using the importContext function down below I think that I should receive the context.
context = new Context(ApiClient);
context.importContext("contextName.context");
Now it does find it, without the ".context" at the end it doesn't. It gives me an error message though.
Exception in thread "main" org.zaproxy.clientapi.core.ClientApiException: The external data provided is not valid.
at org.zaproxy.clientapi.core.ApiResponseFactory.getResponse(ApiResponseFactory.java:50)
at org.zaproxy.clientapi.core.ClientApi.callApi(ClientApi.java:351)
at org.zaproxy.clientapi.gen.Context.importContext(Context.java:186)
at jh.zap.main(main.java:14)
Does anybody know why? Any help is very much appreciated.
Try using the full path rather than just the name. If you look in the zap.log file it should give you more info, including the full file name it was actually trying.

How to get filepath?

I am working on an Eclipse Web Dynamic Project, and trying to access a file that exists in my local machine/server.
What I am looking for is something like "base_url()" in CodeIgniter, which automatically points to the directory the server is located.
I am using a Mac.
try{
model.read(new FileInputStream(url),"");
}catch(IOException e)
{
System.out.println("Exception caught"+e.getMessage());
}
This is the part of the code I am working on, which I am trying to feed the correct URL path to read.
After searching StackOverflow and other places, I came across this piece of code:
String url = request.getRequestURL().toString().replace(request.getRequestURI().substring(1), request.getContextPath())
+"/WebContent/WEB-INF/test.xml";
Which did not seem to work.
I then tried to hard code the path directory in, only to realise that I dont know how Mac file systems work :/
Can anyone share some light on this?
Thank you in advance
I did not understand very well if you are using a servlet or something else (like a WS), however the request object exposes a method called getRealPath() which gives well... the real path of the servlet's context in your file system.
So you need to change your code with this:
String url = this.getServletContext().getRealPath("")+"/test.xml";
It has nothing to do with OS, as you surely know java is portable.
I think what you want is
String path = getServletContext().getRealPath("/");
which point to the bas directory of your application in the server
e.g. /opt/tomcat/webapps/MyApp
I always use getResourceAsStream and suck it up off of my class path. Flat file names are problematic inside of web applications.

getClassLoader().getResource(filepath) returns a null pointer

I'm using a method to generate XML files dynamically for a research project, they get put into a loader that reads from a file path, I don't have any control over how the loader handles things (otherwise I'd pass the internal XML representation instead of monkeying with temp files), I'm using this code to save the file:
File outputs = File.createTempFile("lvlFile", ".tmp.xml");
FileWriter fw = new FileWriter(outputs);
fw.write(el.asXML());
fw.close();
// filenames is my list of file paths which gets returned and passed around
filenames.add(outputs.getAbsolutePath());
Now, I'm sure that the file in question is written to directly. If I print outputs.getAbsolutePath() and navigate there via terminal to check the files, everything is generated and written properly, so everything is correct on the filesystem. However, this code:
URL url = this.getClass().getClassLoader().getResource(_levelFile);
Where _levelFile is one of my filenames generated above, causes url to be null. The path isn't getting corrupted or anything, printing verifies that _levelFile points to the correct path. The same code has succeeded for other files. Further, the bug doesn't seem related to whether or not I use getPath(), getCanonicalPath(), or getAbsolutePath(), further setting outputs.isReadable(true) doesn't do anything.
Any ideas? Please don't offer alternatives to the Url url = structure, I don't have any control over this code*, I'm obligated to change my code so that the url is set correctly.
(*) At least without SIGNIFICANT effort rewriting a large section of the framework I'm working with, even though the current code succeeds in all other cases.
Edit:
Again, I can't use an alternative to the URL code, it's part of a loader that I can't touch. Also, the loading fails even if I set the path of the temp file to the same directory that my successfully loaded files come from.
I assume that the ClassLoader will only look for resources within the class path - which probably doesn't include /tmp. I'm not sure if it actually supports absolute path names. It might just interpret them as relative to the root of the individual class path.
How about using _levelFile.toURI().toURL() instead?
Your are creating file in file system and then trying to read it as a resource. Resource is where JVM takes its classes, i.e. the classpath. So this operation will work only if your are writing file into your classpath.
And even if this is correct be careful: if for example you are running from eclipse your process will not probably "see" the new resource until you refresh your workspace.
Now my question is: Are your really sure that you want to read files as resources. It seems that your just should create new FileInputStream(_levelFile) and read from it.
Edit
#Anonymouse is right. You are creating temporary file using 2-arg version of createTempFile(), so your file is created in your temporary directory. The chance that it is into your classpath is very low... :)
So, if you want to read it then you have to get its path or just use it when creating your input stream:
File outputs = File.createTempFile("lvlFile", ".tmp.xml");
..........................
InputStream in = new FileInputStream(ouptuts);
// now read from this stream.

java windows file creation

i am checking the text file which is present in the mapped hard drive or not.
File cfile = new File("R:\\Link Fixer Reports\\ServiceTest.txt");
but it shows that file is not present
when use c:\\t.txt
it shows the file
what is the problem and how can i rectify the problem?
It's likely that the user that your code is running as can't see the mapped directory.
You've tagged this question as java-ee so I'd guess that this code is running within a web service or similar? What user is your application server running as? Verify that this user can access the location. As #Christian pointed out, a UNC-Path is a better way to go - just make sure that you can access the network location. Try runas net use to double-check.

Java Desktop API not working with network paths? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Not possible to launch a file on a network using Java Desktop?
I am trying to use the Desktop API to launch the appropriate app for a file. So i am using this :
if (Desktop.isDesktopSupported())
Desktop.getDesktop().open(new File(path));
where "path" is a String pointing to the file.
Everything works fine until i try to launch a jpg that resides at a network location (for instance "\\MyNet\folder\image.jpg") when i get an IOException :
java.io.IOException: Failed to open
file:////MyNet/folder/image.jpg
Any one knows if there is a way to fix this?
I believe you need to specify the file location/name in standard URI format - which is close to the standard format except for servers. See the javadocs for the URI Class for more information.
At the highest level a URI reference (hereinafter simply "URI") in string form has the syntax
[scheme:]scheme-specific-part[#fragment]
And a little later:
A hierarchical URI is subject to further parsing according to the syntax
[scheme:][//authority][path][?query][#fragment]
so the URI should look something like the following:
file://MyNet/folder/image.jpg
where "file://" is the protocol, "MyNet" is the server, and "/folder/image.jpg" is the directory location under the share.
Hope this helps a little.
file:////MyNet/folder/image.jpg is not a file path. It's an URL.
File f = new File("\\\\192.168.0.4\\mybookrw\\save\\command.txt");
Desktop.getDesktop().open(f);
Worked fine for me. The one caveat is that you have to be authenticated against the share already. If you paste the path into the run box and it prompts you for a username and password then its not going to work from an app.
Everyone so far has assumed that the file isn't being found.
However, looking at the Desktop open() function, an IOException is thrown
if the specified file has no associated
application or the associated
application fails to be launched
Now, having said that, what happens if you open a jpg on your local machine? Also, what happens if you try manually launching the jpg through the network?
Edit: Actually, the problem may be that the default program set to open jpg files doesn't understand file:// uris. Sticking with UNC paths might be a better choice.

Categories

Resources