Get image path in non-servlet - java

I have a scheduled task running in JBoss 5.1 on a daily basis for sending birthday wishes.
The mail content is HTML and I embed images in the mail.
Now I would like to get the path of that image for embedding, how would it be possible to get path of image in a non-servelt environment.
Ofcourse I could have placed the images at a static location and accessed them, for which I don't want to hardcode the path.
The image is at "WebContent/images/birthday.jpg" location.

How are you generating the email content? Are these also static html files?
If you are going to use simple static html files, you will have to hard code the image paths. There is no other way around it.
You could write a simple Java application, which runs as a standalone application (without any servers,servlets etc), which will create the email content.
The java code can send out the emails for you too if you want.
These are some of the things you can do, if you use java
Use property files to specify the location of images. These are files which hold simple key/value pairs.
You can easily create multiple email content to different users, with the same template.
You will be able to easily redesign the html content for multiple users.
An example of using property files.
Create a file ex: "email_template.properties"
Enter the following into the file and save it.
image_server=http://www.mywebsite.com
image_folder=/WebContent/images/
Create a jave program to create your html email, and use the property file to generate the image locations.
Properties properties = new Properties();
try
{
properties.load(new FileInputStream("C://email_template.properties")); //specify path here
String sServerLocation = properties.getProperty("image_server");
String sImageFolder = properties.getProperty("image_folder");
StringBuilder strEmail = new StringBuilder();
strEmail.append("<html><body> <img src=\"" + sServerLocation + sImageFolder +"birthday.jsp\""> </body> </html>" );
// Write code to generate complete email dynamically
// write code to send out the email or to save as html file to you machine, where you can send it manually.
} catch (IOException e)
{
//
}
You get the idea. using plain html you will have to hard code.
However if you use a simple java file you can get more flexibility.
If you need code to send out email from java, check this link out.
How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Related

FileWriter to write to user desktop in Java, rather than server desktop

As part of a search application, I want the user to be able to download a report showing the results in a CSV file. I have the following method:
public void downloadCustomerResults(String customer) {
String output = "";
output += produceCustomerID(customer);
output += produceCustomerAddress(customer);
output += produceCustomerContactDetails(customer);
output += produceOrderHeader(customer);
output += producePayments(customer);
// Writes to server desktop, not user desktop.
try {
Writer fileWriter = new FileWriter("C:\\Users\\username\\Desktop\\SAR" + customer + "C.csv");
fileWriter.write(output);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This downloads the file to the desktop of the machine running the server, not the user's desktop (accessing the app via JSP's on Tomcat). How would I change the file path string to make this download to the users' desktop? Or would I have to pass the file to the JSP for the user to download via their browser?
Thanks.
Short answer: The server has no means of accessing the client's filesystem.
Longer answer: You might either provide a service for the client to download the file (e.g. a webservice accessible through a URI, like #Kayaman mentioned) or the client provides you a service to write the file (e.g. a remote file system, an FTP server etc.). For the latter there might be libraries providing a special java.nio.FileSystem extension.
You may also provide an application running on the client to receive the file. This client application will then have acces to the client's file systems (unless it lacks the access rights, of course).
So the answer I found was to use the JavaScript package FileSaver.js.
This accepts a blob created from a string, and then saves it with a filename of your choice to the browsers preferred download folder.
I managed to pass the string from Java to JavaScript, and then pass it through FileSaver.js in the .JSP page.

Selenium - Java - How to implement XML variables

I am setting up a Selenium automated testing system written in Java.
I have the following structure:
src/
modules/
LoginForm
browsers/
Chrome
Firefox
This application has to be able to test multiple websites with different username and passwords etc..
I do not want to have to go into each of the classes in order to change the parameters (e.g. if we have to change the website and/or the username and password). I'm therefore wondering if it's possible to have an XML file that we can store all of these values in that then can be read at run time?
What you need to do is create a file with all the parameters and load them at run time. Then you can pick each value within the loop: For example
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
line=scanner.nextLine();
//Split the line to get the variables
//pass variables to selenium object at each line:
}
}
That way you will be able to get the job done
There are several frameworks to read XML files. You can create a XML file as follows and read it.
You may also use a properties file
data.properties
A scanner also works fine. So, now you have many options. Go do it. :)

Struts2: How to store images outside of the webapp and save its path to the db?

Until now I did saving image into the webapp directory and its path into database.
But now am trying to save the image outside of the webapp so that if I deploy my new war files then my old files folder will not be deleted.
From my below code my image file is correctly saving into the specified folder outside of the webapp but i don't know how to retrieve that image into my jsp page.
I tried like this
<img src="www.myproject.com/struts2project/files/smile.jpg/>"
but this is wrong. I am not getting my image to be display into my jsp page.
Below code is working fine for uploading image into absolute path but my problem is how to retrieve that image?
`fileSystemPath= "/files";
try{
File destFile = new File(fileSystemPath, thempicFileName);
FileUtils.copyFile(thempic, destFile);
String path=fileSystemPath+"/"+thempicFileName;
theme=dao.getThemeById(themId);
theme.setThemeScreenshot(path);
theme.setThemeName(theme.getThemeName());
theme.setThemeCaption(theme.getThemeCaption());
dao.saveOrUpdateTheme(theme);
}catch(IOException e){
e.printStackTrace();
return INPUT;
}`
Kindly help me...
I hope I'm being clear on what I need, let me know if I am not and I'll try to explain in another way.
As you say . . . this question describes what you need to do. I guess what you need to know is how to best achieve this with struts 2. Here's what's going on.
In your tag:
That url is being routed to your struts 2 application. Correct? The context is "struts2project".
One of the solutions offered by the referenced question is to use Tomcat's ability to serve static requests and configure tomcat to know about this other document root that holds your images. I think this is a great solution.
If you want to keep it inside of struts2, I think you're best option is to use a dedicated "image streaming from that other place" action that get's an InputStream to the image, then uses the Struts2 Stream Result result type. That result type lets you specify an adhoc InputStream. It also helps you set the appropriate headers. Note, the header values on that documentation page are for downloading the file, so you don't want those values. They would force the browser to open a save as dialog for the image, I think.
You are already using absolute paths, just use a location outside of your web application:
String destinationDir = "/path/to/my/directory/";
File file = new File(destinationDir + item.getName());

Why doesn't the CSV file in my applet work?

I created an applet that requires a CSV file for information. The way the applet works, is that there is a text field in which you type in your zip code, then you press a button. That causes the program to parse through the CSV file which contains a latitude and longitude, then display the latitude and longitude on a JLabel in the applet.
When I created it, I debugged it and tested it, so I know it works on my desktop (when running in eclipse). The problem is when I put in on the web, it displays but can't do anything, meaning it is just an applet with a text field and a button, but when you press the button, nothing happens. I know that it is not my ActionListener, because it works on the desktop, but I must be doing something wrong with the HTML of it. The name of the CSV file is zips.csv. The name of the main class is main.class (or main.java) and the action listener is myActionListener.class (or myActionListener.java).
Here is the HTML that I am using for it right now:
<applet archive="sites/default/files/myApplet.jar" code="main.class" width="500" height="200">
</applet>
Revision:
Romething else that someone recommended to me was to create a php script that will parse the csv file, and than have that return a value to the java applet. My knowledge of PHP ls limited, so I was wonder if someone could tell me how I could go about doing this, or telling me where I can learn how to do this.
CsvReader products = new CsvReader("zips.csv");
My crystal ball tells me that CsvReader presumes the String to represent a File object. It might also have another constructor that accepts an URL.
A sand-boxed applet cannot access File objects, and a trusted applet can only access File objects on the computer of the end user. That is useless to this applet. If the API has a constructor that accepts an URL, that is the one to use here. Something like:
URL url = this.getClass().getResource("zips.csv");
//CsvReader products = new CsvReader(url);
InputStream is = url.openStream();
CsvReader products = new CsvReader(is);
A constructor that accepts an InputStream is even more versatile, and only a line longer.
If the CsvReader accepts neither of URL or InputStream, I suggest you find another API. One that was not written by amateurs.

How to upload a directory via Grails or Java?

What is the best way to upload a directory in grails ?
I try this code :
def upload = {
if(request.method == 'POST') {
Iterator itr = request.getFileNames();
while(itr.hasNext()) {
MultipartFile file = request.getFile(itr.next());
File destination = new File(file.getOriginalFilename())
if (!file.isEmpty()) {
file.transferTo(destination)
// success
}
else
{
// failure
}
}
response.sendError(200,'Done');
}
}
Unfortunately, I can only upload file by file.
I would like to define my directory, and upload all files directly.
Any ideas ?
There is one major misconception here. The code which you posted will only work if both the server and the client runs at physically the same machine (which won't occur in real world) and if you're using the MSIE browser which has the misbehaviour to send the full path along the filename.
You should in fact get the contents of the uploaded file as an InputStream and write it to any OutputStream the usual Java IO way. The filename can be used to create a file with the same name at the server side, but you'll ensure that you strip the incorrectly by MSIE sent path from the filename.
As to your actual functional requirement, HTML doesn't provide facilities to upload complete directories or multiple files by a single <input type="file"> element. You'll need to create a client application which is capable of this and serve this from your webpage, like a Java Applet using Swing JFileChooser. There exist 3rd party solutions for this, like JumpLoader.

Categories