How to read emails from outlook [closed] - api

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
recently I started a task to retrieve the emails on the exchange server using javamail API. However, sometimes I can not fetch any mails because outlook client synchronises with the mail server and those emails are therefore removed from the server.
Is there any way to ensure that I can fetch all new emails no matter before or after outlook synchronization. Or I should try to connect to outlook, if so, is there any available free API? Thank you.

Isn't is possible to configure outlook to leave a copy of the messages on the server? I really do not think connection to outlook is the way to go.

I have the solution to read emails from outlook.
We need to give username, password, domain and exchange address: https://webmail.**companynameXYZ**.com/ews/exchange.asmx.
following is the code .... I have used this from some purpose, to download attachments from undread mails and making it as read after downloading.
NOTE: we need DLL Microsoft.Exchange.WebServices.dll to be downloaded
CODE in C#:
string _username = string.Empty;
string _password = string.Empty;
string _domain = "us";
string _exchange = string.Empty;
_username = ConfigurationSettings.AppSettings["Username"].ToString();
_password = ConfigurationSettings.AppSettings["Pasword"].ToString();
_exchange = ConfigurationSettings.AppSettings["MailServer"].ToString();
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
// service.AutodiscoverUrl("maxdatafeeds#maritz.com");
service.Url = new Uri(_exchange);
service.Credentials = new WebCredentials(_username, _password, _domain);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
int attachmentCount = 0;
foreach (Item item in findResults.Items)
{
// Bind to an existing message item, requesting its Id property plus its attachments collection.
EmailMessage message = EmailMessage.Bind(service, item.Id);
//read only unread mails and has attachemnts to it.
if ((!message.IsRead) && message.HasAttachments )
{
Console.WriteLine(item.Subject);
#region Iterate through the attachments collection and load each attachment.
foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
attachmentCount++;
// Load the file attachment into memory and print out its file name.
fileAttachment.Load();
Console.WriteLine("Attachment name: " + fileAttachment.Name);
//create Attachments-folder if not exists.
if (!Directory.Exists(#"C:\Attachments\"))
{
Directory.CreateDirectory(#"C:\Attachments\");
}
// Load attachment contents into a file.
fileAttachment.Load("C:\\attachments\\" + fileAttachment.Name);
}
else // Attachment is an item attachment.
{
// Load attachment into memory and write out the subject.
ItemAttachment itemAttachment = attachment as ItemAttachment;
itemAttachment.Load();
Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
}
}//for inner
#endregion
//mark as READ
message.IsRead = true;
message.Update(ConflictResolutionMode.AlwaysOverwrite);
Console.WriteLine("------------------------");
}//if
}//for outer

Microsoft team has created EWS-Java-Api (a java implementation) as an alternative to Microsoft.Exchange.WebServices.dll for C# implementation, and nice thing is its open sourced:
Link: https://github.com/OfficeDev/ews-java-api/wiki

JAVA Code:
package EWSGetDetailsOffice365;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.AppointmentSchema;
import microsoft.exchange.webservices.data.CalendarFolder;
import microsoft.exchange.webservices.data.CalendarView;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Folder;
import microsoft.exchange.webservices.data.IAutodiscoverRedirectionUrl;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.ServiceLocalException;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;
public class MSExchangeEmailService {
public static class RedirectionUrlCallback implements IAutodiscoverRedirectionUrl {
public boolean autodiscoverRedirectionUrlValidationCallback(String redirectionUrl) {
return redirectionUrl.toLowerCase().startsWith("https://");
}
}
private static ExchangeService service;
private static Integer NUMBER_EMAILS_FETCH =5; // only latest 5 emails/appointments are fetched.
/**
* Firstly check, whether "https://webmail.xxxx.com/ews/Services.wsdl" and "https://webmail.xxxx.com/ews/Exchange.asmx"
* is accessible, if yes that means the Exchange Webservice is enabled on your MS Exchange.
*/
static{
try{
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
//service.setUrl(new URI("https://webmail.xxxx.com/ews/Exchange.asmx"));
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialize the Exchange Credentials.
* Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables.
*/
public MSExchangeEmailService() {
service.setCredentials(new WebCredentials("abc#domain.com", "1234"));
try {
service.autodiscoverUrl("dhananjayk#sysmind.com", new RedirectionUrlCallback());
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
service.setTraceEnabled(true);
}
/**
* Reading one email at a time. Using Item ID of the email.
* Creating a message data map as a return value.
*/
public Map readEmailItem(ItemId itemId){
Map messageData = new HashMap();
try{
Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties);
EmailMessage emailMessage = EmailMessage.bind(service, itm.getId());
messageData.put("emailItemId", emailMessage.getId().toString());
messageData.put("subject", emailMessage.getSubject().toString());
messageData.put("fromAddress",emailMessage.getFrom().getAddress().toString());
messageData.put("senderName",emailMessage.getSender().getName().toString());
Date dateTimeCreated = emailMessage.getDateTimeCreated();
messageData.put("SendDate",dateTimeCreated.toString());
Date dateTimeRecieved = emailMessage.getDateTimeReceived();
messageData.put("RecievedDate",dateTimeRecieved.toString());
messageData.put("Size",emailMessage.getSize()+"");
messageData.put("emailBody",emailMessage.getBody().toString());
}catch (Exception e) {
e.printStackTrace();
}
return messageData;
}
/**
* Number of email we want to read is defined as NUMBER_EMAILS_FETCH,
*/
public List readEmails(){
List msgDataList = new ArrayList();
try{
Folder folder = Folder.bind( service, WellKnownFolderName.Inbox );
FindItemsResults<Item> results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH));
int i =1;
for (Item item : results){
Map messageData = new HashMap();
messageData = readEmailItem(item.getId());
System.out.println("\nEmails #" + (i++ ) + ":" );
System.out.println("subject : " + messageData.get("subject").toString());
System.out.println("Sender : " + messageData.get("senderName").toString());
msgDataList.add(messageData);
}
}catch (Exception e) {
e.printStackTrace();
}
return msgDataList;
}
/**
* Reading one appointment at a time. Using Appointment ID of the email.
* Creating a message data map as a return value.
*/
public Map readAppointment(Appointment appointment){
Map appointmentData = new HashMap();
try {
appointmentData.put("appointmentItemId", appointment.getId().toString());
appointmentData.put("appointmentSubject", appointment.getSubject());
appointmentData.put("appointmentStartTime", appointment.getStart()+"");
appointmentData.put("appointmentEndTime", appointment.getEnd()+"");
//appointmentData.put("appointmentBody", appointment.getBody().toString());
} catch (ServiceLocalException e) {
e.printStackTrace();
}
return appointmentData;
}
/**
*Number of Appointments we want to read is defined as NUMBER_EMAILS_FETCH,
* Here I also considered the start data and end date which is a 30 day span.
* We need to set the CalendarView property depending upon the need of ours.
*/
public List readAppointments(){
List apntmtDataList = new ArrayList();
Calendar now = Calendar.getInstance();
Date startDate = Calendar.getInstance().getTime();
now.add(Calendar.DATE, 30);
Date endDate = now.getTime();
try{
CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet());
CalendarView cView = new CalendarView(startDate, endDate, 5);
cView.setPropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));// we can set other properties as well depending upon our need.
//FindItemsResults appointments = calendarFolder.findAppointments(cView);
FindItemsResults<Appointment> appointments = calendarFolder.findAppointments(cView);
System.out.println("|------------------> Appointment count = " + appointments.getTotalCount());
int i =1;
//List appList = appointments.getItems();
for (Appointment appointment : appointments.getItems()) {
System.out.println("\nAPPOINTMENT #" + (i++ ) + ":" );
Map appointmentData = new HashMap();
appointmentData = readAppointment(appointment);
System.out.println("subject : " + appointmentData.get("appointmentSubject").toString());
System.out.println("On : " + appointmentData.get("appointmentStartTime").toString());
apntmtDataList.add(appointmentData);
}
}catch (Exception e) {
e.printStackTrace();
}
return apntmtDataList;
}
public static void getAllMeetings() throws Exception {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2016-01-01 00:00:00");
SearchFilter filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime,startDate);
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, filter, new ItemView(1000));
System.out.println("|------------------> meetings count = " + findResults.getTotalCount());
for (Item item : findResults.getItems())
{
Appointment appt = (Appointment)item;
//appt.setStartTimeZone();
System.out.println("TimeZone====="+appt.getTimeZone());
System.out.println("SUBJECT====="+appt.getSubject());
System.out.println("Location========"+appt.getLocation());
System.out.println("Start Time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Last Modified Time========"+appt.getLastModifiedName());
System.out.println("*************************************************\n");
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
public static void main(String[] args) {
MSExchangeEmailService msees = new MSExchangeEmailService();
//msees.readEmails();
//msees.readAppointments();
try {
msees.getAllMeetings();
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Related

Unable to delete documents in documentum application using DFC

I have written the following code with the approach given in EMC DFC 7.2 Development Guide. With this code, I'm able to delete only 50 documents even though there are more records. Before deletion, I'm taking the dump of object id. I'm not sure if there is any limit with IDfDeleteOperation. As this is deleting only 50 documents, I tried using DQL delete command, even there it is limited to 50 documents. I tried using destory() and destroyAllVersions() method that document has, even this didn't work for me. I have written everything in main method.
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.*;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.IDfLoginInfo;
import com.documentum.operations.IDfCancelCheckoutNode;
import com.documentum.operations.IDfCancelCheckoutOperation;
import com.documentum.operations.IDfDeleteNode;
import com.documentum.operations.IDfDeleteOperation;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class DeleteDoCAll {
public static void main(String[] args) throws DfException {
System.out.println("Started...");
IDfClientX clientX = new DfClientX();
IDfClient dfClient = clientX.getLocalClient();
IDfSessionManager sessionManager = dfClient.newSessionManager();
IDfLoginInfo loginInfo = clientX.getLoginInfo();
loginInfo.setUser("username");
loginInfo.setPassword("password");
sessionManager.setIdentity("repo", loginInfo);
IDfSession dfSession = sessionManager.getSession("repo");
System.out.println(dfSession);
IDfDeleteOperation delo = clientX.getDeleteOperation();
IDfCancelCheckoutOperation cco = clientX.getCancelCheckoutOperation();
try {
String dql = "select r_object_id from my_report where folder('/Home', descend);
IDfQuery idfquery = new DfQuery();
IDfCollection collection1 = null;
try {
idfquery.setDQL(dql);
collection1 = idfquery.execute(dfSession, IDfQuery.DF_READ_QUERY);
int i = 1;
while(collection1 != null && collection1.next()) {
String r_object_id = collection1.getString("r_object_id");
StringBuilder attributes = new StringBuilder();
IDfDocument iDfDocument = (IDfDocument)dfSession.getObject(new DfId(r_object_id));
attributes.append(iDfDocument.dump());
BufferedWriter writer = new BufferedWriter(new FileWriter("path to file", true));
writer.write(attributes.toString());
writer.close();
cco.setKeepLocalFile(true);
IDfCancelCheckoutNode cnode;
if(iDfDocument.isCheckedOut()) {
if(iDfDocument.isVirtualDocument()) {
IDfVirtualDocument vdoc = iDfDocument.asVirtualDocument("CURRENT", false);
cnode = (IDfCancelCheckoutNode)cco.add(iDfDocument);
} else {
cnode = (IDfCancelCheckoutNode)cco.add(iDfDocument);
}
if(cnode == null) {
System.out.println("Node is null");
}
if(!cco.execute()) {
System.out.println("Cancel check out operation failed");
} else {
System.out.println("Cancelled check out for " + r_object_id);
}
}
delo.setVersionDeletionPolicy(IDfDeleteOperation.ALL_VERSIONS);
IDfDeleteNode node = (IDfDeleteNode)delo.add(iDfDocument);
if(node == null) {
System.out.println("Node is null");
System.out.println(i);
i += 1;
}
if(delo.execute()) {
System.out.println("Delete operation done");
System.out.println(i);
i += 1;
} else {
System.out.println("Delete operation failed");
System.out.println(i);
i += 1;
}
}
} finally {
if(collection1 != null) {
collection1.close();
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
sessionManager.release(dfSession);
}
}
}
I don't know where I'm making mistake, every time I try, the program stops at 50th iteration. Can you please help me to delete all documents in proper way? Thanks a lot!
At first select all document IDs into List<IDfId> for example and close the collection. Don't do another expensive operations inside of the opened collection, because you are then unnecessarily blocking it.
This is the cause why it did only 50 documents. Because you had one main opened collection and each execution of delete operation opened another collection and it probably reached some limit. So as I said it is better to consume the collection at first and then work further with those data:
List<IDfId> ids = new ArrayList<>();
try {
query.setDQL("SELECT r_object_id FROM my_report WHERE FOLDER('/Home', DESCEND)");
collection = query.execute(session, IDfQuery.DF_READ_QUERY);
while (collection.next()) {
ids.add(collection.getId("r_object_id"));
}
} finally {
if (collection != null) {
collection.close();
}
}
After that you can iterate through the list and do all actions with the document you need. But don't execute delete operation in each iteration - it is ineffective. Instead of it add all documents into one operation and execute it once at the end.
IDfDeleteOperation deleteOperation = clientX.getDeleteOperation();
deleteOperation.setVersionDeletionPolicy(IDfDeleteOperation.ALL_VERSIONS);
for (IDfId id : ids) {
IDfDocument document = (IDfDocument) session.getObject(id);
...
deleteOperation.add(document);
}
deleteOperation.execute();
The same is for the IDfCancelCheckoutOperation.
And another thing - when you are using FileWriter use close() in the finally block or use try-with-resources like this:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.path", true))) {
writer.write(document.dump());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
Using of StringBuilder is good idea, but create it only once at the beginning, append all attributes in each iteration and then write the content of the StringBuilder into the file at the end and not during each iteration - it is slow.
You could just do this from inside your code:
delete my_report objects where folder('/Home', descend)
no need to fetch information you are throwing away again ;-)
You're probably facing result set limit for DFC client.
Try adding to dfc.properties these lines and rerun your code to see if can delete more than 50 rows and after it adjust to your needs.
dfc.search.max_results = 100
dfc.search.max_results_per_source = 100

testNg Factory, DataProvider reading from excel sheet, tests pass only with instance with last row parameters, others get NPE

I am using factory with data provider reading my data from an excel sheet. The issue is that my tests are passing when the last row from the excel sheet is provided through data providers. Preceding rows are giving me NPE.
I am pasting my code here. Thanks for taking a look.
Here is my factory class:
//Factory test class
public class testFactory {
#Factory(dataProviderClass=dataProvider.MyDataProvider.class,dataProvider="userDataProvider")
public Object[] factoryMethod(String email,String password,String firstName, String lastName) {
TestFaceBookUsingExcelSheetAsDataProvider instance = new TestFaceBookUsingExcelSheetAsDataProvider(email,password,firstName, lastName);
return new Object[] { instance };
}
}
This is my data provider class
//Data Provider class
public class MyDataProvider {
#DataProvider(name = "userDataProvider")
public static Object[][] getUserData() {
return ExcelUtils.fileDataProvider("user");//TODO: currently this value is not in use, hard coded in method
}
}
Here is the method which my data provider class method is calling to read data from excel sheet
//Utility Class's helper method to read test data from excel sheet
//#DataProvider(name = "fileDataProvider")
public static Object[][] fileDataProvider(String sheetName) { //TODO: sheetname
try {
//ExcelUtils.setExcelFile(Constant.Path_TestData + Constant.File_TestData,"user");
System.out.println(Constant.Path_TestData + Constant.File_TestData); //TODO
//XSSFWorkbook workbook = new XSSFWorkbook(Constant.Path_TestData + Constant.File_TestData);
XSSFWorkbook workbook = new XSSFWorkbook("<path_to_file>\\TestData.xlsx");
XSSFSheet sheet = workbook.getSheet("user");
Iterator<Row> rowIterator = sheet.iterator();
ArrayList<ArrayList<String>> rowdata = new ArrayList<ArrayList<String>>();
boolean isHeader = true;
while (rowIterator.hasNext()) {
ArrayList<String> columndata = new ArrayList<String>();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (row.getRowNum() > 0) { // To filter column headings
isHeader = false;
if(cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC) {
columndata.add(cell.getNumericCellValue() + "");
} else if (cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING) {
columndata.add(cell.getStringCellValue());
} else if (cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN) {
columndata.add(cell.getBooleanCellValue() + "");
}
}
}
if (isHeader == false ) {
rowdata.add(columndata); // to make sure we don't add an empty array for header row
}
}
workbook.close();
String[][] return_array = new String[rowdata.size()][];
for (int i = 0; i < rowdata.size(); i++) {
ArrayList<String> row = rowdata.get(i);
return_array[i] = row.toArray(new String[row.size()]);
}
return return_array;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
And this, finally, is my test code
//My testclass
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pgFactory.fb.HomePage;
import pgFactory.fb.LandingPage;
import pgFactory.fb.TimeLine;
public class TestFaceBookUsingExcelSheetAsDataProvider {
// Constructor to be called from factory class
public TestFaceBookUsingExcelSheetAsDataProvider(String email, String password, String firstName, String lastName) {
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
}
// class variables to be used in the tests
WebDriver driver;
LandingPage lp;
HomePage hp;
TimeLine tl;
// Variables from data provider which in turn is reading from excel sheet
private String email = null;
private String password = null;
private String firstName = null;
private String lastName = null;
#Override
public String toString()
{
return this.email+ " " + this.password + " " + this.firstName + " " + this.lastName;
}
#BeforeTest
public void setup() {
// Driver
driver = new FirefoxDriver();
// Pages
lp = new LandingPage(driver).get();
hp = new HomePage(driver).get();
tl = new TimeLine(driver).get();
}
// Test methods
#Test()
public void testLogin() {
lp.login(email, password);
// Assert that after login you will see your home page
Assert.assertEquals(hp.getUserLeftNavName().getAttribute("innerHTML"), firstName + " " + lastName,
"The full name is not correct on the left side user navigation frame");
Assert.assertEquals(hp.getUserUpperNavName().getAttribute("innerHTML"), firstName,
"The first is not correct on the upper user navigation bar");
hp.logOut();
}
#Test
public void testMyPage() {
lp.login(email, password);
hp.getUserLeftNavName().click();
String name = (new WebDriverWait(driver, 5))
.until(ExpectedConditions.presenceOfElementLocated(By.id("fb-timeline-cover-name"))).getText();
Assert.assertEquals(name, firstName + " " + lastName, "The fullname on timeline cover is not correct");
hp.logOut();
}
#AfterTest
public void teardown() {
driver.quit();
}
}
BTW, I am learning selenium by automating a few tests on facebook page. So, if I am making a silly mistake, please be patient with me.
I found the solution by debugging the code. The issue is when factory is used then I don't have any control over the BeforeTest annotated methods. These are not being run before tests start to execute. So, NPE is thrown because my pageObject is not instantiated yet.
Workaround. I annotated setup method with #Test and made other tests dependent on this test and it worked like a charm. Its not the best solution because now I have to make every existing and future tests with this dependsOnMethods parameter in annotation.
If you know of a better solution, please reply.

How to solve a FolderClosedIOException?

So I am new to Apache Camel. I know that most of this code is probably not the most efficient way to do this, but I have made a code that uses Apache Camel to access my gmail, grab the new messages and if they have attachments save the attachments in a specified directory. My route saves the body data as a file in that directory. Everytime the DataHandler tries to use the getContent() method, whether its saving a file or trying to print the body to System.out, I get either a FolderClosedIOException or a FolderClosed Exception. I have not clue how to fix it. The catch reopens the folder but it just closes again after getting another message.
import org.apache.camel.*;
import java.io.*;
import java.util.*;
import javax.activation.DataHandler;
import javax.mail.Folder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import com.sun.mail.util.FolderClosedIOException;
public class Imap {
public static void main(String[] args) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() {
from("imaps://imap.gmail.com?username=********#gmail.com&password=******"
+ "&debugMode=false&closeFolder=false&mapMailMessage=false"
+ "&connectionTimeout=0").to("file:\\EMAIL");
}
});
Map<String,String> props = new HashMap<String,String>();
props.put("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.imap.auth", "true");
props.put("mail.imap.host","imap.gmail.com");
props.put("mail.store.protocol", "imaps");
context.setProperties(props);
Folder inbox = null;
ConsumerTemplate template = context.createConsumerTemplate();
context.start();
while(true) {
try {
Exchange e = template.receive("imaps://imap.gmail.com?username=*********#gmail.com&password=***********", 60000);
if(e == null) break;
Message m = e.getIn();
Map<String, Object> s = m.getHeaders();
Iterator it = s.entrySet().iterator();
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey()+" === "+pairs.getValue()+"\n\n");
it.remove();
}
if(m.hasAttachments()) {
Map<String,DataHandler> att = m.getAttachments();
for(String s1 : att.keySet()) {
DataHandler dh = att.get(s1);
String filename = dh.getName();
ByteArrayOutputStream o = new ByteArrayOutputStream();
dh.writeTo(o);
byte[] by = o.toByteArray();
FileOutputStream out = new FileOutputStream("C:/EMAIL/"+filename);
out.write(by);
out.flush();
out.close();
}
}
} catch(FolderClosedIOException ex) {
inbox = ex.getFolder();
inbox.open(Folder.READ_ONLY);
}
}
context.stop();
}
}
Please somebody tell me whats wrong!!
The error occurs here:
dh.writeTo(o);
We were was solving a similar problem in akka-camel
The solution i believe was to use manual acknowledgement and send an acknowledgement after we were done with the message.

How to verify whether a link read from file is present on webpage or not?

I am new at automation. I have to write a code as follow
I have to read around 10 url's from a file and store it into one hashtable then I need to read one by one url's from hashtable and while iterating through this url I also need to read one more file conataining 3 url's and search them on webpage . If present need to click that link
I have written following code but I am not getting the logic for checking whether a link from file is present on webpage or not...
Please check my code and help me to solve/improve it.
Main test script
package com.samaritan.automation;
import java.util.Hashtable;
import java.util.Set;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstScript {
WebDriver driver = new FirefoxDriver();
String data;
CommonControllers commonControll = null;
Hashtable<String, String> recruiters = null;
#Test
public void script() throws Exception {
CommonControllers commonControll = new CommonControllers();
recruiters = new Hashtable<String,String>();
recruiters = commonControll.readDataFromFile("D:/eRecruiters/_Recruiters.properties");
Set<String> keys = recruiters.keySet();
for(String key: keys){
/**HERE I NEED TO WRITE THE FUNCTION TO VERIFY WHETHER THE LINK READ FROM SECOND FILE IS PRESENT ON WEBPAGE OR NOT**/
}
}
}
and function to read from file into hashtable
public Hashtable<String, String> readDataFromFile(String fileName) {
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String strLine = null;
String []prop = null;
while((strLine = br.readLine()) != null) {
prop = strLine.split("\t");
recruiters.put(prop[0], prop[1]);
}
br.close();
fr.close();
}catch(Exception exception) {
System.out.println("Unable to read data from recruiter file: " + exception.getMessage());
}
return recruiters;
}
PLease take a look! thanks
Priya...You can use
if(isElementPresent(By.linkText(LinkTextFoundFromFile))){
//code when link text present there
}else {
//code for not finding the link
}
Now the following method is generalized for any By object you can use like By.xpath, By.id etc.
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}

excel file upload using apache file upload

I am developing an testing automation tool in linux system. I dont have write permissions for tomcat directory which is located on server. I need to develop an application where we can select an excel file so that the excel content is automatically stored in already existing table.
For this pupose i have written an form to select an file which is posted to a servlet CommonsFileUploadServlet where i am storing the uploaded file and then calling ReadExcelFile class which reads the file path and create a vector for data in file which is used to sstore data in database.
My problem is that i am not able to store the uploaded file in directory. Is it necessary to have permission rights for tomcat to do this. Can i store the file on my system and pass the path to ReadExcelFile.class
Please guide me
My code is as follows:
Form in jsp
CommonsFileUploadServlet class code:
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
fileItemFactory.setRepository(new File("/home/example/Documents/Project/WEB-INF/tmp"));
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());
File file = new File("/",item.getName());
String realPath = getServletContext().getRealPath("/")+"/"+item.getName();
item.write(file);
ReadExcelFile ref= new ReadExcelFile();
String res=ref.insertReq(realPath,"1");
}
out.close();
}
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
ReadExcelFile code:
public static String insertReq(String fileName,String sno) {
//Read an Excel File and Store in a Vector
Vector dataHolder=readExcelFile(fileName,sno);
//store the data to database
storeCellDataToDatabase(dataHolder);
}
public static Vector readExcelFile(String fileName,String Sno)
{
/** --Define a Vector
--Holds Vectors Of Cells
*/
Vector cellVectorHolder = new Vector();
try{
/** Creating Input Stream**/
//InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int s=Integer.valueOf(Sno);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(s);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
short minColIndex = myRow.getFirstCellNum();
short maxColIndex = myRow.getLastCellNum();
for(short colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
{
HSSFCell myCell = myRow.getCell(colIndex);
if(myCell == null)
{
cellStoreVector.addElement(myCell);
}
else
{
cellStoreVector.addElement(myCell);
}
}
cellVectorHolder.addElement(cellStoreVector);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void storeCellDataToDatabase(Vector dataHolder)
{
Connection conn;
Statement stmt;
String query;
try
{
// get connection and declare statement
int z;
for (int i=1;i<dataHolder.size(); i++)
{
z=0;
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
String []stringCellValue=new String[10];
for (int j=0; j < cellStoreVector.size();j++,z++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
if(myCell==null)
stringCellValue[z]=" ";
else
stringCellValue[z] = myCell.toString();
}
try
{
//inserting into database
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
stmt.close();
conn.close();
System.out.println("success");
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
POI will happily open from an old InputStream, it needn't be a File one.
I'd suggest you look at the Commons FileUpload Streaming API and consider just passing the excel part straight to POI without touching the disk