File path (JAVA EE) - java

I'm working in a web project and I'm having troubles with files(java.io.File). The problem is only when I run as web application(tomcat 7), if I run as Java Application, the problem doesn't exist.
When I instantiate a file, new File("dir");, its path become C://Windows/System32/dir, this way, i can't do anything, maybe cause don't have Windows privilegies.
"I solved the problem" passing new File("C://Users/user/dir"), but I don't like this solution. I wanted to do this automatically, get the app path, for example. I'm coding in my machine, and after the deploy.... i don't know.
Any tips?
That's the part of the project that I'm having the problem, a jsf bean. My view calls the method addFile() to save the file that I receive from my view. It's working, but i have to pass the path like I said before, like is on the code below. The path goes to the Windows dir System32
Bean.java
#ManagedBean
#ViewScoped
public class Bean {
//ATTRIBUTES AND METHODS
public void addFile() {
File temporaryFile = new File("temporary");
//...
//...
//...
}
}
Sorry for my english, i'm brazillian.

There is a method in the File class that does exactly what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/File.html#createTempFile-java.lang.String-java.lang.String-
Alternatively you can assemble the file's path yourself:
File myTempFile = new File(System.getProperty("java.io.tmpdir"),"temporary");

you can add folder resources in web folder then add files as you want
i tested it from adding some styles (css) and javascript and call them in jsf page.as example if you create file named x in folder files under web/resources folder
new File("files/x");
wishing the answer helps you .you can tell me if any problem happens again

Related

Why does my Image not load in this path, but in another?

I Tried putting an image onto a JButton. After wrote down the path to the image, ran the Program,then image was not on the Button. Code Sample below:
public static JButton start = new JButton(new ImageIcon("resources//img//menu//Start_Game.png"));
The "resources" folder is in the "src" folder. Here is the Hirarchy in Eclipse
After I double checked I spelled everything right, I put in an other path.
public static JButton start = new JButton(new ImageIcon(System.getProperty("user.home") + "//Tindir//Hauptmenue//Start_Game.png"));
Suddenly it worked. It is obvious that the first path was not correct.
Question If there is a way to input a path to an Image in the same Project-Folder as the Code?
Yes, but not that way - those arguments are filenames, and java code is not deployed as a sack of files. It's deployed as a jar file. An entry inside a jar file does not count and can never be used with this API.
So, don't use this call. Use the other one, that takes a URL, because you certainly can represent either a file, or an entry within a jarfile, as one of those:
MyClass.class.getResource("Start_Game.png")
That is what you put instead of "resources/etc/Start_Game.png" in that code. This looks for a resource named Start_Game.png in the exact same place that MyApp.class is found, even if that is found inside a jar file, loaded out of a DB, live-streamed from the internet - whatever. You're using the same mechanism.
If your Start-Game file is somewhere else, start with a /. It seems like you want /img/menu/Start_Game.png here.
This trick is an easy way to get an idea of what you're doing:
class MyClass {
public static void main(String[] args) {
System.out.println(MyClass.class.getResource("MyClass.class"));
}
}
and you'll figure it out with that output.

ServiceLoader cannot find service loaded from path

I have been trying to do a kind of plugin-system using the ServiceLoader. There are 2 modules, the first provides the abstract class LoadedRealmPlugin. The second one extends this class. I have added the file corresponding to the full name of the ServiceProvider and added the service-class to it. IntelliJ does not find any errors (but when changing the filename or classname it does). Here is the structure:
MainModule
src
main
java
com.interestingcompany.mainmodule
LoadedRealmPlugin
MainModule.iml
Plugin
META-INF
services
com.interestingcompany.mainmodule (-> Content: "PluginExtension")
src
PluginExtension
Plugin.iml
(This is simplified, I left out classes that (I think) are not important to the ServiceLoader. I can post a screenshot of the actual structure if anyone needs it)
Here is the code I use to load the Service:
File file = new File("Plugins/Plugin.jar");
URLClassLoader c = new URLClassLoader(new URL[]{file.getAbsoluteFile().toURI().toURL()});
ServiceLoader<LoadedRealmPlugin> loader = ServiceLoader.load(LoadedRealmPlugin.class, c);
LoadedRealmPlugin p = loader.iterator().next(); // Throws a java.util.NoSuchElementException
p.Initialize(RealmPath); // Abstract method implemented in the service
return p;
When trying to run it, I always get an empty ServiceLoader. I looked at this post, but I was not quite sure about how to apply that answer since I am trying to load my plugin from a file. In addition, I found this post. Yet, there was no answer, just some comments that did not seem to have answered the question.
As you might have been able to tell, this is my first time working with classloaders. If there is any additional information needed, just ask me. Thank you for reading through my beginner troubles.
package-less classes are in the unnamed package, which is inaccessible to rather a lot of code, notably including here.
Put PluginExtension.java in a package, make sure the content of your META-INF/services/com.ic.mainmodule file reflects this (content should be pkg.PluginExtension), and it'll work fine.

Tomcat webclassloader fails to find a class

In a Tomcat 7 I have a pretty standar jar file on WEB-INF/lib. Inside this jar I have this class called Parser, and next to it (on the same dir) I have another one called AutomaticLocalLoader. Compilation gives no problem at all. In run time the AutomaticLoader class is found, and when It needs the Parser class, I get a NoClassDefFoundError
The Parser and AutomaticLoader class have been working without this problem for 15 years!! in many diferent vers of java and tomact; and now out of the blue, I am getting this NoClassDefFoundError, only for the Parser class. I already put a copy on a directory inside the WEB-INF/classes path and still got the same error. I already created my own ClassLoader to see if I get some error loading the class from the WEB-INF/classes directory by myself, but I can load it without problems.
log.info("Leer " + aFlInstructions[i].getAbsolutePath());
LoaderTest A = new LoaderTest();
A.test("com.hds.resolve.model.aguila.AutomaticLocalLoader");
LoaderTest B = new LoaderTest();
B.test("com.hds.resolve.model.aguila.Parser");
if(!bOverrideInputDir)
Psr = new Parser(aFlInstructions[i]);
else
Psr = new Parser(aFlInstructions[i], new String[] { StrLocalDirectory } );
The LoaderTest class, try to create the Class Object for the given name using Class.forName. If NoClassDefFoundError, then try to load the class using my own classloader and then create the class.
For the AutomaticLoader, it succed at the first try. For the Parser class if fails, then successfully load it with the custom classloader. Of course when the code reach the "new Parser" part, the old webclassloader still fails and throws the NoClassDefFoundError.
Both Parser and AutomaticLocalLoader belong to the same package and are stored on the same jar inside WEB-LIB.
Funny enough, the error does always happen on production... but never in my machine. I do not use customs classloaders except for doing this debug. Also, trying an old version of the software seems to fix the error. No idea why.
I think I can hack a solution messing with the tomcat's webclassloader, but I really would prefer to understand what is going wrong with this code.

Eclipse RCP: InternalPlatform.getDefault().getUserLocation() doesen't return C:\Users\username\AppData\Roaming

I am currently migrating an Eclipse 3.0 application to 4.4. The user data was and still should be stored in the folder C:\Users\username\AppData\Roaming\applicationname
The application is using following code to read the directory:
public static String getUserDirectory()
{
String directory = InternalPlatform.getDefault().getUserLocation().getFile();
return directory;
}
I know the code is deprecated, but following code returns the same:
public static String getUserDirectory()
{
String directory = Platform.getUserLocation().getURL().getFile();
return directory;
}
They both return C:\Users\username\user but as I said the user data should be stored at C:\Users\username\AppData\Roaming\applicationname. Did the behaviour of those methods change?
How can I realize that I store my user data under C:\Users\username\AppData\Roaming\applicationname and my application can still find the directory?
I know this has to do something with environment-variables which I don't fully understand.
I don't have a 3.x target platform at hand to compare but C:\Users\username\user looks plain wrong.
If you are interested in the details, the constructor of EquinoxLocations computes the userLocation and adds the literal 'user' the the user's home directory if no default is specified.
Hence, if you start your application with -user #user.home or -Dosgi.user.area=#user.home, the user location will be set to C:\Users\username\. Still not what you are looking for, but at least a sane value.
I think this is a bug in Equinox and recommend to file a bugzilla. If it turns out that there is a good reason for this appraoch the bug entry will still serve as documentation/reasoning.
In the meanwhile you could obtain the home directory on Windows through System.getenv( "APPDATA" ). According to this post it will return the roaming home directory.
I solved the problem by adding three properties in the Configuration tab of my config.ini.product-file:
osgi.configuration.area =
#user.home/AppData/Roaming/ApplicationName/...
osgi.user.area =
#user.home/AppData/Roaming/ApplicationName/...
osgi.instance.area =
#user.home/AppData/Roaming/ApplicationName
Now my method as stated in my question reads the paths that are configured by those properties and the config.ini file which is generated looks exactly like the one of the old build with Eclipse 3.0.

Which path should I use when calling a java properties file?

Basically I have the model of my project set up this way:
ModelFolder
-----src
-----bin, etc.
-----PropertiesFolder1
--------File1.properties
--------File2.properties, etc.
-----PropertiesFolder2
--------File1.properties
--------File2.properties, etc.
-----MainPropertiesFile1.properties
-----MainPropertiesFile2.properties
I am trying to use it with my View, which is a Dynamic Web Project, and I got the properties files to finally load in my Web Project after changing
foo.load(new FileInputStream("foo.properties"));
to
foo.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("foo.properties"));
and exporting the project to a JAR file, which I then included in WEB-INF/lib. However, I had to add another method to the Model, and when I tried testing that method, the Model was not able to read my properties file. I know that I can use FileInputStream with the full path to get the properties file working in the Model and the View, but are there any alternatives?
I don't want to keep changing the full path every time I switch computers (I use H:\username\...\Java\Workspace at work, whereas at home it's just C:\Java\Workspace).
I also don't want to have to move my properties files to different folders; and finally I don't want to change the way I load the properties file every time I test my Model or my View.
Is there a way to accomplish this?
This is driving me crazy, I've tried all of the following:
try
{
foo.load(this.getClass().getResourceAsStream("foo.properties"));
//foo.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("foo.properties"));
//foo.getClass().getResourceAsStream("foo.properties");
//foo.load(new FileInputStream("foo.properties"));
} catch (IOException ex)
{
al.logIntoProgrammerLog(ex);
}
All of those lines either work in the model or the view. Is there any way I can call those properties files via a relative path in the model, and then somehow properly connect the model with the view so that all the files are found and loaded?
Any help would be greatly appreciated; I am new to Java, so I might be missing something really simple. Thank you.
EDIT:
Sorry for not clarifying this, the Model is a Java Project, whereas the View is a Dynamic Web Project running on local Tomcat Server v6.0.
Better (I hope) explanation:
My View has a LoginServlet with the following doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = request.getParameter("usernameField");
String password = request.getParameter("passwordField");
ActivityLogger al = new ActivityLogger();
LoginController l_c = new LoginController();
//loginUser method will call my UserStorage class and
//will return true if UserStorage finds the User with those credentials in the db
//UserStorage is using a prepared sql statement stored in a properties file to find the User
//That properties file is not being read unless I specify the full path to it.
//Both Login and UserStorage are in the Model
if(l_c.loginUser(username, password))
{
//take user to welcome page
}
else
//display error
}
Thanks again
Take a look at this thread for possible solutions for sharing a .properties file. But I would suggest that you review this approach to see if it's really what you want. More specifically, if your .properties file contains SQL queries, then are you sure you need it in your View? Sounds like you may want to make a clean separation there.
If you are in a web application, you should be able to get the path (relative path in the context of the webapp, so it will work on any machine) by using the ServletContext's getResourceAsStream(). For example, if you wanted to get the path from your servlet's doGet() method:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
InputStream in = getServletContext().getResourceAsStream(<path>);
}
where <path> would be the relative path to your .properties file (i.e. /WEB-INF/foo.properties, or wherever that properties file is located... look in your deployment folder to find out for sure)
But in re-reading your post it seems like perhaps your "Model" is not a webapp and your "View" is a webapp? Maybe you could clarify whether these are two different applications - and possibly one being a webapp running within a servlet container (i.e. Tomcat, Glassfish, etc) and one being a standalone app? If that's the case then this is more of a shared file issue than a 'cannot find resource' issue. A bit of clarification about the nature of your application(s) would help steer the correct response...

Categories