Cucumber - Content Assistance in Feature file not working - scala

So, I've been having a tough time getting the dependencies down with Cucumber/Scala integration. I finally have a simple step definition running, but when I press control + space bar, the list of step definitions do not show up in my feature file. However, when I run the feature file, it runs successfully.
Test Runner
package CucumberTest
import cucumber.api.CucumberOptions
import cucumber.api.junit.Cucumber
import org.junit.runner.RunWith
#RunWith(classOf[Cucumber])
#CucumberOptions(
features = Array("Feature")
,glue= Array("stepDefinition")
,plugin = Array ("pretty", "html:target/cucumber/html")
)
class TestRunner {
def main(args: Array[String]): Unit = {
println("Hi")
}
}
Step Definition file
package stepDefinition
import cucumber.api.scala.{ ScalaDsl, EN }
class Test_Steps extends ScalaDsl with EN{
Given("""^this pre condition$""") { () =>
println("YOOOOOOOOO!!!")
}
When("""^I do this$""") { () =>
//// Write code here that turns the phrase above into concrete actions
}
Then("""^I can verify that$""") { () =>
//// Write code here that turns the phrase above into concrete actions
}
Then("""^I can also verify that$""") { () =>
//// Write code here that turns the phrase above into concrete actions
}
This is what my feature looks like. "this pre condition" is highlighted in yellow, indicating that the feature file is not finding the glue code.
When I hover my mouse over the Given statement, I get this message
Step 'this pre condition' does not have a matching glue code
But when I run it, I get this as the output.
Scala Console output
Since YOOOOOOOOO!!! printed in the console, it's seeing my glue code and running successfully, but I don't get a list of step definitions and the phrase "this pre condition" is highlighted yellow.
Does anyone know what the issue could be?
Here are some dependencies relating to cucumber/scala
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-scala_2.11</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.8</version>
</dependency>

So I think the issue was a combination on having dependency mismatches as well as not adding Junit to my project path.
This is what my Test_Steps class looks like now. I imported libraries from Cucumber java api.
package stepDefinition
//import org.slf4j.LoggerFactory
import cucumber.api.java.en.Given;
import cucumber.api.scala._
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.api.java8._
import cucumber.api.scala.{ ScalaDsl, EN }
import cucumber.runtime.java.StepDefAnnotation
#StepDefAnnotation
class Test_Steps extends ScalaDsl with EN {
//this works
#Given("""^this pre condition$""")
def this_pre_condition() = {
println("Hello")
}
#When("""^blah condition$""")
def when_condition() = {
println("In the when statement -- ")
}
}
My feature file's content assistance feature works now.
Junit output
Console output

Related

java.util.NoSuchElementException while executing junit Testrunner

Error I am getting is:
java.util.NoSuchElementException while running junit test. Here is full error from console in eclipse:
java.util.NoSuchElementException
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
at java.base/java.util.Collections.max(Collections.java:713)
at io.cucumber.core.feature.FeatureParser.parseResource(FeatureParser.java:45)
at java.base/java.util.function.BiFunction.lambda$andThen$0(BiFunction.java:70)
at io.cucumber.core.resource.ResourceScanner.lambda$processResource$1(ResourceScanner.java:79)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:75)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:60)
at java.base/java.nio.file.Files.walkFileTree(Files.java:2811)
at io.cucumber.core.resource.PathScanner.findResourcesForPath(PathScanner.java:53)
at io.cucumber.core.resource.PathScanner.findResourcesForUri(PathScanner.java:31)
at io.cucumber.core.resource.ResourceScanner.findResourcesForUri(ResourceScanner.java:61)
at io.cucumber.core.resource.ResourceScanner.scanForResourcesUri(ResourceScanner.java:134)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.loadFeatures(FeaturePathFeatureSupplier.java:62)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.get(FeaturePathFeatureSupplier.java:45)
at io.cucumber.junit.Cucumber.<init>(Cucumber.java:156)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.requests.ClassRequest.createRunner(ClassRequest.java:28)
at org.junit.internal.requests.MemoizingRequest.getRunner(MemoizingRequest.java:19)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:90)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:513)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Library I am using:
My Testrunner script is:
package TestRunner;
import org.junit.runner.RunWith;
import org.openqa.selenium.NoSuchElementException;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(features="C:\\Users\\Ashok Kumar\\eclipse-workspace\\CucumberWithSelenium\\Features",glue={"StepDefinition"})
public class Runner {
}
My steps script:
package StepDefinition;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.NoSuchElementException;
//import io.cucumber.java.*;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
//import cucumber.api.junit.Cucumber;
public class Steps {
WebDriver driver = null;
#Given("^I am on Facebook login page$")
/*
public void goToFacebook() {
WebDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com");
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
} */
#Given("^Open the Chrome and launch the application$")
public void open_the_Chrome_and_launch_the_application() throws Throwable{
System.out.println("This Step open the Firefox and launch the application.");
}
#When("^Enter the Username and Password$")
public void enter_the_Username_and_Password() throws Throwable
{
System.out.println("This step enter the Username and Password on the login page.");
}
#Then("^Reset the credential$")
public void Reset_the_credential() throws Throwable
{
System.out.println("This step click on the Reset button.");
}
}
I have searched all previous posts in google on java.util.NoSuchElementException. But still I didn't come to webdriver as you have seen above. I did comment it as I have come across this error. I have tried even with WebDriver code above, still I am getting the error. Please help me. I am unable to edit java.base/java.util.ArrayList$Itr.next using next I have seen in google.
Thanks God. I found a solution or work around. Here is what I had done.
Had converted the project to Maven project.
I have mentioned latest dependencies
Here is my POM.
4.0.0
CucumberWithSelenium
CucumberWithSelenium
0.0.1-SNAPSHOT
src
maven-compiler-plugin
3.8.1
17
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.2.3</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>7.2.3</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-jvm-deps</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>gherkin</artifactId>
<version>22.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>7.2.3</version>
</dependency>
</dependencies>

org.apache.shiro.web.filter.authc.LogoutFilter is already configured in ShiroWebModule

I'm using Shiro 1.7.1 and Guice 4.2.3, below is the snippet of my POM file,
<properties>
<shiro.version>1.7.1</shiro.version>
<guice.version>4.2.3</guice.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-guice</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>com.google.inject.extensions</groupId>
<artifactId>guice-servlet</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
...
</dependencies>
I'm customizing Shiro's LogoutFilter by creating a new class,
package com.myshiro.myshiro;
import org.apache.shiro.web.filter.authc.LogoutFilter;
public class MyLogoutFilter extends LogoutFilter {
}
and bind org.apache.shiro.web.filter.authc.LogoutFilter to the above customized MyLogoutFilter,
package com.myshiro.myshiro;
public class MyShiroModule extends ShiroWebModule {
public MyShiroModule(ServletContext servletContext) {
super(servletContext);
}
protected void configureShiroWeb() {
try {
bindRealm().toConstructor(IniRealm.class.getConstructor(Ini.class));
} catch (NoSuchMethodException e) {
addError(e);
}
bind(org.apache.shiro.web.filter.authc.LogoutFilter.class).to(MyLogoutFilter.class).in(Scopes.SINGLETON);
addFilterChain("/logout", LOGOUT);
}
}
and I try to create the Guice injector in the unit test class like this,
public class MyShiroModuleTest {
#Mock
private ServletContext servletContext;
#Test
public void test() {
Guice.createInjector(new MyShiroModule(servletContext));
}
}
and it failed with the following errors,
1) Binding to null instances is not allowed. Use toProvider(Providers.of(null)) if this is your intended behaviour.
at org.apache.shiro.guice.web.ShiroWebModule.configureShiro(ShiroWebModule.java:136)
2) A binding to org.apache.shiro.web.filter.authc.LogoutFilter was already configured at com.myshiro.myshiro.MyShiroModule.configureShiroWeb(MyShiroModule.java:25).
at org.apache.shiro.guice.web.ShiroWebModule.setupFilterChainConfigs(ShiroWebModule.java:209)
From the second note above, it explained that the binding to org.apache.shiro.web.filter.authc.LogoutFilter is already configured in both MyShiroModule and ShiroWebModule. Do you have any idea of how to bind to my customized LogoutFilter?
This issue did not happened in Shiro 1.3.x.
My sample project is available here, you can see the error simply when you mvn clean install.
Sounds like your problem is related to Guice 4, and less about Shiro. Instead of re-using the same binding key, define a new one, something like:
bind(MyLogoutFilter.class).to(MyLogoutFilter.class).in(Scopes.SINGLETON);
addFilterChain("/logout", Key.get(MyLogoutFilter.class));

Quarkus with Vertx and RxJava2 imports yields NoClassDefFoundError

I'm attempting to follow the basic examples on quarkus.io regarding using Vert.x. While attempting to use RxJava instead of the Axle API, I get a runtime error:
Error handling 24416339-00a4-4898-8373-b5d905b39179-2, org.jboss.resteasy.spi.UnhandledException: java.lang.NoClassDefFoundError: Could not initialize class io.vertx.reactivex.ext.web.client.WebClient
My code for this class is as follows:
package io.blah.accountadminservice.client;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
//import io.vertx.axle.core.Vertx;
//import io.vertx.axle.ext.web.client.WebClient;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ApplicationScoped
public class VaultClient {
private static final Logger LOGGER = LoggerFactory.getLogger(VaultClient.class);
#Inject
Vertx vertx;
private WebClient client;
private String vaultToken;
#ConfigProperty(name = "vault.host")
private String vaultHost;
#ConfigProperty(name = "vault.port")
private String vaultPort;
#ConfigProperty(name = "vault.loginPath")
private String vaultLoginPath;
#PostConstruct
void initialize() {
this.client = WebClient.create(vertx); // this kills it
}
public void getVaultToken() {
}
}
When following the tutorial using the Axel API, I can build a web client. As soon switch to reactivex, these failures start happening.
My dependencies are:
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-vertx</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-rx-java2</artifactId>
<version>${vertx-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
vertx-version is set to 3.7.1 at the moment. Side note: I've noticed when using the rxjava2 import, it's not possible to import io.vertx.ext.web.client.WebClientOptions; I don't know if that's supposed to work or not.
You need to add the following dependency in your pom.xml file:
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
<version>3.7.1</version>
</dependency>
The version must match the version used in Quarkus.

Tesseract gives warning message

I am working with tess4j (4.3.1 version) so that I can convert image files to text file for preparing index for Lucene.It does its work but at the end gives an warning
Warning: Parameter not found: enable_new_segsearch
Here is my pom.xml
<dependencies>
<dependency>
<groupId>org.ghost4j</groupId>
<artifactId>ghost4j</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.lept4j</groupId>
<artifactId>lept4j</artifactId>
<version>1.12.0</version>
</dependency>
</dependencies>
And my java main class:
File imageFile = new File("samples/eurotext.pdf");
ITesseract instance = new Tesseract();
instance.setDatapath("E:\\tessdata");
try {
String result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
Using following VM arguments:
-Djna.library.path=${workspace_loc:/ocr-tess4j-example}/dlls/x64
Contents of dlls/x64 folder:
gsdll64.dll
liblept1760.dll
libtesseract400.dll
How can I get rid of the warning message?
Try:
instance.setTessVariable("debug_file", "/dev/null");
Language data was not correct.Downloaded whole tessdata from [https://github.com/tesseract-ocr/tessdata] . Error gone. Got the idea from here
https://pdfc.inetsoftware.de/public/help/tesseract4/p/optical-character-recognition

Can selenium be used for testing email contents of an email in Microsoft Outlook

I am using Selenium for testing a web Application.
One of the functionality is "Upload a file"-
As soon as i upload a file, a cron job is executed on the back end to upload my file. Once, the file is uploaded, the user receives an email notifying that the file is uploaded containing all the information about the file.
I receive this email on Microsoft Outlook.
Is there any way i can test this functionality and the contents of the email in the Microsoft Outlook?
The best bet to test email is to ask to the email server (and preferrably configure it on IMAP if a client is connected to it :-)). A java mail client is a breeze to do in Java with Apache Commons Email
If you really want to connect to Outlook, then you can use a connector, as suggested by #ABP. See this SO question (and answer)
If you really really (really ?) want to use selenium, you'll be stuck because the basis of Selenium is its drivers (for Firefox, Chrome, etc) and there is no driver for Outlook (Selenium is web site automation, after all). The API itself is for clicking on links, but no retreiving emails
If you're adventurous, you can bet on Sikuli which is a powerful desktop automation solution that can at least open Outlook, check emails, and check if an email subject match a certain pattern. But it is OCR,and when you start doing OCR for testing... things can go bad really really fast
Do you have a web version of your email. Outlook is the email client. Do you have any web based email client, you can do it then. I don't think you can use Selenium to read from outlook.. but in Java I think you will find Outlook connectors that you can use probably.
driver.findElement(By.id("username")).sendKeys("xyz#company.com");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.xpath("submit")).click();
Thread.sleep(3000);
//Click on Arrange by
driver.findElement(By.cssSelector("#tdAB")).click();
//click on selection to arrange
driver.findElement(By.cssSelector("#spnT")).click();
//Come to the top of the list
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_HOME);
robot.keyRelease(KeyEvent.VK_HOME);
//Procedure to find first email by subject and click the link in it
Thread.sleep(5000);
List<WebElement> email = driver.findElements(By.cssSelector("#divSubject"));
for(WebElement emailsub : email){
if(emailsub.getText().equals("<email subject>") == true){
emailsub.click();
break;
}
}
This was exactly requirements in my project. I have sorted this by using JAVAX MAIL API and JAVA. Additionally,it checks for attachment and if yes, read the pdf as well.
// Dependencies & Imports
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.j256.simplemagic.ContentType;
import org.apache.commons.codec.binary.Base64;
import com.testautomationguru.utility.PDFUtil;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
public OutlookEmail(String username, String password, String server, EmailsFolder
inbox) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.mime.base64.ignoreerrors", "true");
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
Store store = mailSession.getStore("imap");
store.connect("outlook.office365.com", "<your email>", "<your password>");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.out.println("Total Message:" + folder.getMessageCount());
System.out.println("Unread Message:" + folder.getUnreadMessageCount());
messages = folder.getMessages();
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
System.out.println("***************************************************");
System.out.println("MESSAGE : \n");
System.out.println("Subject: " + mail.getSubject());
System.out.println("From: " + mail.getFrom()[0]);
System.out.println("To: " + mail.getAllRecipients()[0]);
System.out.println("Date: " + mail.getReceivedDate());
System.out.println("Size: " + mail.getSize());
System.out.println("Flags: " + mail.getFlags());
System.out.println("ContentType: " + mail.getContentType());
System.out.println("Body: \n" + getEmailBody(mail));
System.out.println("Has Attachments: " + hasAttachments(mail));
}
}
}
public boolean hasAttachments(Message email) throws Exception {
// suppose 'message' is an object of type Message
String contentType = email.getContentType();
System.out.println(contentType);
if (contentType.toLowerCase().contains("multipart/mixed")) {
// this message must contain attachment
Multipart multiPart = (Multipart) email.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
System.out.println("Attached filename is:" + part.getFileName());
MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
String fileName = mimeBodyPart.getFileName();
String destFilePath = System.getProperty("user.dir") + "\\Resources\\";
File fileToSave = new File(fileName);
mimeBodyPart.saveFile(destFilePath + fileToSave);
// download the pdf file in the resource folder to be read by PDFUTIL api.
PDFUtil pdfUtil = new PDFUtil();
String pdfContent = pdfUtil.getText(destFilePath + fileToSave);
System.out.println("******---------------********");
System.out.println("\n");
System.out.println("Started reading the pdfContent of the attachment:==");
System.out.println(pdfContent);
System.out.println("\n");
System.out.println("******---------------********");
Path fileToDeletePath = Paths.get(destFilePath + fileToSave);
Files.delete(fileToDeletePath);
}
}
return true;
}
return false;
}
public String getEmailBody(Message email) throws IOException, MessagingException {
String line, emailContentEncoded;
StringBuffer bufferEmailContentEncoded = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
while ((line = reader.readLine()) != null) {
bufferEmailContentEncoded.append(line);
}
System.out.println("**************************************************");
System.out.println(bufferEmailContentEncoded);
System.out.println("**************************************************");
emailContentEncoded = bufferEmailContentEncoded.toString();
if (email.getContentType().toLowerCase().contains("multipart/related")) {
emailContentEncoded = emailContentEncoded.substring(emailContentEncoded.indexOf("base64") + 6);
emailContentEncoded = emailContentEncoded.substring(0, emailContentEncoded.indexOf("Content-Type") - 1);
System.out.println(emailContentEncoded);
String emailContentDecoded = new String(new Base64().decode(emailContentEncoded.toString().getBytes()));
return emailContentDecoded;
}
return emailContentEncoded;
}
Here is POMs dependencies section:
<dependencies>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-gmail</artifactId>
<version>v1-rev105-1.25.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.testautomationguru.pdfutil/pdf-util -->
<dependency>
<groupId>com.testautomationguru.pdfutil</groupId>
<artifactId>pdf-util</artifactId>
<version>0.0.3</version>
</dependency>
<!-- Checking pdf file and whether is corrupted or not -->
<dependency>
<groupId>com.j256.simplemagic</groupId>
<artifactId>simplemagic</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>smtp</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.14.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>