access tomcat alias dir from java - java

In Tomcat7 there is an option to use aliases from the context like this:
<Context aliases="/up=/var/tomcat/upload"></Context>
With this I can access files from outside the webapp. Now, I want to write and read from this dir from my Java code, but do not know how to.
I can do this:
servletContext.getResourcePaths("/up/")
Which shows me the content of /var/tomcat/upload.
How can I write to this dir?
What I did with the excepted answer:
add this to context.xml:
<Context aliases="/up=/var/tomcat/upload">
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow=".*" />
<Parameter name="uploadDir" value="/var/tomcat/upload"/>
and this in my java code:
String uploadDir = servletContext.getInitParameter("uploadDir") + subDir;
OutputStream bos = new FileOutputStream(uploadDir + fileName);
And this works but I could use only the parameter and skip the aliases because for java it does not help. So I'm not quite sure what the idea behind the aliases. I thought it was for uploading files because after a redeploy this dir and content will not be overwritten. But if java can only access it with an extra parameter than it only can be used for serving static content which could be inside the webapp (inside the war).

You separately tell your Java code the path to your upload folder (/var/tomcat/upload) so it can read/write files there.
Example:
<Context aliases="/up=/var/tomcat/upload">
<Parameter name="uploadDir" value="/var/tomcat/upload"/>
</Context>
Your java code can get the parameter value by calling ServletContext.getInitParameter("uploadDir").

Related

Spring MVC - referring an uploaded image

I have implemented an image uploading functionality. The problem is that I am saving these files outside an application (so that they won't be deleted in case of redeploy), and I don't really know how to refer them from a jsp file then, as I only know how to refer to the webapp (or resources) directory.
Have you tried adding to server.xml under $CATALINA_HOME/config/server.xml
<Context docBase="/usr/local/tomcat/folder/with/images" path="/uploads/img" />
For example:If you have foo.jpg inside the
/usr/local/tomcat/folder/with/images directory
then you can access the foo.jpg file via
localhost:8081/uploads/img/foo.jpg

Read common external property file in Java Webapp and java normal app

I know this question has answered many a time with most useful answer as below,
Where to place and how to read configuration resource files in servlet based application?
However, We have some special requirement as below,
Webapp will be deployed to tomcat.
Normal java app in form of .jar will be placed under folder /myapp
myappConfig.property file will be placed under /myapp
Directory Structure on client machine
/myapp
/myapp.jar
/assests/myappConfig.property
/tomcat/webapps/myapp.war
Basically myapp.jar and myapp.war will access sql db connection values for MySql database connection and db operations.
Accessing myappConfig.property from myapp.jar --> Working fine
File jarPath = new File(Myapp.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String propertiesPath = jarPath.getParent();
System.out.println(" propertiesPath-" + propertiesPath);
mainProperties.load(new FileInputStream(propertiesPath + "\\assets\\myapp.property"));
Can anyone help/suggest how to implement,
Accessing myappConfig.property file from mywebapp,
provided run time change in myappConfig.property file does not required myapp.war to be redeployed
Thanks for your help in advance.
edit
Below is the steps in which we want to deliver the project to client.
Below is my app directory
/myapp
/myapp.jar
/assests/myappConfig.property
/tomcat/webapps/myapp.war
pack everything in one package with some packaging tool.
Run this package in client machine at any location and it will have same directory structure as above
Here, I do not want to hard code any location in webapp or tomcat for "/assests/myappConfig.property"
Normal Java app I can read property file but for wepapp I am not getting clear idea for how to do that?
You can add a <context> to tomcat/conf/server.xml (in this example, linux path):
<Context docBase="/home/yourusername/tomcat/assests" path="/assets" />
If you are using Windows:
<Context docBase="C:\path\to\myapp\assets" path="/assets" />
And then you can access it like any other resource within your webapp (e.g.: /assets/myappConfig.property).
If you are using JDBC for example, you could store the connection properties in a Singleton and request it from there, and that class could take care of change checks on that file.

Reading properties file from server location

How do I read a file from a location on my server?
I can successfully read from /WEB_INF/classes using:
InputStream systemParamInputStream = getClass().getClassLoader().getResourceAsStream("ldap.properties");
However, I would like to have this file somewhere on the server, so that it can be configured by the support folks when the application goes live in production.
My liberty profile server.xml lives here: C:\eclipse\runtime\usr\servers\tmpServer.
This would be fine, as indeed would any other location around there.
"WEB-INF/classes" is part of your classpath.
You can continue to read files as you do, by adding another folder to the classpath of the server. In that folder you would have the configuration files.
But you can also access the file directly like this:
InputStream systemParamInputStream=new FileInputStream(filePath);
The trick would be to find a clean way of configuring filePath of the configuration file as hardcoding is not nice. This is an option:
new FileInputStream(System.getProperty("filePath","C:\\eclipse\\runtime\\usr\\servers\\tmpServer"));
And you would send filePath as program parameter -DfilePath=c:\\
I'm using java.util.Properties:
Properties props = new Properties();
props.load(new FileReader("path to your file"));
This thread shows different approaches for doing it.
The one I have successfully tried is to specify a folder as a library in server.xml, so that it will be available in the classpath:
<library id="configResources">
<folder="${server.config.dir}/config" />
</library>
<application location="foo.war">
<classloader privateLibraryRef="configResources" />
</application>
Two minor warnings regarding this approach:
Requires 8.5.5
May result in a server.xml XML validation error in Eclipse due to the use of the folder element (cvc-complex-type.2.4.a: Invalid content was found starting with element 'folder'. One of '{fileset}' is expected.). I gave a try to use a fileset instead but could not get it to work.

How to access folder which is outside war file?

I have application which is having lots of PDF files , when I try to build a war file of my application due to pdfs its size converts to Gbz , so basically I want to remove the pdf file folder from the application ,put it some location and then build a war file and deploy it to tomcat.so ,is there any way I can read folder from my application which is outside the war file?
You can use the File class to work with files and directories on the local file system.
For example if if your pdf files are in a folder called pdf you can create a File object like so
File pdfsFolder = new File("\pdfs");
You need to have a separe folder on your server to store the pdf. You pass this folder location to your application (for example using globaresouces in server.xml, so your production path and local path are coming from the server rather than hardcoded in your app.). You access the given folder normally from java (new File(dir), Paths.get...). If there is no SecurityManager you can access any part of the filesystem from within your webapp.
For example your aplication META-INF/context.xml
<Context>
<ResourceLink global="PDFPath" name="PDFPath" type="java.lang.String"/>
</Context>
Your tomcat, inside server.xml
<GlobalNamingResources>
<Environment name="PDFPath" value="D:\\Data\\PDFs" type="java.lang.String" override="false"/>
</GlobalNamingResources>
In your code:
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
String storagePath = (String) getContext().lookup("PDFPath");
File pdfDir = new File(storagePath);
ya its correct way but give the Tomcat user permission to access the Pdf file , which is use to avoid the file listing when the time of directly url access Ex (www.yourSite.com/pdf/ex.pdf)

Jboss image upload and http access to show image

I am uploading images to jboss server by getting the absolute path using the following code
getServletContext().getRealPath("");
The uploaded image is moved to the absolute path and I can access the image using http://test.com:8080/image.jpg
My problem is the image is being uploaded to the tmp directory of jboss server, so i am losing the uploaded images in the next deployment.
I tried uploading the image to various paths to make it work
\jboss-5.0.1.GA\server\default\deploy
and here \jboss-5.0.1.GA\server\default\work\jboss.web\localhost as well
But fails, I cannot access the image using http://test.com:8080/image.jpg
Kindly help me out in this...
You can add a new context to specify a path to access an external folder.
Steps for Jboss 4 and older versions:
Open your file /YOURINSTANCE_JBOSS/deploy/jboss-web.deployer/server.xml.
Define a new Context in the tag <Host name=”localhost” ...>
Example:
<Host name=”localhost” ...>
<Context path=”/myfolder” docBase=”/home/username/my_images” reloadable=”true”></Context>
Where /myfolder will be the path that you are going to use to access your files, and /home/username/my_images the folder where you are going to upload your pictures.
Restart JBoss
Now you will be able to access your files with the next path:
http://yourserver:yourport/myfolder/filename
Steps for Jboss 5:
Create a new file named context.xml into your WEB-INF folder with the next content:
<?xml version="1.0" encoding="UTF-8"?>
<Context allowLinking="true" cookies="true" crossContext="true" override="true">
<Resources allowLinking="true" className="YOUR_PACKAGE.MyResources" homeDir="/home/username/my_images" />
</Context>
Where className is the java class that will access the resources and homeDir your external directory.
According to this link create a new class to access your resources defined in the file context.xml
Example:
public class MyResources extends FileDirContext {
}
Now you will be able to access your files with the next function:
request.getServletContext().getResourceAsStream(uri);
Steps for Jboss 5 and older versions:
Create a new file named context.xml into your WEB-INF folder with the next content:
<?xml version="1.0" encoding="UTF-8"?>
<Context allowLinking="true" cookies="true" crossContext="true" override="true">
<Resources allowLinking="true" homeDir="/home/username/my_images" />
</Context>
Where homeDir is your external directory.
Create a symbolic link: YourDeployedProject.war/myfolder linked to /home/username/my_images
Windows:
mklink /D C:\YOUR_JBOSS_SERVER\server\default\deploy\YourDeployedProject.war\myfolder C:\users\YOURUSER\my_images
Linux:
YourDeployedProject.war# ln -s /home/username/my_images myfolder
Now you will be able to access your files with the next path:
http://localhost:8080/DeployedProject/myfolder/filename
Steps for Jboss 7:
JBoss 7 doesn't allow any of the methods for the previous JBoss versions, so the easiest solution is to implement a Servlet to access your files like in the next link.

Categories

Resources