java.lang.NoSuchFieldError:ACKNOWLEDGED - mongodb

SOAP UI error log I have encountered the above error message while executing in SOAPUI tool, as the same code works properly while executing through Maven.
I have a search on google about this problem and found that this issue occurred due to the conflict in Jar file. I have removed the Mongo DB jar which is causing the conflict.
Dependency in POM file is
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.8.1</version>
</dependency>
In my bin/ext folder, I have added
bson-3.4.2.jar and
mongo-java-driver-3.10.2
My code is,
import com.mongodb.*
import com.mongodb.client.*
import com.mongodb.client.MongoCollection
import org.bson.*
try{
def mongoURI = "mongodb://localhost:27017";
MongoClientURI connectionString = new MongoClientURI(mongoURI);
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("DatabaseName");
MongoCollection<Document> collection =
database.getCollection("CollectionName");
MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
log.info "Documents is- "+cursor.next().toJson();
}
}finally {
cursor.close();
}
}catch(Exception e){
log.info "test Exception is "+e.getMessage();
}
finally{
log.info "Finally block";
}

Related

Embedded mongodb to spring-boot application java exception

I need to set embedded mongodb in my springboot project but it show infinite error logs. Someone can help me?
I use these dependencies
<!-- https://mvnrepository.com/artifact/de.flapdoodle.embed/de.flapdoodle.embed.mongo -->
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cz.jirutka.spring/embedmongo-spring -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.8.0</version>
<exclusions>
<exclusion>
<groupId>org.mongodb</groupId> <!-- Exclude Project-E from Project-B -->
<artifactId>bson</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>cz.jirutka.spring</groupId>
<artifactId>embedmongo-spring</artifactId>
<version>1.3.1</version>
</dependency>
And then i configure the mongoTemplate with this method in a configuration class
private static final String MONGO_DB_URL = "localhost";
private static final String MONGO_DB_NAME = "embedded_db";
#Bean
public MongoTemplate mongoTemplate() throws IOException {
EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();
mongo.setBindIp(MONGO_DB_URL);
MongoClient mongoClient = (MongoClient) mongo.getObject();
return new MongoTemplate(mongoClient, MONGO_DB_NAME);
}
But when i run my application it show this error+
Exception in thread "main" 11:56:00.710 [Thread-0] DEBUG de.flapdoodle.embed.process.store.CachingArtifactStore - force delete for PRODUCTION:Windows:B64 and de.flapdoodle.embed.process.extract.ImmutableExtractedFileSet#545997b1
11:56:00.710 [Thread-1] DEBUG de.flapdoodle.embed.mongo.AbstractMongoProcess - try to stop mongod
java.lang.NoSuchMethodError: 'void com.mongodb.client.internal.MongoClientDelegate.<init>(com.mongodb.connection.Cluster, java.util.List, java.lang.Object)'
at com.mongodb.Mongo.<init>(Mongo.java:319)
at com.mongodb.Mongo.<init>(Mongo.java:291)
at com.mongodb.Mongo.<init>(Mongo.java:286)
at com.mongodb.Mongo.<init>(Mongo.java:282)
at com.mongodb.MongoClient.<init>(MongoClient.java:180)
at com.mongodb.MongoClient.<init>(MongoClient.java:155)
at com.mongodb.MongoClient.<init>(MongoClient.java:145)
at cz.jirutka.spring.embedmongo.EmbeddedMongoBuilder.build(EmbeddedMongoBuilder.java:104)
at cz.jirutka.spring.embedmongo.EmbeddedMongoFactoryBean.getObject(EmbeddedMongoFactoryBean.java:52)
at com.nextage.arcacrmconnector.commons.EmbeddedMongoDb.mongoTemplate(EmbeddedMongoDb.java:20)
at com.nextage.arcacrmconnector.commons.MongoTemplateSingleton.setMongoTemplate(MongoTemplateSingleton.java:20)
at com.nextage.arcacrmconnector.commons.MongoTemplateSingleton.getMongoTemplate(MongoTemplateSingleton.java:13)
at com.nextage.arcacrmconnector.services.CommonMongoService.<init>(CommonMongoService.java:12)
at com.nextage.arcacrmconnector.services.LogService.<init>(LogService.java:18)
at com.nextage.arcacrmconnector.consumer.QueueConsumerTimerTask.<init>(QueueConsumerTimerTask.java:23)
at com.nextage.arcacrmconnector.application.Application.<clinit>(Application.java:30)
11:56:00.716 [Thread-0] WARN de.flapdoodle.embed.process.io.file.Files - could not delete C:\Users\DONATE~1\AppData\Local\Temp\extract-70ac2cd1-bb5b-4276-9243-cdf6b52db3famongod.exe. Will try to delete it again when program exits.
Exception in thread "Thread-0" java.lang.IllegalStateException: Shutdown in progress
at java.base/java.lang.ApplicationShutdownHooks.add(ApplicationShutdownHooks.java:66)
at java.base/java.lang.Runtime.addShutdownHook(Runtime.java:213)
at de.flapdoodle.embed.process.io.file.FileCleaner.forceDeleteOnExit(FileCleaner.java:51)
at de.flapdoodle.embed.process.io.file.Files.forceDelete(Files.java:128)
at de.flapdoodle.embed.process.extract.ExtractedFileSets.delete(ExtractedFileSets.java:77)
at de.flapdoodle.embed.process.store.ArtifactStore.removeFileSet(ArtifactStore.java:90)
at de.flapdoodle.embed.process.store.CachingArtifactStore$FilesWithCounter.forceDelete(CachingArtifactStore.java:176)
at de.flapdoodle.embed.process.store.CachingArtifactStore.removeAll(CachingArtifactStore.java:100)
at de.flapdoodle.embed.process.store.CachingArtifactStore$CacheCleaner.run(CachingArtifactStore.java:196)
at java.base/java.lang.Thread.run(Thread.java:830)
How can i fix it? It is a dependency version error?
String tempFile = System.getenv("temp") + File.separator + "extract-" + System.getenv("USERNAME") + "-extractmongod";
String executable;
if (System.getenv("OS") != null && System.getenv("OS").contains("Windows")) {
executable = tempFile + ".exe";
} else {
executable = tempFile + ".sh";
}
Files.deleteIfExists(new File(executable).toPath());
Files.deleteIfExists(new File(tempFile + ".pid").toPath());
please try this temporary solution. write this in mongo config file,This should be executed before the start of embedded mongo db
link is : https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo/issues/171

Spring boot data R2DBC requires transaction for read operations

Im trying to fetch a list of objects from the database using Spring boot Webflux with the postgres R2DBC driver, but I get an error saying:
value ignored org.springframework.transaction.reactive.TransactionContextManager$NoTransactionInContextException: No transaction in context Context1{reactor.onNextError.localStrategy=reactor.core.publisher.OnNextFailureStrategy$ResumeStrategy#7c18c255}
it seems all DatabaseClient operations requires to be wrap into a transaction.
I tried different combinations of the dependencies between spring-boot-data and r2db but didn't really work.
Version:
<spring-boot.version>2.2.0.RC1</spring-boot.version>
<spring-data-r2dbc.version>1.0.0.BUILD-SNAPSHOT</spring-data-r2dbc.version>
<r2dbc-releasetrain.version>Arabba-M8</r2dbc-releasetrain.version>
Dependencies:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
<version>${spring-data-r2dbc.version}</version>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-bom</artifactId>
<version>${r2dbc-releasetrain.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
fun findAll(): Flux<Game> {
val games = client
.select()
.from(Game::class.java)
.fetch()
.all()
.onErrorContinue{ throwable, o -> System.out.println("value ignored $throwable $o") }
games.subscribe()
return Flux.empty()
}
#Table("game")
data class Game(#Id val id: UUID = UUID.randomUUID(),
#Column("guess") val guess: Int = Random.nextInt(500))
Github repo: https://github.com/odfsoft/spring-boot-guess-game/tree/r2dbc-issue
I expect read operations to not require #Transactional or to run the query without wrapping into the transactional context manually.
UPDATE:
After a few tries with multiple version I manage to find a combination that works:
<spring-data-r2dbc.version>1.0.0.BUILD-SNAPSHOT</spring-data-r2dbc.version>
<r2dbc-postgres.version>0.8.0.RC2</r2dbc-postgres.version>
Dependencies:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
<version>${spring-data-r2dbc.version}</version>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
<version>${r2dbc-postgres.version}</version>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-bom</artifactId>
<version>Arabba-RC2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
it seems the versions notation went from 1.0.0.M7 to 0.8.x for r2dbc due to the following:
https://r2dbc.io/2019/05/13/r2dbc-0-8-milestone-8-released
https://r2dbc.io/2019/10/07/r2dbc-0-8-rc2-released
but after updating to the latest version a new problem appear which is that a transaction is required to run queries as follow:
Update configuration:
#Configuration
class PostgresConfig : AbstractR2dbcConfiguration() {
#Bean
override fun connectionFactory(): ConnectionFactory {
return PostgresqlConnectionFactory(
PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.username("root")
.password("secret")
.database("game")
.build())
}
#Bean
fun reactiveTransactionManager(connectionFactory: ConnectionFactory): ReactiveTransactionManager {
return R2dbcTransactionManager(connectionFactory)
}
#Bean
fun transactionalOperator(reactiveTransactionManager: ReactiveTransactionManager) =
TransactionalOperator.create(reactiveTransactionManager)
}
Query:
fun findAll(): Flux<Game> {
return client
.execute("select id, guess from game")
.`as`(Game::class.java)
.fetch()
.all()
.`as`(to::transactional)
.onErrorContinue{ throwable, o -> System.out.println("value ignored $throwable $o") }
.log()
}
Disclaimer this is not mean to be used in production!! still before GA.

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

NoSuchMethodError OWLDisjointClassesAxioms.getOperandAsList ()

NoSuchMethodError : org.semanticweb.owlapi.model.OWLDisjointClassesAxiom.getOperandsAsList()
I wanted to create an unsatisfiable class and list it using HermiT reasoner. I went through some sample codes and managed to write one.
Source Code:
package owlapi.tutorial;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.semanticweb.HermiT.ReasonerFactory;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.formats.OWLXMLDocumentFormat;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDisjointClassesAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.model.OWLSubClassOfAxiom;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
public class OWLAPIUnsatisfiableAssignment {
public static void main(String[] args) {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
IRI ontIri = IRI.create("http://owl.api.tutorial");
File fileOut = new File("src/main/resources/curriculum.owl");
try {
OWLOntology ont = manager.createOntology(ontIri);
OWLDataFactory df = ont.getOWLOntologyManager().getOWLDataFactory();
OWLClass student = df.getOWLClass(ontIri+"#Student");
OWLClass teacher = df.getOWLClass(ontIri+"#Teacher");
OWLClass demonst = df.getOWLClass(ontIri+"#Demonstrator");
/*
Set<OWLClass> disjoint = new HashSet<OWLClass>();
disjoint.add(student);
disjoint.add(teacher);
*/
OWLDisjointClassesAxiom disAx1 = df.getOWLDisjointClassesAxiom(student, teacher);
ont.add(disAx1);
OWLSubClassOfAxiom subAx1 = df.getOWLSubClassOfAxiom(demonst, df.getOWLObjectIntersectionOf(student, teacher));
ont.add(subAx1);
OWLReasonerFactory rf = new ReasonerFactory();
OWLReasoner r = rf.createReasoner(ont);
//Checking consistency of ontology
if(r.isConsistent()) {
System.out.println("The ontology is consistent");
}
else {
System.out.println("The ontology is inconsistent.Check the unsatisfiable classes below.");
}
r.getUnsatisfiableClasses().forEach(System.out::println);
manager.saveOntology(ont, new OWLXMLDocumentFormat(), new FileOutputStream(fileOut));
}
catch(OWLOntologyStorageException e) {
e.printStackTrace();
}
catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Console Output:
Exception in thread "main" java.lang.NoSuchMethodError: org.semanticweb.owlapi.model.OWLDisjointClassesAxiom.getOperandsAsList()Ljava/util/List;
at org.semanticweb.HermiT.structural.OWLNormalization$AxiomVisitor.visit(OWLNormalization.java:444)
at org.semanticweb.owlapi.model.OWLDisjointClassesAxiom.accept(OWLDisjointClassesAxiom.java:53)
at org.semanticweb.HermiT.structural.OWLNormalization.lambda$processAxioms$0(OWLNormalization.java:165)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.Collections$2.tryAdvance(Collections.java:4717)
at java.util.Collections$2.forEachRemaining(Collections.java:4725)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.semanticweb.HermiT.structural.OWLNormalization.processAxioms(OWLNormalization.java:165)
at org.semanticweb.HermiT.structural.OWLNormalization.processOntology(OWLNormalization.java:158)
at org.semanticweb.HermiT.structural.OWLClausification.preprocessAndClausify(OWLClausification.java:81)
at org.semanticweb.HermiT.Reasoner.loadOntology(Reasoner.java:212)
at org.semanticweb.HermiT.Reasoner.<init>(Reasoner.java:203)
at org.semanticweb.HermiT.Reasoner.<init>(Reasoner.java:177)
at org.semanticweb.HermiT.ReasonerFactory.createHermiTOWLReasoner(ReasonerFactory.java:51)
at org.semanticweb.HermiT.ReasonerFactory.createReasoner(ReasonerFactory.java:19)
at org.semanticweb.HermiT.ReasonerFactory.createReasoner(ReasonerFactory.java:15)
at owlapi.tutorial.X.main(X.java:50)
When I tried to go through the line numbers of the files, some were found out to be missing from the source attachment, eg:
java.util.stream.ForEachOps
java.util.stream.AbstractPipeLine
POM File:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>owlapi.tutorial</groupId>
<artifactId>msc</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>msc</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.owlapi</groupId>
<artifactId>owlapi-distribution</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.10</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.owlapi</groupId>
<artifactId>org.semanticweb.hermit</artifactId>
<version>1.4.1.513</version>
</dependency>
</dependencies>
</project>
I configured eclipse to use java-8-openjdk-amd64.I am new to OWLAPI and Java 8 stream. Can anyone explain what causes this problem and how to solve it?
Try upgrading owlapi-distribution to 5.1.3 or later as follows:
<dependency>
<groupId>net.sourceforge.owlapi</groupId>
<artifactId>owlapi-distribution</artifactId>
<version>5.1.3</version>
</dependency>
getOperandsAsList() has been introduced since 5.1.3 by this commit.

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>