I want to send Files using Java Mail, I have the next code:
Here I download the file from Google Drive in InputStream.
File file = DriveHelper.getFile("oalsdiañsdluioumadsspdmaasd-asdoiasd");
InputStream inputStream = DriveHelper.downloadFile(file);
After that I write the next code:
Message message = new MimeMessage(session);
String htmlBody = "hello world"; // ...
// convert inputstream to byte[]
byte[] attachmentData = IOUtils.toByteArray(inputStream);
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlBody, "text/html");
mp.addBodyPart(htmlPart);
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName("archivo.pdf");
attachment.setContent(attachmentData, "application/pdf");
mp.addBodyPart(attachment);
message.setContent(mp);
Transport.send(message);
But when I run the code I have next Exception:
javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Converting attachment data failed)
[INFO] at javax.mail.Transport.send(Transport.java:163)
[INFO] at javax.mail.Transport.send(Transport.java:48)
attachment.setContent() does not work properly.
You can use DataSource:
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName("archivo.pdf");
DataSource dataSource = new ByteArrayDataSource(inputStream, "application/pdf");
attachment.setDataHandler(new DataHandler(dataSource));
mp.addBodyPart(attachment);
I found a solution in this link: http://www.programcreek.com/java-api-examples/index.php?api=com.google.appengine.api.mail.MailService, and solved my problem.
Related
This is selenium code using apache Poi where I am reading a file value from excel and opening a link while writing a string value in excel file its giving me null point exception. can you tell me what is wrong ?
on last line I am getting errors, the lines are:-
sheet1.getRow(i).getCell(2).setCellValue(linkLocatin);
File src = new File ("C:\\Sandeep\\Selenium\\automationproject1\\Testdata.xlsx");
My all code:-
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb =new XSSFWorkbook (fis);
XSSFSheet sheet1 =wb.getSheetAt(0);
int rowcount= sheet1.getLastRowNum();
XSSFCell cel;
//System.out.println ("Test data is " + data0);
System.out.println ("rowncount is = "+ rowcount);
for (int i=1; i<= rowcount;i++)
{
//Set browser profile and then get link from excel
FirefoxProfile prof = new FirefoxProfile();
prof.setPreference("media.windows-media-foundation.enabled", false);
prof.setPreference("media.directshow.enabled", false);
prof.setAcceptUntrustedCertificates(true);
prof.setPreference("browser.download.dir","C:\\Sandeep\\Selenium\\automationproject1\\Download1");
prof.setPreference("browser.helperApps.alwaysAsk.force", false);
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "audio/x-mpeg-3");
prof.setPreference("browser.download.folderList", 2);
prof.setPreference("browser.download.manager.showWhenStarting",false);
WebDriver driver = new FirefoxDriver(prof);
String data0 = sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println(data0);
// open the link in browser
driver.get(data0);
WebElement link = driver.findElement(By.linkText("Download the recording"));
String linkLocatin = link.getAttribute("href");
sheet1.getRow(i).getCell(2).setCellValue(linkLocatin);
While setting up string value in excel it's showing null point exception ..W
Now I'm trying to convert Java List object to JSON array, and struggling to convert UTF-8 strings. I've tried all followings, but none of them works.
Settings.
response.setContentType("application/json");
PrintWriter out = response.getWriter();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
final ObjectMapper mapper = new ObjectMapper();
Test#1.
// Using writeValueAsString
String json = ow.writeValueAsString(list2);
Test#2.
// Using Bytes
final byte[] data = mapper.writeValueAsBytes(list2);
String json = new String(data, "UTF-8");
Test#3.
// Using ByteArrayOutputStream with new String()
final OutputStream os = new ByteArrayOutputStream();
mapper.writeValue(os, list2);
final byte[] data = ((ByteArrayOutputStream) os).toByteArray();
String json = new String(data, "UTF-8");
Test#4.
// Using ByteArrayOutputStream
final OutputStream os = new ByteArrayOutputStream();
mapper.writeValue(os, list2);
String json = ((ByteArrayOutputStream) os).toString("UTF-8");
Test#5.
// Using writeValueAsString
String json = mapper.writeValueAsString(list2);
Test#6.
// Using writeValue
mapper.writeValue(out, list2);
Like I said, none of above works. All displays characters like "???". I appreciate your helps. I'm using Servlet to send JSON response to clients.
This problem only happens when I write java.util.List object. If I write single data object, e.g. customer object in below example, then there is no ??? characters, and UTF-8 is working with the following code.
PrintWriter out = response.getWriter();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(customer);
out.print(json);
The answer was very simple. You need to specify UTF-8 charset encoding in response.setContentType too.
response.setContentType("application/json;charset=UTF-8");
Then, many of above code will work correctly. I will leave my question as is, since it will show you several ways of writing JSON to clients.
On RequestMapping in Controller:
#RequestMapping(value = "/user/get/sth",
method = RequestMethod.GET,
produces = { "application/json;**charset=UTF-8**" })
I am using Java on Google App Engine and trying to send an email with multiple attachments.
What I am finding is that it is for some reason missing off the first attachment.
Basically if filesToAttach contains 1 file, then there will be no attachments.
If filesToAttach contains 4 files - A, B, C and D, then the message that comes through will have B, C and D attached. Really bizarre.
The code I am using is as below. Any suggestions as to how to rectify this greatly appreciated.
The output that the log.info calls generate appears to show the correct number of files have been attached.
Properties props = new Properties();
Session session = Session.getInstance(props);
Message message = new MimeMessage(session);
String fromEmail = "admin#" + ApiProxy.getCurrentEnvironment().getAppId() + ".appspotmail.com";
message.setFrom(new InternetAddress(fromEmail, "MyApp Admin"));
message.addRecipients(Message.RecipientType.BCC, addresses);
message.setSubject(subject);
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlBody, "text/html");
multipart.addBodyPart(htmlPart);
for(FileToAttach fileToAttach : filesToAttach) {
MimeBodyPart fileMimeBodyPart = new MimeBodyPart();
DataSource dataSource = new ByteArrayDataSource(fileToAttach.getContents(), "application/octet-stream");
fileMimeBodyPart.setDataHandler(new DataHandler(dataSource));
fileMimeBodyPart.setFileName(fileToAttach.getFileName());
log.info("attaching file " + fileToAttach.getFileName() + " of " + fileToAttach.getContents().length + " bytes");
multipart.addBodyPart(fileMimeBodyPart);
}
message.setContent(multipart);
log.info("the multipart contains " + multipart.getCount() + " parts and isComplete = " + multipart.isComplete());
Transport.send(message);
log.info("called Transport.send");
I need to save a uploaded file in sub directory of Document & Media folder in liferay from web-form portlet.
I have extended the web Form portlet to do so, but file is getting uploaded successfully in database & not in Document & Media folder.
I tried following code to upload the file in document directory but no success please help .
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
String title = file.getName();
DLFolder dlFolder = DLFolderLocalServiceUtil.getFolder(themeDisplay.getScopeGroupId(), 0, "Test");
ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(),actionRequest);
Map<String, Fields> fieldsMap = new HashMap<String, Fields>();
long fileEntryTypeId = DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_BASIC_DOCUMENT;
FileInputStream inputStream = new FileInputStream(file);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(themeDisplay.getUserId(), 10153, dlFolder.getRepositoryId(),
dlFolder.getRepositoryId(), title, file.getContentType(), title, "fileDesc", "sss",
fileEntryTypeId, fieldsMap, file, inputStream, file.length(), serviceContext);
inputStream.close();
DLFileEntryLocalServiceUtil.updateFileEntry(themeDisplay.getUserId(), dlFileEntry.getFileEntryId(), title, file.getContentType(),
title, "fileDesc", "comment", true, dlFileEntry.getFileEntryTypeId(), fieldsMap, file, null, file.length(), serviceContext);
Try this code snippet
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
File file = uploadRequest.getFile("file");
String contentType = MimeTypesUtil.getContentType(file);
InputStream inputStream = new FileInputStream(file);
Folder folderName = DLAppLocalServiceUtil.getFolder(parentRepositoryId,
parentFolderId,
"Folder Name");
long folderId = folderName.getFolderId();
long repositoryId = folderName.getRepositoryId();
FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
repositoryId,
folderId,
file.getName(),
contentType,
"File Name",
"description",
"changeLog",
inputStream,
file.length(),
serviceContext);
I know it's an old question, but I had similar issue today. I used DLFileEntryLocalServiceUtil, and I had to call both addFileEntry() and updateFileEntry() in order to correctly create the asset.
See Liferay DLFileEntryLocalServiceUtil.addFileEntry does not create AssetEntry record
I'm using the bing api to request some results.. when I run my code the response string is truncated so that its missing the first 10-50 characters.. when I paste the exact same request in the browser it returns the results just fine..
Here is my code.. what am I doing wrong?
string AppId = "My APP ID HERE :O ";
string url = "http://api.search.live.net/xml.aspx?Appid={0}&sources={1}&query={2}";
string completeUri = String.Format(url, AppId, "web", validateforweb(Artist) + "%20" + validateforweb(Song) + "%20" + "Lyrics");
HttpWebRequest webRequest = null;
webRequest = (HttpWebRequest)WebRequest.Create(completeUri);
HttpWebResponse webResponse = null;
webResponse = (HttpWebResponse)webRequest.GetResponse();
XmlReader xmlReader = null;
Stream s = webResponse.GetResponseStream();
xmlReader = XmlReader.Create(s);
StreamReader reader;
reader = new StreamReader(s);
string str = reader.ReadToEnd();
I suspect it's related to the fact you're creating 2 readers on the stream (XmlReader and StreamReader). The XmlReader starts buffering data from the stream as soon as you create it, so when the StreamReader starts reading from the same stream, it misses the part of the data that has been buffered by the XmlReader.
You can't use 2 readers on the same stream, they will conflict with each other.