Can't find property files on classpath - java

I'm trying to load/read property files on glassfish 3.1 server.
I can't get it to work. I've searched and tried many possible solutions.
None worked so far, always NULL as result.
I've tried methods from the following link:
How to use a property with Glassfish
My method:
final public class GTS_Properties{
...
public static Properties getPropertiesFromFile(String fileName){
URL url = GTS_Properties.class.getResource(fileName)
...
// url is always null
}
}
My configuration:
Folder properties on build path.
/root/WEB-INF/classes/****.properties
How the Glassfish server looks like (using eclipse startup plugin)
/glassfish-root/domain/eclipseApps/MyWebApp/WEB-INF/classes/****.properties
I have tried to put the property files directly in WEB-INF instead of classes. same result.

I solved it by first going 2 'parent folders up' from the startpoint of the relative path.
Inserting "../../" on the start of the path was all that was needed.
WEB-INF/classes/WebApp/utils/GTS_Properties.class (The class to get the resource from)
WEB-INF/classes/prop.properties (Location of the resource file)
GTS_Properties.class.getResource("../../prop.properties")

Related

Unable to load Ignite config spring bean definition from non default location in spring boot application

I am trying to externalize my ignite configuration in my spring boot application so the configuration can be changed without rebuilding the jar.
Previously the file resided in src/main/resrouces and was loaded via annotations.
#ImportResource("IgniteConfig.xml") and
#Autowired
private IgniteConfiguration cfg;
When I moved the IgniteConfig.xml to the config folder that resides next to the excutable jar the above stopped working and I have tried the following without success:
use --spring.config.location argument. I can tell this is picked up during run time as other configurations work but the above ImportResource annotation says the file IgniteConfig.xml cannot be found.
use a relative path to (e.g. ./config.IgniteConfig.xml) to Ignition.start. I cause this relative path to print the file contents of the xml file in my logs but when I pass it to Ignition.start it says the file cannot be found. I have tried using relative and absolute paths to do this.
Manually create an ApplicationContext and get the configuration by bean name.
ApplicationContext context = new ClassPathXmlApplicationContext("./config/IgniteConfig.xml");
This again complains that the file does not exist even though I can see by opening the file directly:
File igniteConfigFile = new File("./config/IgniteConfig.xml");
The comment by konqi in this post answered my question:
"In case you want to import a resource that is outside the classpath the syntax would be:
#ImportResource( { "file:path/spring-context1.xml", "file:path/spring-context2.xml" } )
"
In my case I just needed to do:
#ImportResource( { "file:./config/IgniteConfig.xml" } )

Spring boot serving static resource

I work on spring boot application. I'm trying to serve static content with spring.
want to serve a resource stored in the /c:/frontend/files/ directory whenever a request comes in for the URL matching the pattern: /file/**:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/file/**")
.addResourceLocations("file:///C:/frontend/files/" );
}
but when i try to access to this resource using this url: http://localhost:9999/file/app.min.js
I have this problem
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation
I resolved the problem. it's related to "spring-cloud-config-server". I just delete this config: org.springframework.cloud spring-cloud-config-server
It sounds like your project's folder structure is wrong.
Code should go under src/main/java and resources (like your javascript) should go under src/main/resources. You have a few different options where you can actually serve the files from. This post on the spring.io blog has the following to say:
Spring Boot will automatically add static web resources located within any of the following directories:
/META-INF/resources/
/resources/
/static/
/public/
Another option you also have is using webjars.
Personally, I've found it easiest to put those kind of files under src/main/resources/public. It always works without any issues for me. The interesting thing is you can put a folder named /public anywhere in your project and spring-boot will serve files out of it. You have to be really careful that it's under src/main/resources/public though if you're using a build tool like maven, as when you come to build your .jar the files won't be in the right place otherwise.

access via spring injected property which references a directory to access its files

I'm trying to access a property defined in a bean like this:
<bean id="reportdepositService" class="a.b.c.ServiceImpl">
<property name="reportDeposit" value="/WebContent/WEB-INF/dirName/" />
</bean>
ServiceImpl class looks like this:
public class ServiceImpl implements IService {
private Resource springResource;
public Resource getSpringResource() {
return springResource;
}
public void setSpringResource(Resource springResource) {
this.springResource = springResource;
}
private File getSpringResourceFile() throws IOException{
Resource r = getSpringResource();
URL url = FileLocator.resolve(r.getURL());
return FileUtils.toFile(url);
}
public void doSomething(){
.. some logic .
File f = getSpringResourceFile();
}
executing that code within eclipse on a ubuntu machine works fine, application build on a jenkins works fine as well on ubuntu. Running that application on a win7/64, the code throws the following exception:
OSGi resource[/WebContent/WEB-INF/springResource/|bnd.id=332|bnd.sym=a.b.server] cannot be resolved to URL because it does not exist
java.io.FileNotFoundException: OSGi resource[/WebContent/WEB-INF/springResource/|bnd.id=332|bnd.sym=a.b.server] cannot be resolved to URL because it does not exist
at org.springframework.osgi.io.OsgiBundleResource.getURL(OsgiBundleResource.java:228)
What is necessary to access the property on windows hosted system?
Any ideas?
Thanks in advance
I am not sure whether you are on the correct road with this:
The /WebContent/WEB-INF path suggests that you are writing a web application to be run in a web container. In that case you should never assume that your resource is a file. You should open the resource using Resource.getInputStream() in stead of using the URL/File. The reason is that the the application may well be run directly from the .war without a file system being available.
That may immediately answer the question: is the Windows 7 environment the same in relation to the run-enviroment? My impression is that it is not. If you bundled the project into a bundle jar while transporting it to the windows machine, I guess you should add a prefix to the path (but probably need to leave the WebContent off), like bundle:, classpath:, etc. See Spring OSGI reference. But you need to give a little more information to be sure.

FileNotFoundException in test case run with maven using Spring resource loader

Our program is sending mails. For sending mails it includes an attachment.
The project is set up with maven. The JUnit test case loads the spring configuration first. Spring is loading the File with its DefaultResourceLoader. When running this directly within the workspace its running fine, however as a maven test it fails.
Spring Configuration for resource loader:
<property name="defaultResourceLoader">
<bean class="org.springframework.core.io.DefaultResourceLoader" />
</property>
ImplementingClass:
#Service
public class SomeClassA {
#Autowired
private DefaultResourceLoader defaultResourceLoader;
#Value("${mailLogoPath}")
private String mailLogo;
public void someMethod(){
String filePath = defaultResourceLoader.getResource(mailLogo).getFile().getAbsolutePath();
}
}
The exception points to the actual problem and difference:
java.io.FileNotFoundException: class path resource [templates/efmaillogo.jpg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/C:/IBM/workspace/efMy10/ef-mvxsrv-reactor/ef-mvxsrv-service-resources/target/ef-mvxsrv-service-resources-1.5.23-SNAPSHOT.jar!/templates/efmaillogo.jpg
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:204)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:52)
at SomeClassA.someMethod(SomeClassA.java:9)
Spring tries to look the file up within the jar. When running it as a junit test within eclipse, everything is working, because spring finds the file directly within the workspace. However when running the same unit test with maven it fails, because it doesn't find the file, because its in a jar in a different module. The file in the other module is needed by different modules, so I don't want to move it. On the application server where everything is deployed its working as well, because the .ear file is expanded.
I'm wondering if there is a different way to access the file with Spring, so that I don't have to skip this test case with maven.
Update
Tried doing a lookup for the file with:
String filePath = defaultResourceLoader.getResource(mailLogo).getURL.getFile();
However it now fails when actually sending the mail with Transport.send(msg).
java.io.FileNotFoundException: file:\C:\Users\uhe.m2\repository\com\clavisit\ef\mvxsrv\ef-mvxsrv-service-resources\1.5.23-SNAPSHOT\ef-mvxsrv-service-resources-1.5.23-SNAPSHOT.jar!\templates\efmaillogo.jpg (The filename, directory name, or volume label syntax is incorrect.)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1141)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.clavisit.ef.ep.service.integration.handler.mail.SendMail.sendMessage(SendMail.java:153)
String filePath = defaultResourceLoader.getResource(mailLogo).getURL().getFile();
The above code change must work as per the discussion in this thread http://www.coderanch.com/t/474047/Spring/Spring-cannot-find-file-classpath

Getting tomcat's installation directory using java

I want to get tomcat's installation directory in my computer using java. I tried using :
System.getProperty("catalina.base");
and
System.getProperty("catalina.home");
But both methods return null as the answer. I tried it with System.getProperty("java.home"); and it correctly returns the java path.
Any ideas as to what the problem is? Thanks
Try installing this JSP and passing various values for the "property" parameter:
<%
String propertyName = request.getParameter("property");
Object propertyValue;
String typeString;
if(null == propertyName)
propertyValue = null;
else
propertyValue = System.getProperty(propertyName);
if(null == propertyValue)
typeString = "null";
else
typeString = propertyValue.getClass().getName();
%>
The system property <code><%= propertyName %></code> has the value:
<code><%= propertyValue %></code> (<%= typeString %>).
Maybe you can find a pattern to which property values return null.
I also encountered the same error as you did. but then I realized that the tomcat server was not running. After starting the server, I still failed to get the tomcat path.
Then I realized that I was trying to get the path from the main method in a JSF project while tomcat was still running.
So i finally got the tomcat path by using: System.out.println(System.getProperty("catalina.base")); in a #PostConstruct method of one of my #ViewScoped beans in a JSF project. And it successfully displayed C:\Documents and Settings\S!LENT W#RRIOR\Application Data\NetBeans\7.2.1\apache-tomcat-7.0.27.0_base in the console in NetBeans.
So In order to get Tomcat's installation directory, following points should be kept in mind:
Tomcat Server is running
You're not trying to get path from main method
hope this helps
we are using cucumber for testing and in cucumber cases, we are accessing project's individual method. in project, we are reading configuration for xml and the location is in config folder of Apache tomcat. Now when i run project,System.out.println(System.getProperty("catalina.base")); it's provide the proper path however when i call project's method from cucumber then it's returning null

Categories