According OrientDB official doc, I should create Connection Pool with Object API with following code.
// OPEN THE DATABASE
OObjectDatabaseTx db= OObjectDatabasePool.global().acquire("remote:localhost/petshop", "admin", "admin");
However, I found that OObjectDatabasePool class has been deprecated and suggested to use com.orientechnologies.orient.core.db.OPartitionedDatabasePool instead.
But in that way, how can I get OObjectDatabaseTx object? That is because OPartitionedDatabasePool.acquire() can only return ODatabaseDocumentTx object.
Hope there are someone knows how to resolve it.
Thanks
With this code you can get "object to connect to" and then make queries etc.
GET DOCUMENT DB
String remote = "remote:localhost/";
String nameDB = "domain";
String url = remote + nameDB;
OPartitionedDatabasePool pool = new OPartitionedDatabasePool(url, "admin", "admin");
ODatabaseDocumentTx db = pool.acquire();
//use example
List<ODocument> resultset = db.query(new OSQLSynchQuery<Object>("select from ORole"));
for(ODocument doc:resultset) {
System.out.println(doc);
}
db.close();
GET OBJECT DB
String remote = "remote:localhost/";
String nameDB = "TestPartitioned2";
String url = remote + nameDB;
OServerAdmin serverAdmin = new OServerAdmin(url).connect("root", "root");
serverAdmin.createDatabase(nameDB, "object", "plocal");
System.out.println(" Database '"+nameDB +"' created!..");
OPartitionedDatabasePool pool = new OPartitionedDatabasePool(url, "admin", "admin");
//object
OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire());
db.getEntityManager().registerEntityClass(Person.class);
Person personA = db.newInstance(Person.class);
personA.setName("tennantA");
db.save(personA);
db.close();
Related
i have following test in spring boot 2.7.7 with mongodb as a database sevices
// UserController.java
#GetMapping(value = "admin", produces = MediaType.APPLICATION_JSON_VALUE)
public String getAdmin () {
JSONObject report = new JSONObject();
String dataAdmin = userRepo.findByUsername("admin");
if(dataAdmin == null) {
User myadmin = new User();
myadmin.setUsername("admin");
myadmin.setFirstname("admin");
myadmin.setLastname("admin");
myadmin.setEmail("admin#admin");
myadmin.setRole("admin");
userRepo.save(myadmin);
report.put("message", "admin generated");
} else {
report.put("message", "admin only generated once");
}
return report.toString();
}
// AppTests.java
#Test
#DisplayName("generate admin")
void isertAdmin() throws IOException {
userRepo.deleteAll();
URL url = new URL("http://"+ addrHost +":8080/users/admin");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
String encoding = conn.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
MatcherAssert.assertThat(body, CoreMatchers.containsString("admin generated"));
}
#Test
#DisplayName("generate failed")
void isertAdminTwice() throws IOException {
URL url = new URL("http://"+ addrHost +":8080/users/admin");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
String encoding = conn.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
MatcherAssert.assertThat(body, CoreMatchers.containsString("admin only generated once"));
}
# docker-compose.yml
db:
container_name: database
image: mongo
restart: always
environment:
MONGO_INITDB_DATABASE: mydb
first testing is to generate new record data admin. I need to make sure there's no any previous document that contains the same record, so i decided to clean the collection before generate admin data when visiting users/admin.
the secound testing is almost similar with the first testing, but it doesnt clean the collection, so its designed to generate error report because the admin record already exist.
Above testing is running as expected when i run the program outside docker. But, when i run inside the docker, the second test failed because the data has been filled from my first test is not exist. In second test display error with actual result equals to first test.
I have a remote tenant database application using MongoDB with authentication enabled. During run-time, I have to programmatically create a new tenant database, create a new tenant database user, create a new collection, and write to the new database with user metadata. My problem is that I am not setting up the tenant user authorization correctly. I am able to create the new tenant database and a database user with role credentials "readWrite". I also can correctly write the document to the "users" collection. If I use my admin credentials, I can access the Tenant database and examine the users document with no issue. However, if I try to later access the database with the newly created database user credentials I get an incorrect user credentials exception. Below is my code that creates the new tenant database,
MongoCredential adminCredentials = MongoCredential
.createCredential(adminuid, admindb, adminpw.toCharArray());
ServerAddress adminSA = new ServerAddress(mongoConnectionUri, mongoPort);
// Create the Mongo Password Vault Client & Document Template
MongoClient adminclient = new MongoClient(adminSA, Arrays.asList(adminCredtials)):
MongoClient adminclient MongoClient(adminSA,Arrays.asList(adminCredentials));
DB tenant = adminclient.getDB(tenantdb);
// Create pwvdb user
DBObject pwvdbrole = new BasicDBObject();
pwvdbrole.put("role", pwvrole);
pwvdbrole.put("db", pwvdb);
ArrayList<DBObject> pwvdbroles = new ArrayList<DBObject>();
pwvdbroles.add(pwvdbrole);
DBObject pwvaultcmd = new BasicDBObject();
pwvaultcmd.put("createUser", pwvuid);
pwvaultcmd.put("pwd", pwvpw);
pwvaultcmd.put("roles", pwvdbroles);
CommandResult result = tenant.command(pwvaultcmd);
if (result.ok()) {
System.out.println("Tenant Credentials: OK");
} else {
System.out.println("Tenant Credentials Error: " +
result.getErrorMessage());
}
// Create users Collection
DBCollection tenantCollection =
tenant.getCollection(tenantcollection);
// Create user default credentials & update user collection
BasicDBObject userdocument = new BasicDBObject();
userdocument.put("firstname", userfirstname);
userdocument.put("lastname", userlastname);
userdocument.put("email", useremail);
userdocument.put("username", username);
userdocument.put("password", pwencoder.encode(userpassword));
userdocument.put("role", Integer.parseInt(userrole));
// Create admin web portal users uid/pw
tenantCollection.insert(userdocument);
pwvclient.close();
Because the client is remote, I use my admin userid, pw, and db for the credentials. However, the MongoDB tenant client is setup using the new tenant database name. This is probably where I am going wrong but I don't know how to remotely access the database with a user I have not created yet. These databases are created at run time and I do not know the name of the tenant user when the application starts.
there are two different places for user permissions to be created, which can be confusing. Both can be done dynamically in your code.
User roles in tenant DB
The easiest option is for you to create the user you want in the tenant DB. You should use the runCommand call with the document structure for the createUser command documented here. You would create this user in the tenant DB. The role should be readWrite or any others documented.
Then later you would authenticate for the user and password for that same DB.
You can also centralize all of your user management in the Admin DB with each createUser call enumerating the roles for each DB/role pair you want. Let me know if you need that explanation. It works basically the same way to create users there and authenticate against that DB also. Then you switch to the DB you want to access on the same MongoClient.
I could not post 2 other helpful links because of strange limitation on posting more than 2 links if I am not an active enough poster (10 reputation).
Here is what I did to get it to work. The two key things I want to point out is the adminops and testops MongoDB templates. Notice that in adminops I used my MongoDB admin credentials but pointed to the testdb. In testops I used my new testdb credentials and point to testdb as well. My error was with adminops. I used the admindb which was incorrect. Also getting the roleobj and cmd was a little tricky but I eventially figured it out.
package com.belcan;
import java.util.ArrayList;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class PreConfigTestApplication implements CommandLineRunner {
public static void main(String[] args) {
// Fire off Spring Boot & Embedded Linux
SpringApplication.run(PreConfigTestApplication.class, args);
}
#Override
public void run(String...args) throws Exception {
String testdb = "testdb";
String testuid = "skm";
String testpw = "password";
// Set up credentials
MongoCredential admincredentials = MongoCredential
.createCredential(adminuid, admindb, adminpw.toCharArray());
ServerAddress adminsa = new ServerAddress(mongoConnectionUri, mongoPort);
// Create the Mongo Client & Document Template
MongoClient adminclient = new MongoClient(adminsa,Arrays.asList(admincredentials));
MongoOperations adminops = new MongoTemplate(adminclient, testdb);
// First create new user
DBObject roleobj = new BasicDBObject();
roleobj.put("role", "readWrite");
roleobj.put("db", "testdb");
ArrayList<DBObject> array = new ArrayList<DBObject>();
array.add(roleobj);
DBObject cmd = new BasicDBObject();
cmd.put("createUser", testuid);
cmd.put("pwd", testpw);
cmd.put("roles", array);
// Create new User
CommandResult result = (CommandResult) adminops.executeCommand(cmd);
// check to see if command is ok
if (result.ok()) {
System.out.println("createUser Command: OK");
} else {
System.out.println("createUser Error:" + result.getErrorMessage());
}
// switch to testdb
MongoOperations testops = new MongoTemplate(adminclient, testdb);
// Create the user object
User user = new User();
user.setFirstname("mickey");
user.setLastname("mouse");
user.setEmail("mmouse#gmail.com");
user.setUsername("mmouse");
user.setPassword("mmouse1");
user.setRole("USER");
user.setStatus("ACTIVE");
// Now save it
testops.save(user, "users");
// Close Database Connection
adminclient.close();
//
// Now see if we can open the file with the new uid/pw
//
// Set up credentials
MongoCredential testcredentials = MongoCredential
.createCredential(testuid, testdb, testpw.toCharArray());
ServerAddress testsa = new ServerAddress(mongoConnectionUri, mongoPort);
// Create the Mongo Client & Document Template
MongoClient testclient = new MongoClient(testsa,Arrays.asList(testcredentials));
MongoOperations myops = new MongoTemplate(testclient, testdb);
User myuser = new User();
myuser.setFirstname("Daffy");
myuser.setLastname("Duck");
myuser.setEmail("dduck#gmail.com");
myuser.setUsername("dduck");
myuser.setPassword("dduck1");
myuser.setRole("USER");
myuser.setStatus("ACTIVE");
// Now save it
myops.save(myuser,"users");
// Lets print it out
System.out.println("Print Results");
ArrayList<User> userout = (ArrayList<User>) myops.findAll(User.class, "users");
for (int i = 0; i < userout.size(); i++) {
System.out.println(userout.get(i));
}
System.out.println("\n\nAll Done....");
// Close the database
testclient.close();
}
// MongoDB Connection URI
#Value("${spring.data.mongodb.uri}")
private String mongoConnectionUri;
// MongoDB Connection Port
#Value("${spring.data.mongodb.port}")
private int mongoPort;
// MongoDB userid
#Value("${mongo.server.admin.db}")
private String admindb;
// MongoDB admin password
#Value("${mongo.server.admin.pw}")
private String adminpw;
// MongoDB admin userid
#Value("${mongo.server.admin.uid}")
private String adminuid;
}
Previously I could use db.authenticate(String username, char[] password) method. With 2.13.0, how can I achieve this?
There is no replacement for db.authenticate(). The driver will use the credentials provided and make sure the connections are authenticated as they are created.
Based on this mongodb-user discussion the Java Driver team is open to discussions on what the real need for the db.authenticate(...) method.
Use
import com.mongodb.MongoCredential;
MongoCredential mongoCred =
MongoCredential.createMongoCRCredential(String username, String
dbName, char[] password);
and create mongoclient using mongocredentials
com.mongodb.MongoClient.MongoClient(List seeds, List
credentialsList, MongoClientOptions options)
We can have user-password based authentication for databases, in that case we need to provide authorization credentials like below for new version.
MongoCredential journaldevAuth = MongoCredential.createPlainCredential("pankaj", "journaldev", "pankaj123".toCharArray());
MongoCredential testAuth = MongoCredential.createPlainCredential("pankaj", "test", "pankaj123".toCharArray());
List<MongoCredential> auths = new ArrayList<MongoCredential>();
auths.add(journaldevAuth);
auths.add(testAuth);
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
MongoClient mongo = new MongoClient(serverAddress, auths);
If you are using older versions, you need to provide authentication details after getting the DB object like below
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("journaldev");
boolean auth = db.authenticate("pankaj", "pankaj123".toCharArray());
Trying to connect to mongoDB using MongoLab AddOn, I get the following error:
{ "$err" : "not authorized for query on myAppDB.Users", "code" : 13 }
when I run the following code:
private string connectionString = "mongodb://appharbor_93126661-e8b7-4986-958c-74e4ed8401e6:qj0boq192osh10rXXXXXXXX#ds027521.mongolab.com:27521/appharbor_93126661-e8b7-4986-958c-74e4ed8401e6";
private string dbName = "myAppDB";
private string userCollectionName = "Users";
private MongoCollection<User> GetUsersCollection()
{
MongoUrl url = new MongoUrl(connectionString);
MongoClient client = new MongoClient(url);
mongoServer = client.GetServer();
MongoDatabase database = mongoServer.GetDatabase(dbName);
MongoCollection<User> userCollection = database.GetCollection<User>(userCollectionName);
return userCollection;
}
I tried to connect from shell running the command:
mongo ds027521.mongolab.com:27521/appharbor_93126661-e8b7-4986-958c-74e4ed8401e6 -u appharbor_93126661-e8b7-4986-958c-74e4ed8401e6 -p qj0boq192osh10rXXXXXXXX
but also haven't managed to connect.
If anyone encountered similar issue or knows what is causing the problem I would be very thankful for any suggestion in prder to solve the problem.
When trying to update with mongodb by using the below code my result is getting null: in C#
public bool UpdateContact(string id, Contact item)
{
IMongoQuery query = Query.EQ("_id", id);
item.LastModified = DateTime.UtcNow;
IMongoUpdate update = Update
.Set("Email", item.Email)
.Set("LastModified", DateTime.UtcNow)
.Set("Name", item.Name)
.Set("Phone", item.Phone);
WriteConcernResult result = _contacts.Update(query, update);
return result.UpdatedExisting;
}
If you're not using the new connection style for the C# driver (and likely other drivers), your connection may be configured to not have a WriteConcern by default.
If there's no WriteConcern configured, the C# API will return a null as the result for the code you provided (see Update for more info)
For example, if your connection is like this:
var connectionString = "mongodb://localhost";
var server = MongoServer.Create(connectionString); // deprecated
var database = server.GetDatabase("test"); // WriteConcern defaulted to Unacknowledged
That would be configured to for no write concern.
You should be using this style (as of the C# 1.7 driver):
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test"); // WriteConcern defaulted to Acknowledged
The difference is that you need to use the MongoClient class (and get the MongoServer and the MongoDatabase from that object instance).