Retrieving a file from a Tomcat Server on an Apache box - java

So I am working on a web application with JSP on Tomcat 7. I need to be able to retrieve a log file from a few Tomcat servers saved as shared folder drives on my computer and then be able to parse it with a regex expression. However, is there anyway to retrieve the file without having to manually upload it with a form.
I tried this
public void init() throws ServletException {
// Define base path somehow. You can define it as init-param of the servlet.
this.filePath = "/Users/oakesjo/Documents/LogViewerTools";
// In a Windows environment with the Application server running on the
// c: volume, the above path is exactly the same as "c:\files".
// In UNIX, it is just straightforward "/files".
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
// Get requested file by path info.
String requestedFile = request.getPathInfo();
...}
However, the this.filePath will only let me access files on my C: drive (local computer) instead of other network drives. Is there any other way to configure this? Also: Does there exist an option of just automatically storing the file to a string?

Your applet might not have rights to where the log file is saved. When you use windows, make sure you have full acces to the folder you are trying to access. Once you got your file, you can read it via bufferedReader and make the reader put all the contents into a String.

Related

class path resource [static/pixel.png] cannot be opened because it does not exist (Heroku)

Im developing a spring boot application using Jhipster, and Im trying to add pixel to email.
The pixel image saved on resources/static folder.
My pixel link:
#GetMapping("/email-status/OPENED/{customer}")
#Timed
public void mailOpened(#PathVariable String customer, HttpServletResponse response) throws IOException {
//code...
InputStream in = new ClassPathResource("/static/pixel.png").getInputStream();
response.setContentType(MediaType.IMAGE_PNG_VALUE);
IOUtils.copy(in, response.getOutputStream());
}
The static folder explorer
When i call the api from the browser with localhost:8080/api/email-status/OPENED/...
the pixel image is displayed.
But when I call from my Domain https://app.mydomain.com/api/email-status/OPENED/123
(I'm using Heroku for hosting)
I get this error
java.io.FileNotFoundException: class path resource [static/pixel.png] cannot be opened because it does not exist
Anyone know why does this happen?
It seems to me that the localhost uses the generated classes where the domain uses the jar. In the latter case the image is inside the jar and that is why cannot be found.
As the document states for ClassPathResource:
Supports resolution as java.io.File if the class path resource resides
in the file system, but not for resources in a JAR
Maybe you should consider using
YourClassName.class.getResourceAsStream("/static/pixel.png")
A very useful link about using resources is the "How to Use Icons"
In case you deployed your app on a webserver in order to access it from your domain, it could only access the image if it is also stored on the same server.
In that case you'd have to copy the image in the appropriate folder on your server.
So I did not find any answer, The image is exists in the files, but yet couldn't use any Local path resource solution ..
I have decided to host the image and use the link instead of static image, This is my working solution
InputStream in = new URL("https://some-host/12345/pixel.png").openStream();
response.setContentType(MediaType.IMAGE_PNG_VALUE);
IOUtils.copy(in, response.getOutputStream());
And one more thing that was must for me is also, the img tag should contain all those params
<img src="image_url(the pixel image)" alt="Logo" title="Logo" style="display:block" width="1" height="1" />

Java converting Jar project to War Project

I've built a java program that logs into a game server and asks the user for an input ID and then sends a packer to the game server and parses and prints out the reply.
I need to convert this into an API that will be run on Tomcat I assume? I've installed Tomcat on my server but I am not sure what to do now and what the correct way to convert this would be.
Any help would be greatly appreciated.
I have done similar things in the past. Mainly turn regular applications into web applications. Or more simply put, wrapping an application inside a Servlet web application so it can be controlled via an HTTP API.
By the way there are multiple ways to do this. Many in fact. This is just one way. Servlets is a Java interface that allows developers to quickly create a server, mainly an HTTP server, though its not limited to just that. Tomcat is a Servlet container. That means you can create a Servlet, then register it to the Servlet container, either using a special file called a web.xml or annotations. In the example below I use the WebServlet annotation to register my Servlet with Tomcat. Once registered, Tomcat will send any requests destined to the your application (the name of the WAR file) and to the specific Servlet (the registered urlPatterns, see example below). So if your WAR file is named "MyWebServer", and your Servlet has registered the urlPattern "getSomething", then any requests to the Tomcat with the URL MyWebServer/getSomething, will be directed to your Servelet's doGet or doPost command. If you do a simple browser request (or curl on Linux) with no msg body, then by default its a HTTP GET request. Stick with GET requests for now until you get the hang of it.
A couple of things you will need.
1) Know how to package a Java application into a WAR file. The WAR file would then just go to into Tomcat's webapp folder. When Tomcat starts up it will unzip the WAR files in that directory and host the web application implemented in that WAR file. Please read up on WAR files. The easiest way to do it is to use your IDE, I prefer Netbeans, and click on new project. In Netbeans you can select new Maven->Web Application project -or- Java->Web Application. It will set up the directory structure.
2) You will need a Servlet. Create a Servet, please read up on it. Once again your IDE will make things easy for you. In Servlet 3.x you can configure your Servlet using annotations. Your Servlet will actually be a HttpServet. Here is a simple example, you will have to look up the various components (like HttpServletRequest and HttpServletResponse) to get the full blown details. Stackoverflow has a treasure trove of information on how those two work.
#WebServlet(name = "MyWebServer", urlPatterns = {"/getSomething", "/postSomething"}, loadOnStartup = 1)
public class MyWebServer extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get the input to your web service from the HttpServletRequest.
String someParam = request.getParameter("someParamName");
//process your request
String output = yourExistingClass.processSomething(someParam);
//set the response
try (PrintWriter out = response.getWriter()) {
out.println(output);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
///////////////////////////////////////////////////////////////////////////
//public functions
#Override
public void init() {
//put any code you want executed when the application comes up in here.
}
#Override
public void destroy() {
//put any code you want executed when the application comes down in here.
}
}
3) You will need to include your JAR in your application. Once again your IDE can help you add your JAR to your project. Your JAR, and any other dependency JAR's will get packaged inside your WAR, specifically inside the WEB-INF/lib folder.
I hope this helps get you started.

read upload file in play framework

I'm using play framework 2.1.0, upload files to play-app/upload folder.
then I run play 'start -Dhttp.port=80' to start server.
but when I upload a file to play-app/upload folder, it can not be access immediately.
if I stop the server and start again, then I can access the file.
How can I solve this problem? Thanks a lot.
ps, I route /upload as below:
GET /upload/*file controllers.Assets.at(path="/upload", file)
Could it be that static files are loaded once? How can I solve it?
Preferably create upload folder outside the application's folder and add it's full path like /home/navins/upload-folder/ in application.conf, then you'll be able to access it whole time, also you will be able to upload files there not only with app (ie, by FTP) without need of restarting.
I think what you need is to define a sort of Remote assets controller. Basically, once a file is uploaded, you put it in a folder that is outside your application's folder. Then, use a controller that will let you access it. Here is an example: http://www.jamesward.com/2012/08/08/edge-caching-with-play2-heroku-cloudfront
Here, James Ward creates a controller to access assets that are stored on cloudfront, what you need to do is to write a similar controller and replace the "content url" with the absolute path to your "Uploaded files directory".
finally what I've solve it by adding access method in controller:
public static Result view(String filename) {
File file = new File(Play.application().path().getAbsolutePath() + "/upload/" + filename);
return ok(file);
}
then, change route conf, you can access the files by the method.
BTW, if you are using play framework below 2.0, you may user:
renderBinary(file, ContentType);

how to create a folder in tomcat webserver using java program?

i want to know how to create a folder in webserver(tomcat 7.0) in java.
iam recently start one project.In that project i need to upload files into server from the client machine.In this each client has his own folder in server and upload the files into them.
And in each user folder we have more than two jsp files.when user request the server to show their content by an url (eg:ipaddress:portnumber/userid/index.jsp) using that files i want to show his uploaded data.
is it possible.?
please,guide me to solve this problem.
thanks.
As to your concrete question, just the same way as in a normal Java application.
File root = new File("/path/to/all/uploads");
File newfolder = new File(root, "/userid");
newfolder.mkdir();
// ...
As to your idea with those copypasted JSP files over all folders, don't do that. Just have a single servlet which is mapped on for example /files/* and reads the folder specific to the currently logged-in user and finally forwards to the JSP to present the results. Or if your intent is really to make the uploads public to everyone so that each user can see each other's uploads, then supply the desired user ID as parameter or pathinfo in the request URL like so http://localhost:8080/context/files/userid.
Please note that you shouldn't store the files in the expanded WAR folder, or they will get lost everytime you redeploy the webapp. Store them on a fixed path outside Tomcat's /webapps folder.
You access files and folders from a web application just like any other Java application: using java.io.File or maybe JDK7's new File I/O mechanism. See also the Java I/O Tutorial and the File-related utilities of Apache Commons IO.
Ok, here we go.
try {
File f = new File("file/path/name/.ext");
if(!f.isDirectory()) {
boolean success = (new File(f)).mkdirs();
}
if(success) {
System.out.println("Success")
}
} catch(Exception e) {}
That's it. I hope that functionally. Ciao

How to store a file on a server(web container) through a Java EE web application?

I have developed a Java EE web application. This application allows a user to upload a file with the help of a browser. Once the user has uploaded his file, this application first stores the uploaded file on the server (on which it is running) and then processes it.
At present, I am storing the file on the server as follows:
try {
// formFile represents the uploaded file
FormFile formFile = programForm.getTheFile();
String path = getServlet().getServletContext().getRealPath("") + "/"
+ formFile.getFileName();
System.out.println(path);
file = new File(path);
outputStream = new FileOutputStream(file);
outputStream.write(formFile.getFileData());
}
where, the formFile represents the uploaded file.
Now, the problem is that it is running fine on some servers but on some servers the getServlet().getServletContext().getRealPath("") is returning null so the final path that I am getting is null/filename and the file doesn't store on the server.
When I checked the API for ServletContext.getRealPath() method, I found the following:
public java.lang.String getRealPath(java.lang.String path)
Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext.
The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).
So, Is there any other way by which I can store files on those servers also which is returning null for getServlet().getServletContext().getRealPath("")
By spec, the only "real" path you are guaranteed to get form a servlet container is a temp directory.
You can get that via the ServletContext.gerAttribute("javax.servlet.context.tempdir"). However, these files are not visible to the web context (i.e. you can not publish a simple URL to deliver those files), and the files are not guaranteed in any way to survive a web app or server restart.
If you simply need a place to store a working file for a short time, then this will work fine for you.
If you really need a directory, you can make it a configuration parameter (either an environment variable, a Java property (i.e. java -Dyour.file.here=/tmp/files ...), a context parameter set in the web.xml, a configuration parameter stored in your database via a web form, etc.). Then it's up to the deployer to set up this directory for you.
However, if you need to actually later serve up that file, you will either need a container specific mechanism to "mount" external directories in to your web app (Glassfish as "alternate doc roots", others have similar concepts), or you will need to write a servlet/filter to serve up file store outside of your web app. This FileServlet is quite complete, and as you can see, creating your own, while not difficult, isn't trivial to do it right.
Edit:
The basic gist is the same, but rather than using "getRealPath", simply use "getInitParameter".
So:
String filePath = getServletContext().getInitParameter("storedFilePath") + "/" + fileName;
And be on your way.
Edit again:
As for the contents of the path, I'd give it an absolute path. Otherwise, you would need to KNOW where the app server sets its default path to during exeuction, and each app server may well use different directories. For example, I believe the working directory for Glassfish is the config directory of the running domain. Not a particularly obvious choice.
So, use an absolute path, most definitely. That way you KNOW where the files will go, and you can control the access permissions at the OS level for that directory, if that's necessary.
Writing to the file system from a Java EE container is not really recommended, especially if you need to process the written data:
it is not transactional
it harms the portability (what if you are in a clustered environment)
it requires to setup external parameters for the target location
If this is an option, I would store the files in database or use a JCR repository (like Jackrabbit).

Categories

Resources