Am integrating JavaMailAPI in my webapplication. I have to embed images in the html body. How do i get the images from the src/main/resource directory instead of hard code the image path.
Please find the below code that i have hard coded the image path.
try {
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("C:\\email\\logo_email.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
I want to get the images from the following code : ( src/main/resource )
ClassLoader classLoader = getClass().getClassLoader();
FileInputStream fileinputstream = new FileInputStream(new
File(classLoader.getResource("email/logo_email.png").getFile()));
I dont have idea to call fileinputstream inside DataSource
Do not use URL.getFile() as it returns the filename part of the URL...
Use URLDataSource instead of FileDataSource. Try something like this:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("email/logo_email.png");
DataSource ds = new URLDataSource(url);
Edit
In Web applications getClass().getClassLoader() might not get the correct class loader. Should use the Thread's context class loader...
Related
I have a report in jasper and want to use a logo (gif) that is inside my application (inside /src/main/resources/img)
The Code used to rettrieve the image logo is
public void imprimir(MyReport myreport) throws Exception
{
List myReportList = new ArrayList();
File logo = new File(getClass().getClassLoader().getResource("img/myLogo.gif").getPath());
myreport.setLogo(logo);
myReportList.add(myreport);
FileInputStream fis = (FileInputStream) getClass().getClassLoader().getResourceAsStream("jasper/myreport.jasper");
// JasperReport report = JasperCompileManager.compileReport(fis);
JasperPrint print = JasperFillManager.fillReport(fis, null, new JRBeanCollectionDataSource(myReportList));
JasperExportManager.exportReportToPdfFile(print, "c:/myreport.pdf");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(print, baos);
DataSource datasource = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
Email mail = new Email();
mail.setFromLabel("xxxxxxxx#xxxxxxxx.yyy.zz");
mail.setTo("destiny#xxxxxxxx.yyy.zz");
mail.setSubject("myreport");
mail.setMessage("Mesage");
EmailService emailService = new EmailService();
emailService.sendEmail(mail, datasource);
}
But this path does not exists.
[Server:server01] 09:40:12,492 ERROR [stderr] (default task-3) Caused by: java.io.FileNotFoundException: C:\Java\AS\wildfly-8.1.0.Final\content\MyProject.war\WEB-INF\classes\img\logo.gif
So, as it seems, the Path is beeing resolved to a different value.
The deployment is made over a Wildfly 8.1 Final in domain mode (Clustered).
What am I missing here?
Your myLogo.gif has been package in MyProject.war file. The path C:\Java\AS\wildfly-8.1.0.Final\content\MyProject.war\WEB-INF\classes\img\logo.gif isn't exist.
I suggest two solution to resolve this issue.
1.Move myLogo.gif out of MyProject.war. Use real path to load your gif file.
File logo = new File(realPath);
myreport.setLogo(logo);
2.Change the myreport.setLogo(logo) method's parameter type to InputStream.
InputStream logoInputStream = getClass().getClassLoader().getResourceAsStream("img/myLogo.gif");
myreport.setLogoInputStream(logoInputStream);
I have a properties file which is located under conf folder. conf folder is under the project root directory. I am using the following code.
public class PropertiesTest {
public static void main(String[] args) {
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("/conf/sampleprop.conf");
Properties prop = new Properties();
try {
prop.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(prop.getProperty("TEST"));
}
}
But I get nullpointer exception.
I have tried using
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("./conf/sampleprop.conf");
and
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("conf/sampleprop.conf");
But all result in nullpointer exception.
Can anyone please help.
Thanks in advance
Try to recover your working directory first:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working dir: " + workingDir);
and then is simple:
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(workingDir+ "/yourFilePath"));
String first= propertiesFile.getProperty("myprop.first");
Regards, fabio
The getResourceAsStream() method tries to locate and load the resource using the ClassLoader of the class it is called on. Ideally it can locate the files only the class folders .. Rather you could use FileInputStream with relative path.
EDIT
if the conf folder is under src, then you still be able to access with getResourceAsStream()
InputStream inputStream = Test.class
.getResourceAsStream("../conf/sampleprop.conf");
the path would be relative to the class from you invoke getRes.. method.
If not
try {
FileInputStream fis = new FileInputStream("conf/sampleprop.conf");
Properties prop = new Properties();
prop.load(fis);
System.out.println(prop.getProperty("TEST"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NOTE: this will only work if it is Stand alone application/in eclipse. This will not work if its web based (as the root will be Tomcat/bin, for eg)
I would suggest to copy the configuration file at designated place, then you can acess at ease. At certain extent 'System.getProperty("user.dir")' can be used if you are always copying the file 'tomcat` root or application root. But if the files to be used by external party, ideal to copy in a configurable folder (C:\appconf)
Your code works like a charm! But you might have to add the project root dir to your classpath.
If you work with Maven, place your configuration in src/main/resources/conf/sampleprop.conf
When invoking java directly add the project root dir with the java -classpath parameter. Something like:
java -classpath /my/classes/dir:/my/project/root/dir my.Main
protected void executeInternal(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Sending Birthday Wishes... ");
try
{
for(int i=0;i<maillist.length;i++)
{
Email email = new Email();
email.setFrom("spv_it#yahoo.com");
email.setSubject("Happy IndependenceDay");
email.setTo(maillist[i]);
email.setText("<font color=blue><h4>Dear Users,<br><br><br>Wish you a Happy Independence Day!<br><br><br>Regards,<br>Penna Cement Industries Limited</h4></font>");
byte[] data = null;
ClassPathResource img = new ClassPathResource("newLogo.gif");
InputStream inputStream = img.getInputStream();
data = new byte[inputStream.available()];
while((inputStream.read(data)!=-1));
Attachment attachment = new Attachment(data, "HappyBirthDay","image/gif", true);
email.addAttachment(attachment);
emailService.sendEmail(email);
}
}
catch (MessagingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is the error I'm getting:
java.io.FileNotFoundException: class path resource [newLogo.gif] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:135)
at com.mail.schedular.BirthdayWisherJob.executeInternal(BirthdayWisherJob.java:55)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:66)
at org.quartz.core.JobRunShell.run(JobRunShell.java:223)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
The best practise is to read/write or to provide reference of any file is by mentioning the ABSOLUTE PATH of that file.
To your question, It shows the FileNotFoundException because, JVM failed to locate the file in your current directory which is by default your source path. So provide the absolute path in ClassPathResource or copy that image file to your current directory. It will solve your problem.
I think you need to put your file inside inside the src folder , if it's there then check whether it's under some directory which is inside the src directory.
Then give the correct location like given details below
src[dir]----->newLogo.gif
ClassPathResource img = new ClassPathResource("newLogo.gif");
or,
src[dir]----->images[dir]---->newLogo.gif
ClassPathResource img = new ClassPathResource("/images/newLogo.gif");
You got this error since the job is running in a separate quartz thread, I suggest that you locate your file newLogo.gif outside the jar and use the following to load it.
Thread.currentThread().getContextClassLoader().getResource("classpath:image/newLogo.gif");
I am uploading file using spring MVC and jquery. Inside my class method I have written
#RequestMapping(value="attachFile", method=RequestMethod.POST)
public #ResponseBody List<FileAttachment> upload(
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpSession session) {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
//Save the file to a temporary location
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
fileName = realContextPath +"/images/"+file.getOriginalFilename();
//File dest = new File(fileName);
try {
//file.transferTo(dest);
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fileName);
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its uploading the file correctly I am using
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
to get the path. My first question is , Is this the correct way to get the path and it stores the file somewhere at
workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images
and when I am trying to display this image on my jsp page using the following code
<img src="<%=request.getRealPath("/") + "images/images.jpg" %>" alt="Upload Image" />
It does not display the image, Its generating the following html
<img src="/home/name/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images/images.jpg" alt="Upload Image">
Am I doing the things right? In my project I have to upload large number of files everyday.
Please let me know if you need anything else to understand my question
It will be better if you upload your files in some directory by absolute path(e.g. C:\images\) instead of relative (your approach). Usually, web apps runs on linux mathines on production and it is good practice to make save path configurable.
Create some application property which will holds save path for files(in xml or property file).
I'm working on a web application, and I have created a properties file in package com.xx.yy. I need to read this file from a class in author package com.aa.bb.
I have the folowing code:
try {
FileInputStream fileInputStream = new FileInputStream("com/xx/yy/myfile.properties");
internationalizationFile = new Properties();
internationalizationFile.load(fileInputStream);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
but it doesn't work!!
Have you tried to load the resource through the class loader? like:
InputStream in = this.getClass().getClassLoader.getResourceAsStream("com/xx/yy/myfile.properties");
1) I would print out the absolute path to make sure the file / resource is in the correct location.
getResourceAsStream() vs FileInputStream
2) I would use getResourceAsStream, same reference.