How to generate email on failed test cases in selenium WebDriver? - selenium

Unable to generate email on Failed test cases in selenium web driver, have generated the generic email(on Passed/Failed Test cases) and it will send an email at the end of the test suite in TestNG framework but the requirement here is to send an email only in the case of failed test case(s).
Here is the code snippet of Email:
String to="smimran#macrosoftinc.com";
final String username = "username";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("syed.imran3411#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("A testing mail header !!!");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "F:\\Java Selenium\\WorkPlace\\Velco Automation Testing\\test-output\testng.css";
String fileName = "testng.css";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
Thread.sleep(5000);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
}
}
Please suggest me the solution. Thanks!

I suggest using Jenkins and send mail via the email plugin.

Related

get report G Suite account

I'm trying to get google report activity by calling https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet
I created a service account and I have to use the generated private key (json file) as access token.
My code was:
String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?eventName=call_ended&maxResults=10&access_token=";
String graph = "";
try
{
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader("C:/Users/Administrateur/Desktop/GoogleApis/Interoperability-googleApis/target/classes/my-first-project-274515-361633451f1c.json"));//path to the JSON file.
String json_private_key = data.toJSONString();
URL urUserInfo = new URL(PROTECTED_RESOURCE_URL + json_private_key);
HttpURLConnection connObtainUserInfo = (HttpURLConnection) urUserInfo.openConnection();
if (connObtainUserInfo.getResponseCode() == HttpURLConnection.HTTP_OK)
{
StringBuilder sbLines = new StringBuilder("");
BufferedReader reader = new BufferedReader(new InputStreamReader(connObtainUserInfo.getInputStream(), "utf-8"));
String strLine = "";
while ((strLine = reader.readLine()) != null)
{
sbLines.append(strLine);
}
graph = sbLines.toString();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
System.out.println("--------------- Result: " + graph);
but I got null value.
Could you please tell me what I misses ?.
Big Thanks.
The Access Token is not part of your request URL. You can read here about the OAuth2 protocol and how it works.
However, Google built an API that enables you to authenticate your requests without worrying about the underlying OAuth2 process.
You should be using the Java Google Reports API to access activities. Here you can find the Java Quickstart that will help you with the first set up of your Java Application.
Here the Java translation of what you are trying to do, using the Google Reports API:
Reports service = new Reports.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
String userKey = "all";
String applicationName = "meet";
String eventName = "call_ended";
Activities result = service.activities().list(userKey, applicationName)
.setEventName(eventName)
.setMaxResults(10)
.execute();
Edit:
Be sure to use the last version of the Java API package. You can find the Java API docs here: https://developers.google.com/resources/api-libraries/documentation/admin/reports_v1/java/latest/
If you are using Gradle be sure to have this line in the dependencies parameter.
dependencies {
...
compile 'com.google.apis:google-api-services-admin-reports:reports_v1-rev89-1.25.0'
}
References
OAuth2
Google Reports API

LDAP Authentication for Azkaban

We are trying to setup Azkaban with LDAP authentication in our production environment. Any leads on how to do this? Documentation says it can be done by adding plugin jar file by extending UserManager class . I am a newbie to azkaban , looking for some example code for this
You will need to install a custom "user manager" plugin. It can be found on github: https://github.com/researchgate/azkaban-ldap-usermanager
The instructions on how to configure the user manager plugin can be found on the front page of the github repo.
In essence you will need to:
Download and build the plugin
Copy the .jar file that you built into the ./extlib directory of your Azkaban installation
Edit azkaban.properties file, specifying user.manager.class and a number of user.manager.ldap properties.
We also wanted to setup an LDAP authentication in azkaban - but the open source project mentioned in first answer has very limited capabilities and doesn't allow to start TLS negotiation after the connection to LDAP server is established.
We have written a completely new java class to take care of the following scenarios:
Establish a LDAP connection unsecurely (on port 389)
Start TLS Response and TLS negotiate
And then athenticate the user credentials.
With this approach we also dont have to create a service user in LDAP only for azkaban.
Take a look in the sample code block
#Override
public User getUser(String username, String password) throws UserManagerException {
if (username == null || username.trim().isEmpty()) {
throw new UserManagerException("Username is empty.");
} else if (password == null || password.trim().isEmpty()) {
throw new UserManagerException("Password is empty.");
}
String email = null;
String groups = null;
StringBuilder url = new StringBuilder("ldap://").append(ldapHost).append(":").append(ldapPort);
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url.toString());
try {
// Create initial context
LdapContext ctx = new InitialLdapContext(env, null);
// Start TLS
StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
SSLSession sess = tls.negotiate();
// Adding username and password to environment
StringBuilder sb = new StringBuilder("uid=").append(username).append(",").append(ldapUserBase);
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, sb.toString());
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
// Search the user in a LDAP directory
final LdapCtx x = (LdapCtx) ctx.lookup(sb.toString());
// Lookup is successful - creating an Azkaban user
User user = new User(username);
// Searching LDAP directory to get email and group
SearchControls ctls = new SearchControls();
String[] attributes = { "cn", "memberOf", "mail" };
ctls.setReturningAttributes(attributes);
NamingEnumeration<?> answer = ctx.search(ldapUserBase, "(uid=" + username + ")", ctls);
Boolean isAdmin = false;
// Search user email and groups
while (answer.hasMore()) {
SearchResult rslt = (SearchResult) answer.next();
Attributes attrs = rslt.getAttributes();
groups = attrs.get("memberof").toString().split(":")[1].trim();
if (attrs.get("memberof") != null && attrs.get("memberof").toString().split(":").length > 0) {
groups = attrs.get("memberof").toString().split(":")[1].trim();
for (String group : groups.split(",")) {
if (ldapAdminGroups.contains(group))
isAdmin = true;
}
}
if (attrs.get("mail") != null) {
email = attrs.get("mail").toString().split(":")[1].trim();
user.setEmail(email);
}
}
// Assign the correct role
if (isAdmin)
user.addRole("admin");
else
user.addRole("read");
ctx.close();
return user;
} catch (NamingException e) {
throw new UserManagerException("LDAP error: " + e.getMessage(), e);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new UserManagerException("IO error", e);
}
}
Note: I haven't done lot of exception handling in this - you need to do it as per your needs.
How to make it make it work in Azkaban:
Build a maven or gradle project.
No additional library is required (except Azkaban - i.e. com.linkedin.azkaban)
Have a new class which will inherit 'azkaban.user.UserManager'
Build and copy the jar in azkaban/extlibs
In azkaban.properties - set "user.manager.class=" and also all required properties like host, port and ldap userbase (ou=Users,dc=stackoverflow,dc=com) details.
And you should be good to authenticate users via LDAP.
Happy Coding !!
Thanks,
Hussain Bohra

JavaMail, Exchange Server and “no login methods supported”

I'm trying to read contents of a mailbox, using JavaMail and IMAP.
No SSL, only plain IMAP.
My code is like this:
// Connection default properties
Properties props = new Properties();
props.setProperty("mail.imap.timeout", "5000");
props.setProperty("mail.imap.connectiontimeout", "5000");
props.setProperty("mail.pop3.timeout", "5000");
props.setProperty("mail.pop3.connectiontimeout", "5000");
props.setProperty("mail.smtp.timeout", "5000");
props.setProperty("mail.smtp.connectiontimeout", "5000");
// Get session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
// Get the store
Store store = session.getStore(account.getProtocol()); // returns "imap"
String username = account.getUsername();
String password = account.getPassword();
String host = account.getHost();
store.connect(host, username, password);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[] = folder.search(ft);
System.out.println("Ci sono " + messages.length + " messaggi da leggere");
Here is what i get:
https://www.dropbox.com/s/zbqh7gt3xqgobo7/imap_error.png
It seems that Exchange server is rejecting my login trials...i'm stuck with this and can't understand how to proceed further.
Anyone can help?
The server is configured not to allow 'LOGIN' on plaintext ports.
Note the CAPABILITY response: LOGINDISABLED, and no alternative AUTH methods are presented. You will likely need to connect with SSL encryption.
On the other hand, I don't know why they'd keep open the plaintext port if it can't be used....

Is it possible to get Remote Servers for testing Upload Files functionality?

I have a simle program shown below which is resonsible to upload a file to a Remote Location
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File firstLocalFile = new File("D:/Test/Projects.zip");
String firstRemoteFile = "Projects.zip";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
}
My question is , is it possible to test this program anyway , as i dont have a Remote Server currently .
Means is it possible to get remote server to upload files for temporary purpose ( Sorry but only open source please )
Is anybody aware of such websites ??
Screen shot

send the VSTS 2008 test results by email

Can I send the VSTS 2008 test results by email automatically after test run?
Here you can download "Email Reporter: VSTS 2008 Load Test Plug-in" http://code.msdn.microsoft.com/erep
It's a very helpful post by Mohammad Ashraful Alam.
you can send email with notification and report attached. I guess, you can you can create stored procedure and run them at the end of the test execution for gathering required data. After that you can create .xml or Excel file with result of created procedure and attached it to email. So, you need to create load test plug-in:
namespace LoadTestPluginTest
{
public class MyLoadTestPlugin : ILoadTestPlugin
{
LoadTest myLoadTest;
public void Initialize(LoadTest loadTest)
{
myLoadTest = loadTest;
myLoadTest.LoadTestFinished += new
EventHandler(myLoadTest_LoadTestFinished);
}
void myLoadTest_LoadTestFinished(object sender, EventArgs e)
{
try
{
// place custom code here
MailAddress MyAddress = new MailAddress("someone#example.com");
MailMessage MyMail = new MailMessage(MyAddress, MyAddress);
MyMail.Subject = "Load Test Finished -- Admin Email";
MyMail.Body = ((LoadTest)sender).Name + " has finished.";
SmtpClient MySmtpClient = new SmtpClient("localhost");
MySmtpClient.Send(MyMail);
}
catch (SmtpException ex)
{
MessageBox.Show(ex.InnerException.Message +
".\r\nMake sure you have a valid SMTP.", "LoadTestPlugin");
}
}
}
}
Here is the description of LoadTest DB tables http://blogs.msdn.com/billbar/articles/529874.aspx