Delete operation is failing to delete a document in mongo using groovy in Jmeter - mongodb

IAm trying to delete a document i created through my script using deleteone as well as deletemany using following code:
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import static com.mongodb.client.model.Filters.*;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.Arrays;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
try {
String mongoUser = vars.get("mongouser");
String userDB = vars.get("userdb");
char[] password = vars.get("password").toCharArray();
MongoCredential credential = MongoCredential.createCredential(mongoUser, userDB, password);
MongoClientSettings settings = MongoClientSettings.builder()
.applyToClusterSettings {builder ->
builder.hosts(Collections.singletonList(new ServerAddress(vars.get("mongohost"), vars.get("mongoPort") as int)))}
.credential(credential)
.build();
MongoClient mongoClient = MongoClients.create(settings);
MongoDatabase database = mongoClient.getDatabase(vars.get("databaseName"));
MongoCollection<Document> collection = database.getCollection(vars.get("collectionName1"));
vars.putObject("collection1", collection);
collection.deleteone(eq("EmployeeName", "Test Automation through Jmeter"));
return "Document deleted";
}
catch (Exception e) {
SampleResult.setSuccessful(false);
SampleResult.setResponseCode("500");
SampleResult.setResponseMessage("Exception: " + e);}
getting this error:
Response message: Exception: groovy.lang.MissingMethodException: No signature of method: com.mongodb.client.internal.MongoCollectionImpl.deleteone() is applicable for argument types: (com.mongodb.client.model.Filters$
SimpleEncodingFilter) values: [Filter{fieldName='EmployeeName', value=Test Automation through Jmeter}]
Possible solutions: deleteOne(org.bson.conversions.Bson), deleteOne(com.mongodb.client.ClientSession, org.bson.conversions.Bson), deleteOne(org.bson.conversions.Bson, com.mongodb.client.model.DeleteOptions), deleteOne(com.mongodb.client.ClientSession, org.bson.conversions.Bson, com.mongodb.client.model.DeleteOptions), deleteMany(org.bson.conversions.Bson), deleteMany(com.mongodb.client.ClientSession, org.bson.conversions.Bson)
What am I doing wrong?

I believe the method is called deleteOne, not deleteone, so the correct way to call it should be:
collection.deleteOne(eq("EmployeeName", "Test Automation through Jmeter"));
See also the javadocs for the MongoCollection: https://mongodb.github.io/mongo-java-driver/3.6/javadoc/?com/mongodb/client/MongoCollection.html

Related

Unable to start Appium server programmatically

I am trying to start the Appium server using Appium service builder but am getting the following error. I tried everything but still get the error.
AppiumTest
io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException: The local appium server has not been started. The given Node.js executable: C:\Program Files\nodejs\node.exe Arguments: [C:\Users\[username]\AppData\Roaming\npm\node_modules\appium\build\lib\main.js, --port, 4723, --address, 127.0.0.1]
at io.appium.java_client.service.local.AppiumDriverLocalService.start(AppiumDriverLocalService.java:191)
package MahiyarAutomation;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
public class AppiumBasics {
#Test
public void AppiumTest() throws MalformedURLException
{
AppiumDriverLocalService service = new AppiumServiceBuilder().withAppiumJS(new File("C:\\Users\\mahiyarwadia\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"))
.withIPAddress("127.0.0.1").usingPort(4723).build();
service.start();
UiAutomator2Options options = new UiAutomator2Options();
options.setDeviceName ("MahiyarPhone");
options.setApp ("//Users//mahiyarwadia//eclipse-workspace//Appium//src//test//java//resources//ApiDemos-debug.apk");
}
}
Could you try the following?
AppiumServiceBuilder builder = new AppiumServiceBuilder()
.withAppiumJS(new File("C:\\Users\\mahiyarwadia\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"))
.withIPAddress("127.0.0.1")
.usingPort(4723);
AppiumDriverLocalService service = AppiumDriverLocalService.buildService(builder);
service.start();
If it still does not work:
Are you able to start the server via the GUI or command line?
Is the Appium path correct?

Micronaut + Vertx + testcontainers

How do I configure Micronaut app using Vert.x and testcontainers? I'm trying:
application-test.yml
datasources:
default:
url: jdbc:tc:mysql:8:///db
driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver
vertx:
mysql:
client:
uri: jdbc:tc:mysql:8:///db
Tests with micronaut-data-jdbc work, but with micronaut-vertx-mysql-client not work:
Error:
Message: Cannot parse invalid connection URI: jdbc:tc:mysql:8:///db
I'm not very familiar with testecontainers, but it seems like it doesn't come up with a fixed port, so I don't know how to configure the connection URI.
Thanks!
It might be a problem that micronaut-vertx-mysql-client does not support the Testcontainers JDBC URL scheme (hard to say without further logs).
In this case, I would suggest to use Testcontainers with database container objects instead of the special JDBC URL.
I got a solution to the problem:
Micronaut + jdbc hikari + vertx mysql client + flyway mysql
package br.com.app;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.env.PropertySource;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.client.HttpClient;
import io.micronaut.runtime.EmbeddedApplication;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
#Testcontainers
class AuthTest {
static Logger log = LoggerFactory.getLogger(AuthTest.class.getName());
#Container
static MySQLContainer mysql = new MySQLContainer("mysql:8");
private HttpClient client;
private static EmbeddedApplication application;
private static ApplicationContext context;
#BeforeAll
public static void initTests(){
log.info("Mysql is running {}, port {}", mysql.isRunning(), mysql.getFirstMappedPort());
var port = mysql.getFirstMappedPort();
var host = mysql.getHost();
var database = mysql.getDatabaseName();
var user = mysql.getUsername();
var password = mysql.getPassword();
var url = String.format("jdbc:mysql://%s:%s/%s", host, port, database);
application = ApplicationContext.run(EmbeddedApplication.class,
PropertySource.of(
"test",
CollectionUtils.mapOf(
"vertx.mysql.client.port", port,
"vertx.mysql.client.host", host,
"vertx.mysql.client.database", database,
"vertx.mysql.client.user", user,
"vertx.mysql.client.password", password,
"datasources.default.url", url,
"datasources.default.username", user,
"datasources.default.password", password,
"flyway.datasources.default.enabled", true
)
));
context = application.getApplicationContext();
}
#BeforeEach
void beforeEach(){
this.authService = context.getBean(AuthService.class);
this.client = context.getBean(HttpClient.class);
}
#Test
void testItWorks() {
Assertions.assertTrue(application.isRunning());
}
// api tests
}
Help links:
https://dev.to/major13ua/micronaut-integration-testing-using-testcontainers-2e30
https://github.com/major13ua/micronaut-tc/blob/main/src/test/java/com/example/testcontainer/controller/DemoControllerTest.java

Upload documents with OPENTEXT REST API not working

I'm new to the OPENTEXT Rest API and while I'm able to authenticate/create folders using it, I can't get the document upload to work. The following is the code I've been using:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
URIBuilder builder = new URIBuilder(https://bla.com/<restapiroot/v2/nodes");
builder.setParameter("type", "144")
.setParameter("parent_id", "123456")
.setParameter("name", "bla.pdf")
.setParameter("file", "C:\\My_Data\\bla.pdf");
MultipartEntityBuilder multiPartBuilder = MultipartEntityBuilder.create();
multiPartBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multiPartBuilder.addBinaryBody("ufile", new File (fullFileName), ContentType.DEFAULT_BINARY, fileName);
multiPartBuilder.setBoundary("aall12dk##Joey");
HttpPost httpPostRequest = new HttpPost(builder.build());
httpPostRequest.addHeader( "<auth code name>", "value" );
httpPostRequest.addHeader( HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=aall12dk##Joey" );
httpPostRequest.addHeader( "Content-Disposition", "attachment;filename=" + "bla.pdf" );
httpPostRequest.setEntity(multiPartBuilder.build());
HttpResponse response = = httpClient.execute(httpPostRequest);
I get the following error:
00:47:47.694 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "{"error":"Could not process object, invalid action \u0027create\u0027"}"
00:47:47.695 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 500 Internal Server Error
I'm not sure if I'm invoking the API wrong and/or whether I'm coding the file upload logic wrong entirely. Any help would be greatly appreciated.
Thank you
I got the solution for this. Basically, the answer is to use only a generic URIBuilder. Everything else goes to the multi-part builder:
URIBuilder builder = new URIBuilder("https://bla.com/<restapiroot>/v2/nodes");
MultipartEntityBuilder multiPartBuilder = MultipartEntityBuilder.create();
multiPartBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multiPartBuilder.setBoundary("aall12dk##RandomBoundary2019"); //Random value basically.
multiPartBuilder.addPart("type", new StringBody(String.valueOf(LAPI_DOCUMENTS.DOCUMENTSUBTYPE), ContentType.MULTIPART_FORM_DATA));
multiPartBuilder.addPart("parent_id", new StringBody(String.valueOf(parentId), ContentType.MULTIPART_FORM_DATA));
multiPartBuilder.addPart("name", new StringBody(fileName, ContentType.MULTIPART_FORM_DATA));
multiPartBuilder.addPart("file", new FileBody(new File (fullFileName), ContentType.DEFAULT_BINARY));
multiPartBuilder.addPart("description", new StringBody(comments, ContentType.MULTIPART_FORM_DATA));
multiPartBuilder.addPart("external_create_date", new StringBody("2017-12-10", ContentType.MULTIPART_FORM_DATA));
multiPartBuilder.addPart("external_modify_date", new StringBody(LocalDate.now().toString(), ContentType.MULTIPART_FORM_DATA));
multiPartBuilder.addPart("external_source", new StringBody("ftp", ContentType.MULTIPART_FORM_DATA));
HttpPost httpPostRequest = new HttpPost(builder.build());
httpPostRequest.addHeader("<TicketHeaderName>", "<ticket value>");
httpPostRequest.setEntity(multiPartBuilder.build());
HttpResponse response = httpClient.execute(httpPostRequest); //need to assign response to variable or you'll end up with hanging connections.
if ( response.getStatusLine().getStatusCode() != 200 ) {
//Error handling logic
}

How to externalize mongo db queries

I want to externalize complete mongo db query.
I know that we can externalize by splitting query into $project, $filter ,$sort and so on...
But I want the whole query to be externalized.
For example,
db.employee.find({dept:'FINANCE'},{empId:1,empName:1,empDesn:1}).sort({empSal:1}),
Here I want to externalize this mongo query, please share your thought how to achieve it using java.
I connect to mongodb using java for read and right. We use mongo-java-driver-2-XX.jar to connect it
sample code is :
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
For more details check this link

Issue in sending a SOAP request in ApacheHttpClient with SSL

I want to send a SOAP request through SSL to SOAP server (Microsoft IIS server). When I test the SOAP request through the soapUI tool with SSL - Keystore configurations it returns response correctly. But Using following code it returns "HTTP/1.1 400 Bad Request"
I used httpclient-4.2.3 and httpcore-4.2.2.
import java.security.KeyStore;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream instream1 = new FileInputStream(new File("C:\\CCDKeyStore\\mykeystore.jks"));
try {
keyStore.load(instream1, "1214524".toCharArray());
} finally {
try { instream1.close(); } catch (Exception ignore) {}
}
SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,"1214524");
Scheme sch = new Scheme("https", 443, socketFactory);
SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
schemeRegistry.register(sch);
final HttpParams httpParams = new BasicHttpParams();
DefaultHttpClient lHttpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams);
String lUrl = "https://api.demo.server.com/XDS/Service.svc?wsdl";
StringBuffer lXmlBuffer = new StringBuffer();
lXmlBuffer.append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">\n");
lXmlBuffer.append("<s:Header>\n");
lXmlBuffer.append("<a:Action s:mustUnderstand=\"1\">urn:74347:4757:StoredQuery</a:Action>\n");
lXmlBuffer.append("<a:MessageID>urn:uuid:c6430690-412e-4744-afe1-233e2138f2d2</a:MessageID>\n");
.
.
.
.
.
.
lXmlBuffer.append("</Slot>\n");
lXmlBuffer.append("</AdhocQuery>\n");
lXmlBuffer.append("</query:AdhocQueryRequest>\n");
lXmlBuffer.append("</s:Body>\n");
lXmlBuffer.append("</s:Envelope>\n");
String lXml = lXmlBuffer.toString();
HttpPost lMethod = new HttpPost(lUrl);
HttpEntity lEntity = new StringEntity(lXml, "multipart/related", "utf-8");
lMethod.setHeader("SOAPAction", "urn:74347:4757:StoredQuery");
System.out.println(EntityUtils.toString(lEntity));
lMethod.setEntity(lEntity);
HttpResponse lHttpResponse = lHttpClient.execute(lMethod);
} finally {
httpclient.getConnectionManager().shutdown();
}
Any help on this highly appreciate
Thanks,
Mohan
Finally I found the answer...
Here the following line in above code contains content type as "multipart/related". But web service is expected the content type "application/soap+xml" since this is SOAP request. Please refer w3schools tutorial for further information
HttpEntity lEntity = new StringEntity(lXml, "multipart/related", "utf-8");