How can I e-mail a .csv file in Codename One? - codenameone

In my app, I create a file with a comma-separated array by writing to an OutputStream. Then I want to be able to share this by e-mail so a user can get the data. This is the code I use to create the file:
public String getLogFile(String logName) {
String path = FileSystemStorage.getInstance().getAppHomePath() + "exp " + logName + ".csv";
Set<Long> keys;
OutputStream os = null;
try {
os = FileSystemStorage.getInstance().openOutputStream(path);
Hashtable<Long, Integer> log = (Hashtable<Long, Integer>) dataStorage
.readObject(logName);
keys = log.keySet();
for (Long key : keys) {
String outString = (key + "," + log.get(key) + "\n");
System.out.println(outString);
byte[] buffer = outString.getBytes();
os.write(buffer);
}
} catch (IOException e) {
AnalyticsService.sendCrashReport(e, "Error writing log", false);
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return path;
}
Then, I've created a button that when pressed passes the path of the file to share. I've tried to use MIME types such as "text/plain" and "text/comma-separated-values", but that causes errors. Here is the code executed when the button is pressed.
public void exportLog(String logName) {
String path = dataBuffer.getLogFile(logName);
EmailShare email = new EmailShare();
// email.share("Here is your log.", path, "text/plain");
email.share("Here is your log.", path, "text/comma-separated-values");
}
When pressed (in the simulator). I get this stack after selecting the dummy e-mail contact to send to:
java.lang.NullPointerException
at com.codename1.impl.javase.JavaSEPort.scale(JavaSEPort.java:3483)
at com.codename1.ui.Image.scale(Image.java:963)
at com.codename1.ui.Image.scaledImpl(Image.java:933)
at com.codename1.ui.Image.scaled(Image.java:898)
at com.codename1.impl.javase.JavaSEPort$60.save(JavaSEPort.java:6693)
at com.codename1.share.ShareForm.<init>(ShareForm.java:75)
at com.codename1.share.EmailShare$1$2$1.actionPerformed(EmailShare.java:102)
at com.codename1.ui.util.EventDispatcher.fireActionSync(EventDispatcher.java:455)
at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:358)
at com.codename1.ui.List.fireActionEvent(List.java:1532)
at com.codename1.ui.List.pointerReleasedImpl(List.java:2011)
at com.codename1.ui.List.pointerReleased(List.java:2021)
at com.codename1.ui.Form.pointerReleased(Form.java:2560)
at com.codename1.ui.Component.pointerReleased(Component.java:3108)
at com.codename1.ui.Display.handleEvent(Display.java:2017)
at com.codename1.ui.Display.edtLoopImpl(Display.java:1065)
at com.codename1.ui.Display.mainEDTLoop(Display.java:994)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

The EmailShare class expects a path to an image file not an arbitrary file as its second argument so loading that fails.
The Message class is better suited for that indeed. You can also use the cloud send option which won't launch the native email app. E.g. the Log class includes that ability directly thru the Log.sendLog API.

It looks like the Messages class is better suited for this task, and should allow attachments, etc.

Related

Reading Hadoop sequence file in Flink

How to read Hadoop sequence file in Flink? I hit multiple issues with the approach below.
I have:
DataSource<String> source = env.readFile(new SequenceFileInputFormat(config), filePath);
and
public static class SequenceFileInputFormat extends FileInputFormat<String> {
...
#Override
public void setFilePath(String filePath) {
org.apache.hadoop.conf.Configuration config = HadoopUtils.getHadoopConfiguration(configuration);
logger.info("Initializing:"+filePath);
org.apache.hadoop.fs.Path hadoopPath = new org.apache.hadoop.fs.Path(filePath);
try {
reader = new SequenceFile.Reader(hadoopPath.getFileSystem(config), hadoopPath, config);
key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), config);
value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), config);
} catch (IOException e) {
logger.error("sequence file creation failed.", e);
}
}
}
One of the issues: Could not read the user code wrapper: SequenceFileInputFormat.
Once you get an InputFormat, you can call ExecutionEnvironment.createInput(<input format>) to create your DataSource.
For SequenceFiles, the type of the data is always Tuple2<key, value>, so you have to use a map function to convert to whatever type you're trying to read.
I use this code to read a SequenceFile that contains Cascading Tuples...
Job job = Job.getInstance();
FileInputFormat.addInputPath(job, new Path(directory));
env.createInput(HadoopInputs.createHadoopInput(new SequenceFileInputFormat<Tuple, Tuple>(), Tuple.class, Tuple.class, job);

Selenium-Extent_Reports: Not able to view the failure screenshots on other Computer/Machine

-Failure Screenshot are visible in Extent_Reports on my local machine. But not able to view the failure screenshot in Extent_Reports on other Computer/Machine.
-When i trigger build from Jenkins, After build successful, Sending email to:Recipient List
To Capture Screenshot
public String captureScreen(String fileName) {
if(fileName =="") {
fileName="Screenshot"; }
File destFile=null;
Calendar calendar =Calendar.getInstance() ;
SimpleDateFormat formater= new SimpleDateFormat("dd_MM_yyy_hh_mm_ss");
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
String reportDirectory = "/src/main/java/com/test/automation/Demo/screenshot/";
//String reportDirectory= new File(System.getProperty("user.dir")).getAbsolutePath()+"./src/main/java/com/test/automation/Demo/screenshot/";
destFile= new File((String)reportDirectory + fileName +"-" + formater.format(calendar.getTime())+ ".png");
FileUtils.copyFile(srcFile,destFile );
//This will help us to link screen shot in Extent report
Reporter.log("<a href='"+destFile+ "'><img src='" +destFile+"' height='100' width='100'/></a>");
//Reporter.log("<a href='"+destFile.getAbsolutePath()+ "'><img src='" +destFile.getAbsolutePath()+"' height='100' width='100'/></a>");
}
catch(IOException e) {
e.printStackTrace();
}
return destFile.toString();
}
For generating Extent reports with screenshots for Failure test cases
public void getresult(ITestResult result) {
if(result.getStatus()==ITestResult.FAILURE)
{
test.log(LogStatus.ERROR, result.getName()+" Test case FAILED due to below issues: "+result.getThrowable());
String screen = captureScreen("");
test.log(LogStatus.FAIL," Failure Screenshot : "+ test.addScreenCapture(screen));
}}
If You're using remoteWebDriver than it must be augmented before you can use the screenshot capability. Did You try to
WebDriver driver = new RemoteWebDriver();
driver = new Augmenter().augment(driver);
// or for mobile driver
androidDriver.setFileDetector(new LocalFileDetector());
//this is needed when using remoteDriver
Here is how I take screenshot for ExtentReport
File scrFile = driver.getScreenshotAs(OutputType.FILE);
String dest = System.getProperty("user.dir") + "/resources/screenshots/" + dataMethod.getAndroidDriver().getSessionId() + ".png";
File destination = new File(dest);
try {
FileUtils.copyFile(scrFile, destination);
// this is just utility which takes screenshot and copy it to desired destination
dataMethod.setScreenshotPath(destination.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
And on code failure:
#Override
public synchronized void onTestFailure(ITestResult result) {
setTestEndTime(result);
ExtentTest extentTest = methodData.getExtentTest();
extentTest.addScreenCaptureFromPath(methodData.getScreenshotPath());
}
Hope this will help.
I didn't used Extent reports, i have my own implementation for reports. But i am expecting is there is issue with src
<img src='" +destFile+"' height='100' width='100'/></a>");
Here, destFile brings location of image or screenshot which is related to your machine. the same should not be works for others. We have to use relative path, see this
https://www.w3schools.com/html/html_filepaths.asp
And also make sure that when sharing reports, it should contains all requires files and folders also.
Normally, the issue happens as the local files are not allowed to be loaded. So even we put relative or absolute path, that seems not work for many cases.
So I try to take base64screenshot instead, and it displays quite good in Extent Report.
To have the screenshot in folder report, just need to take screenshot as usual.
public static String getBase64Screenshot(WebDriver driver, String screenshotName) throws IOException {
String encodedBase64 = null;
FileInputStream fileInputStream = null;
TakesScreenshot screenshot = (TakesScreenshot) driver;
File source = screenshot.getScreenshotAs(OutputType.FILE);
String destination = windowsPath + "\\FailedTestsScreenshots\\"+screenshotName+timeStamp+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
try {
fileInputStream =new FileInputStream(finalDestination);
byte[] bytes =new byte[(int)finalDestination.length()];
fileInputStream.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
}catch (FileNotFoundException e){
e.printStackTrace();
}
return encodedBase64;
}
Call it in failure cases:
public synchronized void onTestFailure(ITestResult result) {
System.out.println("==="+methodDes + "=== failed!");
try {
WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver");
String base64Screenshot = ExtentManager.getBase64Screenshot(driver, result.getName());
MediaEntityModelProvider mediaModel = MediaEntityBuilder.createScreenCaptureFromBase64String(base64Screenshot).build();
test.get().fail("image:", mediaModel);
} catch (IOException e) {
e.printStackTrace();
}
test.get().fail(result.getThrowable().getMessage());
}

JavaMail MimeBodyPart.SaveFile provide corrupted files

I'm using JavaMail Library to parser email mime message.
I'm trying to extract the attached files and save them to the local disk but the saved files are not valid and their size is different from the original. only *.txt file are saved ok but *.PDF or *.xlsx are not.
Can you please help me to fix the code?
My code is:
private static void Test3() {
String email_string = File_Reader.Read_File_To_String("D:\\8.txt");
MimeMessage mm = Email_Parser.Get_MIME_Message_From_Email_String(email_string);
Email_Parser.Save_Email_Attachments_To_Folder(mm,"D:\\TEST");
}
public static String Read_File_To_String(String file_path) {
byte[] encoded = new byte[0];
try {
encoded = Files.readAllBytes(Paths.get(file_path));
} catch (IOException exception) {
Print_To_Console(exception.getMessage(), true,false);
}
return new String(encoded, m_encoding);
}
public static MimeMessage Get_MIME_Message_From_Email_String(String email_string) {
MimeMessage mm = null;
try {
Session s = Session.getDefaultInstance(new Properties());
InputStream is = new ByteArrayInputStream(email_string.getBytes());
mm = new MimeMessage(s, is);
} catch (MessagingException exception) {
Print_To_Console(exception.getMessage(), true, false);
}
return mm;
}
public static void Save_Email_Attachments_To_Folder(MimeMessage mm, String output_folder_path) {
ArrayList<Pair<String, InputStream>> attachments_InputStreams = Get_Attachments_InputStream_From_MimeMessage(mm);
String attachment_filename;
String attachment_filename_save_path;
InputStream attachment_InputStream;
MimeBodyPart mbp;
for (Pair<String, InputStream> attachments_InputStream : attachments_InputStreams) {
attachment_filename = attachments_InputStream.getKey();
attachment_filename = Get_Encoded_String(attachment_filename);
attachment_filename_save_path = String.format("%s\\%s", output_folder_path, attachment_filename);
attachment_InputStream = attachments_InputStream.getValue();
try {
mbp = new MimeBodyPart(attachment_InputStream);
mbp.saveFile(attachment_filename_save_path);
} catch (MessagingException | IOException exception) {
Print_To_Console(exception.getMessage(), true, false);
}
}
}
You're doing something very strange in Save_Email_Attachments_To_Folder. (Not to mention the strange naming convention using both camel case and underscores. :-)) I don't know what the InputStreams are you're collecting, but constructing new MimeBodyParts based on them and then using the new MimeBodyPart to save the attachment to the file is almost certainly not what you want to do.
What exactly is Get_Attachments_InputStream_From_MimeMessage doing? Why iterate over the message to collect a bunch of InputStreams, then iterate over the InputStreams to save them? Why not iterate over the message to find the attachments and save them as you find them using the MimeBodyPart.saveFile method? Have you seen the msgshow.java sample program?

Download a file through the WebBrowser control

I have a WebBrowser control on a form, but for the most part it remains hidden from the user. It is there to handle a series of login and other tasks. I have to use this control because there is a ton of Javascript that handles the login. (i.e., I can't just switch to a WebClient object.)
After hopping around a bit, we end up wanting to download a PDF file. But instead of downloading, the file is displayed within the webBrowser control, which the user can not see.
How can I download the PDF instead of having it load in the browser control?
Add a SaveFileDialog control to your form, then add the following code on your WebBrowser's Navigating event:
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (e.Url.Segments[e.Url.Segments.Length - 1].EndsWith(".pdf"))
{
e.Cancel = true;
string filepath = null;
saveFileDialog1.FileName = e.Url.Segments[e.Url.Segments.Length - 1];
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filepath = saveFileDialog1.FileName;
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(e.Url, filepath);
}
}
}
//Callback function
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("File downloaded");
}
Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d338a2c8-96df-4cb0-b8be-c5fbdd7c9202
The solution I ended up using:
I did everything else as-needed to get the URL where it needed to go. Knowing that all of the login information, required settings, viewstates, etc. were stored in the cookies, I was finally able to grab the file using a hybrid of the web control to navigate then the WebClient object to actually snag the file bytes.
public byte[] GetPDF(string keyValue)
{
DoLogin();
// Ask the source to generate the PDF. The PDF doesn't
// exist on the server until you have visited this page
// at least ONCE. The PDF exists for five minutes after
// the visit, so you have to snag it pretty quick.
LoadUrl(string.Format(
"https://www.theMagicSource.com/getimage.do?&key={0}&imageoutputformat=PDF",
keyValue));
// Now that we're logged in (not shown here), and
// (hopefully) at the right location, snag the cookies.
// We can use them to download the PDF directly.
string cookies = GetCookies();
byte[] fileBytes = null;
try
{
// We are fully logged in, and by now, the PDF should
// be generated. GO GET IT!
WebClient wc = new WebClient();
wc.Headers.Add("Cookie: " + cookies);
string tmpFile = Path.GetTempFileName();
wc.DownloadFile(string.Format(
"https://www.theMagicSource.com/document?id={0}_final.PDF",
keyValue), tmpFile);
fileBytes = File.ReadAllBytes(tmpFile);
File.Delete(tmpFile);
}
catch (Exception ex)
{
// If we can't get the PDF here, then just ignore the error and return null.
throw new WebScrapePDFException(
"Could not find the specified file.", ex);
}
return fileBytes;
}
private void LoadUrl(string url)
{
InternalBrowser.Navigate(url);
// Let the browser control do what it needs to do to start
// processing the page.
Thread.Sleep(100);
// If EITHER we can't continue OR
// the web browser has not been idle for 10 consecutive seconds yet,
// then wait some more.
// ...
// ... Some stuff here to make sure the page is fully loaded and ready.
// ... Removed to reduce complexity, but you get the idea.
// ...
}
private string GetCookies()
{
if (InternalBrowser.InvokeRequired)
{
return (string)InternalBrowser.Invoke(new Func<string>(() => GetCookies()));
}
else
{
return InternalBrowser.Document.Cookie;
}
}
bool documentCompleted = false;
string getInnerText(string url)
{
documentCompleted = false;
web.Navigate(url);
while (!documentCompleted)
Application.DoEvents();
return web.Document.Body.InnerText;
}
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
documentCompleted = true;
}

Javamail Auto-reply for my domain

Javamail Auto-reply
I would truly like to auto-reply to an email using Javamail.
I already use my domain email to send a confirmation code during registration.
What I need now is when an email is sent to choices#mydomain.com I can auto-reply with a canned email based on parsing out and reading the received email. It would be nice to include the username in the reply.
Thank you for your help!
This simplest approach is to write a program that monitors your mailbox and creates and sends a reply based on every message it sees. The JavaMail download bundle includes a sample program monitor.java that will get you started. The MimeMessage.reply method will be helpful. You'll have to fill in the content of the reply message yourself. Various other JavaMail sample programs will show you how to send a message once you've created it.
And don't forget to read the JavaMail FAQ.
Nice thinking John,I had the same problem in my project, in JSP and I solved it as shown below with java class as ReadingMail
package com;import java.io.*;import java.util.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
public class ReadingMail {
public static void main(String args[]) throws Exception {
try{
String host = "pop.gmail.com";
String user="username";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public String Manu()
{
String email=null;
try{
String host = "pop.gmail.com";
// String user = "xyz";
// String password = "12345";
String user="username#gmail.com";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
// System.out.println("SentDate : " + message[i].getSentDate());
//System.out.println("From : " + message[i].getFrom()[0]);
email=message[i].getFrom()[0]==null?null:((InternetAddress) message[i].getFrom()[0]).getAddress();
System.out.println("From addrss is..........................."+email);
// System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
return email;
}
You can fetch the username from the database and provide it as message in this program.

Resources