MongoDB java connection in Mongodb java driver 3.12.1 - java

I have mongodb 4.0 install in my Ubuntu 18.04.
I am using java-mongo-driver 3.12.1
I am uploading my code you can see that i have check different type of connections but it's not working.
How to solve this problem?

Give this a try, let me know what you think...
package test;
public class Main {
public static void main(String[] args) {
com.mongodb.client.MongoClient client = connectToStandAlone();
com.mongodb.client.MongoDatabase db = client.getDatabase("javatest");
QueryData(db);
}
private static com.mongodb.client.MongoClient connectToStandAlone() {
// STANDALONE STILL REQUIRES HOSTS LIST WITH ONE ELEMENT...
java.util.ArrayList<com.mongodb.ServerAddress> hosts = new java.util.ArrayList<com.mongodb.ServerAddress>();
hosts.add(new com.mongodb.ServerAddress("127.0.0.1", 27017));
com.mongodb.MongoCredential mongoCredential = com.mongodb.MongoCredential.createScramSha1Credential("testuser", "admin", "mysecret".toCharArray());
com.mongodb.MongoClientSettings mongoClientSettings = com.mongodb.MongoClientSettings.builder()
.applyToClusterSettings(clusterSettingsBuilder -> clusterSettingsBuilder.hosts(hosts))
.credential(mongoCredential)
.writeConcern(com.mongodb.WriteConcern.W1)
.readConcern(com.mongodb.ReadConcern.MAJORITY)
.readPreference(com.mongodb.ReadPreference.nearest())
.retryWrites(true)
.build();
com.mongodb.client.MongoClient client = com.mongodb.client.MongoClients.create(mongoClientSettings);
return client;
}
private static void QueryData(com.mongodb.client.MongoDatabase db) {
// DRIVER DOES NOT HAVE collection.findOne().
com.mongodb.client.MongoCollection<org.bson.Document> collection = db.getCollection("people");
com.mongodb.client.MongoCursor<org.bson.Document> cursor = collection.find(com.mongodb.client.model.Filters.eq("testfield", true))
.sort(new org.bson.Document("review_date", -1))
.skip(5)
.limit(20)
.iterator();
while(cursor.hasNext()) {
org.bson.Document document = cursor.next();
String json = document.toJson();
System.out.println(json);
boolean testfieldValue = document.getBoolean("testfield");
String ssnValue = document.getString("ssn");
}
}
}

I found simple solution.
I have added more jar files,in total we need (bson-3.12.1.jar, mongodb-driver-core-3.12.1.jar, mongodb-driver-sync-3.12.1.jar, mongodb-driver-sync-3.12.1-javadoc.jar). These are available in enter link description here
Now my code is working fine
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class MongoConnection {
public static void main(String[] args) {
try {
// Create Connection
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
System.out.println("MongoDB connected successfully");
//Accessing the database
MongoDatabase database = mongoClient.getDatabase("java");
System.out.println("MongoDB database connection ");
//Creating a collection
database.createCollection("first");
System.out.println("Collection created successfully");
//Accessing collection
MongoCollection<Document> collection = database.getCollection("first");
Document document = new Document("name", "Café Con Leche")
.append("contact", new Document("phone", "228-555-0149")
.append("email", "cafeconleche#example.com")
.append("location",Arrays.asList(-73.92502, 40.8279556)))
.append("stars", 3)
.append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));
collection.insertOne(document);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

How can I launch a UFT Mobile test script remotely from a java application?

I'm developing a java application that will be used to launch remotely the UFT Mobile scripts, on related server, download the test result from it and then analyze the report in order to save the results on a specific database.
I'm writing this post in order to ask a help about it.
The application will have the following steps:
A file properties where I read the name of scripts and some properties needed for application
A class that will be used to connect to the Mobile Center of UFT Mobile in order to install through Mobile Center API the application that will be under the test
A class that will connect to the server and start the execution of test script of application installed on step 2
Download the test result/logs in order to analyze the report and save the result on database
Step 2 (UFTLabUtils is a class of API related to Mobile Center):
package uft;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class UploadFile {
public static boolean uploadFile(Properties myPropertiesFile) throws IOException {
final String MC_SERVER = myPropertiesFile.getProperty("CLOUD_NAME").toLowerCase();
final String USERNAME = myPropertiesFile.getProperty("USERNAME");
final String PASSWORD = myPropertiesFile.getProperty("PASSWORD");
final String PACKAGE = myPropertiesFile.getProperty("PACKAGE");
final String VERSION = myPropertiesFile.getProperty("VERSION");
final String DEVICE_ID = myPropertiesFile.getProperty("DEVICE_ID");
final Boolean STRUMENTED = true;
try {
UFTLabUtils client = new UFTLabUtils(USERNAME, PASSWORD, MC_SERVER);
client.login(USERNAME, PASSWORD);
client.installApp(PACKAGE, VERSION, DEVICE_ID, STRUMENTED);
client.logout();
return true;
}catch(Exception e) {
System.err.println("Si è verificato un errore nella uploadFile: ");
String exc = ExceptionUtils.getStackTrace(e);
System.err.println(exc);
System.exit(-1);
return false;
}
}
}
The problem is on the step 3, where I cannot find a way to execute the script saved of UFT Mobile Server.
I'm looking on internet and I found some snippet code like this that I customized:
package uft;
import java.util.HashMap;
import java.util.Properties;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.client.utils.URIBuilder;
import org.json.JSONObject;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.ios.IOSDriver;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
public class StartExecution {
#SuppressWarnings("unused")
public static String startExecution(Properties myPropertiesFile) {
final String MC_SERVER = myPropertiesFile.getProperty("CLOUD_NAME");
final String MC_SERVER_CLIENT_ID = myPropertiesFile.getProperty("MC_SERVER_CLIENT_ID");
final String MC_SERVER_CLIENT_SECRET = myPropertiesFile.getProperty("MC_SERVER_CLIENT_SECRET");
final String MC_SERVER_TENANT_ID = myPropertiesFile.getProperty("MC_SERVER_TENANT_ID");
final String MC_SERVER_WORKSPACE_NAME = myPropertiesFile.getProperty("MC_SERVER_WORKSPACE_NAME");
try {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("oauthClientId", MC_SERVER_CLIENT_ID);
capabilities.setCapability("oauthClientSecret", MC_SERVER_CLIENT_SECRET);
capabilities.setCapability("tenantId", MC_SERVER_TENANT_ID);
capabilities.setCapability("mcWorkspaceName", MC_SERVER_WORKSPACE_NAME);
switch (myPropertiesFile.getProperty("OS").toUpperCase()) {
case "ANDROID":
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("appPackage", "com.Advantage.aShopping");
capabilities.setCapability("appActivity", "com.Advantage.aShopping.SplashActivity");
AndroidDriver wd = new AndroidDriver(new URL(MC_SERVER + "/wd/hub"), capabilities);
wd.executeScript(MC_SERVER_WORKSPACE_NAME, null);
HashMap<String, String> encoding= new HashMap<String, String>();
encoding.put("encoding", "UTF-8");
String logFileContents = (String) wd.executeScript("mc-wd: downloadLogs", encoding);
case "IOS":
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("bundleId", "com.Advantage.aShopping");
IOSDriver wd2 = new IOSDriver(new URL(MC_SERVER + "/wd/hub"), capabilities);
wd2.executeScript(MC_SERVER_WORKSPACE_NAME, null);
HashMap<String, String> encoding2= new HashMap<String, String>();
encoding2.put("encoding", "UTF-8");
String logFileContents2 = (String) wd2.executeScript("mc-wd: downloadLogs", encoding2);
}
return null;
}catch(Exception e) {
System.out.println("Si è verificato un problema nella startExecution: ");
String exc = ExceptionUtils.getStackTrace(e);
System.err.println(exc);
System.exit(-1);
return null;
}
}
All desired capabilities are read from external, in particular from the file properties that is in input to the java application.
The question is: after the connection to the mobile center, in particular, to the hub (wd/hub), how can I start and launch a test script that is saved on server (not in local)?
Furthermore, I looked the documentation about the method 'executeScript', but it is used to run a JavaScript code/command.
UPDATE: I also found this snippet:
public static void main(String args[]) {
try {
PrintStream out = new PrintStream(new FileOutputStream("LaunchQTP.vbs"));
out.println("Set qtApp = CreateObject(\"QuickTest.Application\")");
out.println("qtApp.Launch");
out.println("qtApp.Visible = True");
out.close();
Process p = Runtime.getRuntime().exec("cscript LaunchQTP.vbs");
p.waitFor();
out.println(p.exitValue());
} catch (Exception err) {
err.printStackTrace();
}
}
that seems to be used for launch a UFT scripts but on local machine. Could it be used also for remotely server? In this case how can i connect to the server and launch the script?
Thanks for supporting!

Retrieve WFS Map Content with Geotools in Java

I am trying to retrieve Map content via WFS Geoserver connection in Java with Geotools 18.4. But I am getting the following error: Content type is required for org.geotools.data.ows.Response.
The idea is that i want to map features (Position and Heartrate of a running person) of a WFS Layer with the java processing library.
I would be very grateful if someone can help me with this error.
here is the code:
`
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
public class Heartrate2 {
public static void main(String[] args) throws IOException {
Heartrate2 me = new Heartrate2();
DataStore ds = me.dataStoreWFS();
for (String n:ds.getTypeNames()) {
System.out.println(n);
}
}
public DataStore dataStoreWFS() {
DataStore dataStore = null;
try {
Map<String, Serializable> connectionParameters = new HashMap<>();
String getCapabilities = "http://webgis.regione.sardegna.it/geoserver/ows?service=WFS&request=GetCapabilities";
String variableCapabilities = "WFSDataStoreFactory:GET_CAPABILITIES_URL";
connectionParameters.put(variableCapabilities, getCapabilities);
dataStore = (new WFSDataStoreFactory()).createDataStore(connectionParameters);
} catch (IOException e) {
e.printStackTrace();
}
return dataStore;
}
}
`

Insert a document JSON from URL in mongodb with java

I'm new in MongoDb and I have to upload a file in MongoDB with a java program.
I tried to write something but I do not know if it's the right way.
Can someone help me?
My difficulty is that the json file I have to upload is in a link address.
can mongodb read and upload the document to a database through java language?
I load the code below.
Thank you.
import java.io.IOException;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
public class mongodb {
public static void main (String args []) throws IOException {
MongoClient mongo = null;
MongoDatabase db = null;
try {
/**** Connect to MongoDB ****/
mongo = new MongoClient("localhost", 27017);
/**** Get database ****/
db = mongo.getDatabase("db_plant");
System.out.println("Successfully connected to database");
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
DBCollection collection = db.getCollection("plants");
final String URL = "https://www.plants.usda.gov/java/downloadData?fileName=plantlst.txt&static=true";
String json = getTextFromUrl(URL);
DBObject dbObject = (DBObject)JSON.parse(json);
collection.insert(dbObject);
DBCursor cursorDocJSON = collection.find();
while (cursorDocJSON).hasNext() {
System.out.println(cursorDocJSON).next();
}
collection.remove(new BasicDBObject();
}
private static String getTextFromUrl(String uRL) {
// TODO Auto-generated method stub
return null;
}
}
You are using the old API.
If you use the Mongo java driver 3.X, the correct api is :
MongoCollection<Document> collection = database.getCollection("plants");
Document dbObject = Document.parse(json);
MongoCursor<Document> cursor = collection.find().iterator();

ContentModel cannot be resolved to a variable

I'm having this error :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
ContentModel cannot be resolved to a variable
at test2CMIS.Test.main(Test.java:39)"
And I dont understand from where it comes, here is my code :
public class Test {
public static void main(String[] args){
Test atest = new Test();
Session session = atest.iniSession();
AuthenticationService authenticationService=null;
PersonService personService = null;
if (authenticationService.authenticationExists("test") == false)
{
authenticationService.createAuthentication("test", "changeMe".toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, "test");
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "test"+"#example.com");
personService.createPerson(ppOne);
}
}
I did import the : import org.alfresco.model.ContentModel; and a lot of others librarys for my code.
Thx for help.
The code I'm using and I left some things that I tried too in comments so you can see what things I have done:
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.alfresco.service.cmr.security.*;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import java.util.Iterator;
import org.alfresco.repo.jscript.People;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.PropertyMap;
import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisContentAlreadyExistsException;
import org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException;
import org.apache.chemistry.opencmis.client.util.FileUtils;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
public class Test {
public static void main(String[] args){
Test atest = new Test();
Session session = atest.iniSession();
AuthenticationService authenticationService=new AuthenticationServiceImpl();
PersonService personService = new PersonServiceImpl();
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME, "test");
properties.put(ContentModel.PROP_FIRSTNAME, "test");
properties.put(ContentModel.PROP_LASTNAME, "qsdqsd");
properties.put(ContentModel.PROP_EMAIL, "wshAlors#gmail.com");
properties.put(ContentModel.PROP_ENABLED, Boolean.valueOf(true));
properties.put(ContentModel.PROP_ACCOUNT_LOCKED, Boolean.valueOf(false));
personService.createPerson(properties);
authenticationService.createAuthentication("test", "changeme".toCharArray());
authenticationService.setAuthenticationEnabled("test", true);
authenticationService.getAuthenticationEnabled("Admin");
//String testAuthen = authenticationService.getCurrentTicket();
//System.out.println(testAuthen);
//QName username = QName.createQName("test");
//Map<QName,Serializable> propertiesUser = new HashMap<QName,Serializable>();
//propertiesUser.put(ContentModel.PROP_USERNAME,username);
//propertiesUser.put(ContentModel.PROP_FIRSTNAME,"test");
//propertiesUser.put(ContentModel.PROP_LASTNAME,"test");
//propertiesUser.put(ContentModel.PROP_EMAIL, "test#example.com");
//propertiesUser.put(ContentModel.PROP_PASSWORD,"0000");
//personService.createPerson(propertiesUser);
//if (authenticationService.authenticationExists("test") == false)
//{
// authenticationService.createAuthentication("test", "changeMe".toCharArray());
// PropertyMap ppOne = new PropertyMap(4);
// ppOne.put(ContentModel.PROP_USERNAME, "test");
// ppOne.put(ContentModel.PROP_FIRSTNAME, "test");
// ppOne.put(ContentModel.PROP_LASTNAME, "test");
// ppOne.put(ContentModel.PROP_EMAIL, "test#example.com");
//ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
// personService.createPerson(ppOne);
//}
}
public Session iniSession() {
Session session;
SessionFactoryImpl sf = SessionFactoryImpl.newInstance();
Map<String, String> parameters = new HashMap<String, String>();
Scanner reader = new Scanner(System.in);
System.out.println("Enter your logging : ");
String log = reader.nextLine();
System.out.println("Enter your password : ");
String pass = reader.nextLine();
parameters.put(SessionParameter.USER, log);
parameters.put(SessionParameter.PASSWORD, pass);
parameters.put(SessionParameter.BROWSER_URL, "http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/browser");
parameters.put(SessionParameter.BINDING_TYPE, BindingType.BROWSER.value());
parameters.put(SessionParameter.REPOSITORY_ID, "-default-");
try{
session = sf.createSession(parameters);
}catch(CmisUnauthorizedException cue){
session = null;
System.out.println("Wrong logging OR password !");
}
return session;
}
You are writing a runnable class which is not running the same process as Alfresco. In that sense, your class is running "remotely".
Because your class is running remotely to Alfresco, you are correct in using CMIS. But CMIS will only allow you to perform Create, Read, Update, and Delete (CRUD) functions against documents and folders in Alfresco. CMIS does not know how to create users or groups.
Your class will not be able to instantiate the AuthenticationService or PersonService. Those are part of the Alfresco Foundation API which only works when you are running in the same process as Alfresco, such as in an Action, a Behavior, or a Java-backed web script. In those cases, you will use Spring Dependency Injection to inject those services into your Java class. You would then put your class in a JAR that gets deployed into the Alfresco web application and loaded by the same classloader as Alfresco's.
If you want to create users remotely you should consider using the Alfresco REST API. Your runnable class can then use an HTTP client to invoke REST calls to create people and groups.
Thanks you for everything ! Thanks to you and researches I found out how to do it ! For the others who wonder how to do I'll post how I did and what site I used to understand it !
So you just need to manipulate JSON with Java because your alfresco people page (127.0.0.1:8080/alfresco/service/api/people) returns a JSON object, and you'll be able to create, delete, search... users! Thx again !
Sites :
https://api-explorer.alfresco.com/api-explorer/#/people
http://crunchify.com/json-manipulation-in-java-examples/
The code :
This is for creating an user :
public User createUser(String firstN, String lastN, String email, String pass, String authTicket) throws Exception{
try{
String url = "http://127.0.0.1:8080/alfresco/service/api/people?alf_ticket="+authTicket;
HttpClient httpclient = new HttpClient();
PostMethod mPost = new PostMethod(url);
//JSONObject obj = new JSONObject();
//JSONArray people = obj.getJSONArray("people");
JSONObject newUser = new JSONObject();
newUser.put("userName", firstN.toLowerCase().charAt(0)+lastN.toLowerCase());
newUser.put("enabled",true);
newUser.put("firstName",firstN);
newUser.put("lastName", lastN);
newUser.put("email", email);
newUser.put("quota",-1);
newUser.put("emailFreedDisable",false);
newUser.put("isDeleted",false);
newUser.put("isAdminAuthority",false);
newUser.put("password", pass);
//people.put(newUser);
//Response response = PostRequest(newUser.toString()));
StringRequestEntity requestEntity = new StringRequestEntity(
newUser.toString(),
"application/json",
"UTF-8");
mPost.setRequestEntity(requestEntity);
int statusCode2 = httpclient.executeMethod(mPost);
mPost.releaseConnection();
}catch(Exception e){
System.err.println("[ERROR] "+e);
}
return new User(firstN, lastN);
}
And if you want to get all the users you have on alfresco :
public ArrayList<User> getAllUsers(String authTicket)
{
ArrayList<User> allUsers = new ArrayList<>();
String lastName, firstName;
try{
String url = "http://127.0.0.1:8080/alfresco/service/api/people?alf_ticket="+authTicket;
HttpClient httpclient = new HttpClient();
GetMethod mPost = new GetMethod(url);
int statusCode1 = httpclient.executeMethod(mPost);
System.out.println("statusLine >>> "+statusCode1+"....."
+"\n status line \n"
+mPost.getStatusLine()+"\nbody \n"+mPost.getResponseBodyAsString());
JSONObject obj = new JSONObject(mPost.getResponseBodyAsString());
JSONArray people = obj.getJSONArray("people");
int n = people.length();
for(int i =0 ; i < n ; i++)
{
JSONObject peoples = people.getJSONObject(i);
User u = new User(peoples.getString("firstName"), peoples.getString("lastName"));
if (!allUsers.contains(u)){
allUsers.add(u);
}
}
}catch(Exception e){
System.err.println("[ERROR] "+e);
}
return(allUsers);
}

Credentials Java application connect to google cloud datastore

I am writing a local java application which is to access my google datastore. I followed the tutorial here http://googlecloudplatform.github.io/gcloud-java/0.2.0/index.html
This is my basic code
package myproject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.google.cloud.AuthCredentials;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyFactory;
public class Main {
private String projID = "myID";
public static void main(String[] args) throws IOException {
System.out.println("correct");
Main test = new Main();
Datastore dstore = test.getDatastore();
KeyFactory keyFactory = dstore.newKeyFactory().kind("keyKind");
Key key = keyFactory.newKey("keyName");
Entity entity = Entity.builder(key)
.set("name", "John Doe")
.set("age", 30)
.build();
dstore.put(entity);
}
private Datastore getDatastore() throws IOException {
File file = new File("./resource/mycredential.json");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
} catch (IOException e) {
e.printStackTrace();
}
DatastoreOptions options = DatastoreOptions.builder()
.projectId(projID)
.authCredentials(AuthCredentials.createForJson(fis)).build();
Datastore datastore = options.service();
return datastore;
}
}
I created the json credential key from cloud console. After I run the program, it shows com.google.datastore.v1beta3.client.DatastoreFactory makeClient
??: Not using any credentials
I am really trapped here. How to create the right credential and use it correctly?
Thanks in advance.
This is "INFO" message which means nothing. I agree that it's confusing, but this message shows up every time I start my local program, which works fine - connects to the Datastore, retrieves and saves data, etc.

Categories