Mongeez - Adding user to database - java

I'm testing Mongeez, but am having trouble adding a user to the DB system.users collection.
My code is:
MongeezTest.java
Mongeez mongeez = new Mongeez();
mongeez.setFile(new ClassPathResource("mongeez.xml"));
mongeez.setMongo(new Mongo("127.0.0.1", 27018));
mongeez.setDbName("MongeezTest");
mongeez.setAuth(new MongoAuth("admin", "admin"));
mongeez.process();
test.javascript
// changeset mlysaght:ChangeSet-1
db.organization.insert({
"Name" : "10Gen", "Location" : "NYC", DateFounded : {}
});
db.organization.insert({
"Name" : "SecondMarket", "Location" : "NYC", DateFounded : {"Year" : 2004, "Month" : 05, "day" :04}
});
When I run my code I get:
Exception in thread "main" com.mongodb.CommandResult$CommandFailure:
command failed [getlasterror]: { "serverUsed" : "/127.0.0.1:27018" ,
"errmsg" : "need to login" , "ok" : 0.0}
For further details:
I have a MongoDB instance with active authentication.
Using uMongo, after running my Mongeez application I see that the DB gets created. If I manually add a user to the MongeezTest database, and rerun my application, the JS code gets executed.
How do I solve this?
Thanks

Related

Mongodb Unable to persist transaction state because the session transaction collection is missing

I'm using Mongodb 4 with spring boot 2.1.0-M4
The follwing code works locally on my computer, but fails at dev environment:
#Transactional
public void registerNewUser(UserRegistrationForm registrationForm)
throws IllegalArgumentException {
validator.validate(registrationForm);
User user = new User();
user.setEmail(registrationForm.email);
user.setPassword(encoder.encode(registrationForm.password));
user.setEnabled(false);
user.setGroups(Sets.newHashSet(ClientRoles.USER));
User saved = userRepository.save(user);
registrationService.sendInvitation(user.getEmail());
}
With the following error:
com.mongodb.MongoCommandException: Command failed with error 40527 (Location40527): 'Unable to persist transaction state because the session transaction collection is missing. This indicates that the config.transactions collection has been manually deleted.' on server mongodb-1-servers-vm-0:27017. The full response is { "operationTime" : { "$timestamp" : { "t" : 1540422989, "i" : 1 } }, "ok" : 0.0, "errmsg" : "Unable to persist transaction state because the session transaction collection is missing. This indicates that the config.transactions collection has been manually deleted.", "code" : 40527, "codeName" : "Location40527", "$clusterTime" : { "clusterTime" : { "$timestamp" : { "t" : 1540422994, "i" : 1 } }, "signature" : { "hash" : { "$binary" : "AAAAAAAAAAAAAAAAAAAAAAAAAAA=", "$type" : "00" }, "keyId" : { "$numberLong" : "0" } } } } at
I have no idea what I should try debugging, or what to try, both databases are of the same version and have replica sets initialized. Any help is appreciated.
Actually, the error is pretty self explanatory. It seems that for some reason transactions collection from dev environment db was deleted. The fix is straightforward:
use config
db.createCollection("transactions",{})

MongoDB Aggregation in Morphia

I am trying to map a successful MongoDB Aggregation to morphia but I am not able to get a satisfying result. I fails everytime but I cannot figure out why. Maybe someone of you could help me to state the aggregation correctly in morphia. My MongoDB Query looks like the following:
db.user.aggregate([{$match: { roles: "MEMBER" }}, {$group:{_id: "$roles", sum:{$sum: "$payments.2039.amount"}}}])
Roles is an array and the aggregation works fine and outputs:
{ "_id" : [ "MEMBER" ], "sum" : 100 }
I tried to do this in morphia with this java code:
final Query<User> query = datastore.createQuery(User.class).field("roles").in(Lists.newArrayList(Role.MEMBER));
final Iterator<AggregatePayments> aggregatePayments = datastore
.createAggregation(User.class)
.match(query)
.group("$roles", grouping("sum", sum("payments." + currentSeason + ".amount")))
.out(AggregatePayments.class);
But, unfortunately, this fails with the following exception:
com.mongodb.MongoCommandException: Command failed with error 17276 (Location17276): 'Use of undefined variable: roles' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "Use of undefined variable: roles", "code" : 17276, "codeName" : "Location17276" }
My problem is now finding out why this works in MongoDB but not in morphia. When I try to leave out the "$" at roles variable for _id in morphia I get the following exception:
com.mongodb.MongoCommandException: Command failed with error 16996 (Location16996): 'insert for $out failed: { connectionId: 1419, err: "can't use an array for _id", code: 2, codeName: "BadValue", n: 0, ok: 1.0 }' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "insert for $out failed: { connectionId: 1419, err: \"can't use an array for _id\", code: 2, codeName: \"BadValue\", n: 0, ok: 1.0 }", "code" : 16996, "codeName" : "Location16996" }
Any help appreciated! Thank you very much!
Using MongoDB version 3.6 and current morphia build 1.4-SNAPSHOT.
EDIT:
What seems really strange to me is that above Query in MongoDB works but the query generated by morphia not. But the manually edited Query in MongoDB and the generated one by morphia seem to correspond closely to another. Does anyone see any mistakes? Generated query is as follows:
11040 [qtp104739310-39] DEBUG org.mongodb.driver.protocol.command - Sending command '{ "aggregate" : "user", "pipeline" : [{ "$match" : { "roles" : { "$in" : ["MEMBER"] } } }, { "$group" : { "_id" : "$roles", "sum" : { "$sum" : "$payments.2039.amount" } } }, { "$out" : "AggregatePayments" }], "cursor" : { }, "$db" : "sua", "$readPreference" : { "mode" : "primaryPreferred" } }' with request id 19 to database sua on connection [connectionId{localValue:2, serverValue:1419}] to server localhost:27017
and produces the exception:
com.mongodb.MongoCommandException: Command failed with error 16996 (Location16996): 'insert for $out failed: { connectionId: 1419, err: "can't use an array for _id", code: 2, codeName: "BadValue", n: 0, ok: 1.0 }' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "insert for $out failed: { connectionId: 1419, err: \"can't use an array for _id\", code: 2, codeName: \"BadValue\", n: 0, ok: 1.0 }", "code" : 16996, "codeName" : "Location16996" }
When manually editing the query in MongoDB I can also use $group:{_id: "$roles".... Seems quite strange to me...
I didn't recognize the difference between morphia's "out()" and "aggregate()" method. "out()" changes the collection in the MongoDB store which was not intended. Using "aggregate()" now solved all problems:
final Query<User> query = datastore.createQuery(User.class).field("roles").in(Lists.newArrayList(Role.MEMBER));
final Iterator<AggregatePayments> aggregatePayments = datastore
.createAggregation(User.class)
.match(query)
.group("roles", grouping("sum", sum("payments." + currentSeason + ".amount")))
.aggregate(AggregatePayments.class);
Works now as expected with morphia 1.4.0-SNAPSHOT (most recent build from git master) and MongoDB 3.6.

Updating a field within matching Array in mongo

I recently switched from java mongo driver 3.1 to 3.4 in attempts to use Cosmo db api for mongo on azure. I am having issues with the driver when attempting to modify and field within an array.
My mongo Object looks like so
{
"_id" : ObjectId("5af4d4e97bad4700076d7aea"),
"URI" : "v3egoun#myip"
},
"record" : false,
"active" : true,
"audioonly" : true,
"environment" : "dev",
"participants" : [
{
"user" : "test1.medocity#test.org",
"state" : "pending",
"callid" : "null",
"host" : true
},
{
"user" : "test2.medocity#test.org",
"state" : "pending",
"callid" : "74ff79f83c375355058838a1b8d0ec03#test.org",
"host" : false
}
]
}
I wish to modify the variables for state and callid within the array for the user matching the query:
BasicDBObject query = new BasicDBObject();
query.put("URI", URI);
query.put("participants.user", FROMURI);
BasicDBObject data = new BasicDBObject();
data.put("participants.$.state", newstate.toString());
data.put("participants.$.callid", XMScallid);
BasicDBObject command = new BasicDBObject();
command.put("$set", data);
table.updateOne(query, command);
As of now I get the following error.
Exception in thread "Thread-13" com.mongodb.MongoWriteException: Invalid BSON field name 'participants.$.state'
Anyone have an Idea of how I can modify the state within the participants array for the user provided in the query?
Thanks

Delay While Retrieving Data From Firebase Database

It's a chat app. I am retrieving messages to show on the chat room recyclerview. For that I'm using FirebaseRecyclerAdapter. I'm retrieving latest 500 messages. And that chat room has over 20k messages.. When I load that activity it is taking 6 seconds to load all 500 messages.
I tracked the time.
The delay was between setAdapter and RecyclerAdapter class.
My Message Structure In Firebase Database
{
"-KlQc42ici0_PRCBX7-V" : {
"message" : "message 1",
"timestamp" : 1496185853436,
"type" : "action",
"username" : "berkleef2",
},
"-KlQmhcwK96j30FNoSs-" : {
"message" : "message 2",
"timestamp" : 1496188640000,
"type" : "action",
"username" : "atrickrodney16yahoocomat",
"zread" : true
},
"-KlQmjSoucJD7uaHriOh" : {
"message" : "message 3",
"timestamp" : 1496188647083,
"type" : "text",
"username" : "atrickrodney16yahoocomat",
"zread" : true
}
}
The Delay Started after setAdapter
mNewAdapter = new NewChatRecyclerAdapter(
ChatMessageItem.class,
R.layout.message_item,
RecyclerView.ViewHolder.class, ref.limitToLast(500), Fusername, booIsPrivateChat, chatd, strOpponent);
messageList.setAdapter(mNewAdapter);
I think there is no problem with the adapter class. So if the problem is with loading 500 messages. Then what should I do in this case to load chat messages...
Use Firebase Offline feature set persistence enabled on so that you can store your messages
You can fetch them in chunks of 20 or 50 messages one after another.
You can use keepsynced function given by firebase database on your database reference.

JSON Format Error-Amzon EC2 instance creation

i am doin Amazon Stack Creation through Java Eclipse.
tis below line of code is throwing the error
csr.setTemplateURL("https://s3.amazonaws.com/cloudformation-templates-us-east- 1/AutoScalingMultiAZSample.template");
I am getting the error as :
Caught Exception: Parameters: [KeyName] must have values (Service: AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: 9363d711-3535-11e4-8cf2-913ef42879cb)
Reponse Status Code: 400
my json template url is
https://s3.amazonaws.com/cloudformation-templates-us-east-1/AutoScalingMultiAZSample.template
Please help on this to detect the exact source of the error.
Ok i tried to validate your json schema using online validator.
http://jsonlint.com/
I just copied your json schema and pasted there. It said invalid schema expecting { on line 1. Ok for sure i have to put opening and closing brackets and in between your schema. But again it gave error. Extra Bracket } on last line. So i had to remove it. And then json schema was validated. It means somewhere in your schema you are putting an extra closing bracket }.
I think the place where you are making mistake is:
"InstanceSecurityGroup" : {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
"GroupDescription" : "Enable SSH access and HTTP from the load balancer only",
"SecurityGroupIngress" : [ {
"IpProtocol" : "tcp",
"FromPort" : "22",
"ToPort" : "22",
"CidrIp" : { "Ref" : "SSHLocation"}
},
{
"IpProtocol" : "tcp",
"FromPort" : { "Ref" : "WebServerPort" },
"ToPort" : { "Ref" : "WebServerPort" },
"SourceSecurityGroupOwnerId" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.OwnerAlias"]},
"SourceSecurityGroupName" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.GroupName"]}
} ]
}
}//Extra Bracket i think so
},
"Outputs" : {
"URL" : {
"Description" : "The URL of the website",
"Value" : { "Fn::Join" : [ "", [ "http://", { "Fn::GetAtt" : [ "ElasticLoadBalancer", "DNSName" ]}]]}
}
}
}

Categories

Resources