How do I save an image into a mongoDB collection using Kmongo? - mongodb

I searched a lot today but all answers seem to be only in nodejs. I'm currently working on ktor application and I can't seem to find any way to upload images into MongoDB with KMongo.

You can use GridFS to store and retrieve binary files in MongoDB. Here is an example of storing an image, that is requested with the multipart/form-data method, in a test database:
import com.mongodb.client.gridfs.GridFSBuckets
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.litote.kmongo.KMongo
fun main() {
val client = KMongo.createClient()
val database = client.getDatabase("test")
val bucket = GridFSBuckets.create(database, "fs_file")
embeddedServer(Netty, port = 8080) {
routing {
post("/image") {
val multipartData = call.receiveMultipart()
multipartData.forEachPart { part ->
if (part is PartData.FileItem) {
val fileName = part.originalFileName as String
withContext(Dispatchers.IO) {
bucket.uploadFromStream(fileName, part.streamProvider())
}
call.respond(HttpStatusCode.OK)
}
}
}
}
}.start()
}
To make a request run the following curl command: curl -v -F image.jpg=#/path/to/image.jpg http://localhost:8080/image
To inspect stored files run db.fs_file.files.find() in the mongo shell.

Related

Error On Using Route53 ChangeResourceRecordSets

I'm currently using Grails 2.4.5 and used AmazonWebService plugin for grails 2.4.5
I'm trying to create a new recordset on route53 using this plugin.
On my BuildConfig.groovy I used this plugin fro aws web services.
compile ":aws-sdk:1.10.44"
I need your help guys regarding route53 change resource record sets.
I got an error below when I tried to change route53 resource record sets.
Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6). Stacktrace follows:
Message: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6)
This is my code.
import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional
#Transactional
class AwsRoute53Service {
AmazonWebService amazonWebService
ChangeResourceRecordSetsResult changeRecordSet() {
AmazonRoute53Client route53Client = amazonWebService.route53
AliasTarget target = new AliasTarget('hostedZoneIDHere', 'app.sample.com.')
target.setEvaluateTargetHealth(true)
List<ResourceRecord> resourceRecords = new ArrayList<>()
resourceRecords.add(new ResourceRecord('dNSNameHere'))
ResourceRecordSet recordSet = new ResourceRecordSet('app.sample.com.', RRType.A)
recordSet.setAliasTarget(target)
recordSet.setResourceRecords(resourceRecords)
recordSet.setTrafficPolicyInstanceId('simple')
List<Change> changes = new ArrayList<>()
changes.add(new Change(ChangeAction.CREATE, recordSet))
ChangeBatch changeBatch = new ChangeBatch(changes)
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest('hostedZoneIDHere', changeBatch)
return route53Client.changeResourceRecordSets(request)
}
}
Can you tell me what is the problem with the setup?
I would be glad if you can help me with my problem right now.
Thank you guys.
I already solve this problem. below is the working code.
import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional
#Transactional
class AwsRoute53Service {
private static final String DOMAIN_NAME_SERVER = "${System.env.DOMAIN_NAME_SERVER}"
private static final String HOSTED_ZONE_ID = "${System.env.HOSTED_ZONE_ID}"
AmazonWebService amazonWebService
ChangeResourceRecordSetsResult changeRecordSet() {
AmazonRoute53Client route53Client = amazonWebService.route53
GetHostedZoneResult hostedZoneResult = route53Client.getHostedZone(new GetHostedZoneRequest(HOSTED_ZONE_ID))
HostedZone hostedZone = hostedZoneResult.getHostedZone()
ResourceRecordSet resourceRecordSet = new ResourceRecordSet()
.withName('dNSName')
.withType(RRType.CNAME)
.withTTL(60)
.withResourceRecords([
new ResourceRecord().withValue(DOMAIN_NAME_SERVER)
])
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
.withHostedZoneId(hostedZone.id)
.withChangeBatch(
new ChangeBatch()
.withChanges([
new Change()
.withAction(ChangeAction.CREATE)
.withResourceRecordSet(resourceRecordSet)
])
)
return route53Client.changeResourceRecordSets(request)
}
}

Meteor + React: Can't get data from mongoDB Collection

I have a Meteor Application that I'm developing with React. I still have the autopublish package in my project (autopublish#1.0.7).
Here is my relevant code:
MainMenu.jsx
import React, { Component, PropTypes } from 'react'
import { Meteor } from 'meteor/meteor'
import { FlowRouter } from 'meteor/kadira:flow-router'
import { createContainer } from 'meteor/react-meteor-data'
import { ChatRooms } from '/imports/api/chatrooms.js'
export class MainMenu extends Component {
render() {
console.log(this.props.chatrooms)
return (
{/* Render stuff here is not part of the scope of this question */}
)
}
}
MainMenu.PropTypes = {
chatrooms: PropTypes.array.isRequired
}
export default createContainer(() => {
return {
chatrooms: ChatRooms.find({}).fetch()
}
}, MainMenu)
chatrooms.js
import { Mongo } from 'meteor/mongo'
export const ChatRooms = new Mongo.Collection('chatrooms')
The console.log(this.props.chatrooms) in the MainMenu Component always returns an empty array ([]).
There are definitely items in the Mongo Database because when I run the meteor mongo command in my console and type db.chatrooms.find({}); it returns the 3 items that I've inserted to test this all.
Anyone have any idea what I may be doing wrong here? Help would be much appreciated!
I've figured it out. I left out a crucial step of this whole process.
In my /server/main.js file I needed to add the following line which fixed everything:
import '../imports/api/chatrooms.js

Access the store finder _findQuery in ember-cli

I need to override the DS.Store.findQuery in Ember cli. that is no problem in itself.
The problem is importing the _findQuery method from the 'finder' file -- in that new app/store.js file
this._findQuery doesnt work
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/store.js
in the 'shimmed' component/ember-data
the prototype is
function ember$data$lib$system$store$finders$$_findQuery(adapter, store, typeClass, query, recordArray
Has anyone some advice on the required import statement.
here is some failed attempts
import DS from 'ember-data';
import Ember from 'ember';
//import _findQuery from 'ember-data/lib/system/store/finders'; NOPE
//import _findQuery from 'ember-data'; NOPE
export default DS.Store.extend({
findQuery: function(typeName, query) {
var type = this.modelFor(typeName);
var array = this.recordArrayManager
.createAdapterPopulatedRecordArray(type, query);
var adapter = this.adapterFor(type);
Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", typeof adapter.findQuery === 'function');
var x = _findQuery(adapter, this, type, query, array); // <-- URGH HERE
return promiseArray(x);
},
I'm not sure that you are able to import it in the way you describe, you could do it on the Adapter though.
You should be able to override it per Adapter, or if you want to do it everywhere, override on your application Adapter.
Like this
import DS from 'ember-data';
import Ember from 'ember';
export default DS.ActiveModelAdapter.extend({
findQuery (typeName, query) {
// do your stuff here
}
});

Import mongo_dart package stops text from displaying

The following code works just fine...simply displaying some JSON in an unordered list:
import 'dart:html';
import 'dart:convert';
main() {
// Db db = new Db("mongodb://127.0.0.1/mongo_dart-showjson");
querySelector("#sample_text_id")
..onClick.listen(showJSON);
}
void reverseText(MouseEvent event) {
var text = querySelector("#sample_text_id").text;
var buffer = new StringBuffer();
for (int i = text.length - 1; i >= 0; i--) {
buffer.write(text[i]);
}
querySelector("#sample_text_id").text = buffer.toString();
}
void showJSON(MouseEvent event) {
var path = 'hcps.json';
var hcpDisplay = querySelector('#json_length_id');
HttpRequest.getString(path).then((String fileContents) {
List<String> hcpList = JSON.decode(fileContents);
for (int i = 0; i < hcpList.length; i++) {
hcpDisplay.children.add(new LIElement()..text = hcpList[i].toString());
}
});
}
However, when I add an import statement for mongo-dart, the JSON is not displayed, though I do not receive an error:
import 'dart:html';
import 'dart:convert';
import 'package:mongo_dart/mongo_dart.dart';
main() {
Db db = new Db("mongodb://127.0.0.1/mongo_dart-showjson");
querySelector("#sample_text_id")
..onClick.listen(showJSON);
}
...
The mongo_dart package has been added to pubspec.yaml as a dependency.
Does anyone have an idea as to why importing the mongo_dart package would cause the json text not to display, though there is no error? Thank you in advance.
As stated in package readme
mongo-dart is a server-side driver library for MongoDb implemented in
pure Dart
.
It cannot work at client side. Main reason for that - browsers do not have real sockets to connect to databases like mongodb, mysql, postgress and so on. You may look at some database with a RESTful API like CouchDB. Or you should use some middleware - for example objectory.
You could try
import 'package:mongo_dart/mongo_dart.dart' as mdb;
main() {
mdb.Db db = new mdb.Db("mongodb://127.0.0.1/mongo_dart-showjson");
to see if there is a conflict
You could also add a try/catch block
try {
mdb.Db db = new mdb.Db("mongodb://127.0.0.1/mongo_dart-showjson");
} catch(e) {
print(e)
}
sometimes exceptions are swallowed due to the use of zones (might not help here though) but I think it's worth a try.
It is possible that the package cache directory is corrupted.
You could try
pub cache repair

No fields in scala class are set when returned from query

I have a Scala class, User:
class User {
#OId var id: String = _
var email: String = _
var password_hash: String = _
var password_salt: String = _
var admin : Boolean = _
#OVersion var version: String = _
}
I can successfully create and store User objects in the DB, but when I query for a User, e.g. db.queryBySql[User]("select * from User where email = ?", username)
I get a User object back, but all fields are null.
When stepping the code I can see the correct result from the DB, the POJO conversions is what fails.
I am using scala 2.9.2 and Orient DB 1.1.0.
What am I doing wrong?
I did the exemple explain at : http://code.google.com/p/orient/wiki/ScalaLanguage
This exemple uses the local connexion
var db: ODatabaseObjectTx = new ODatabaseObjectTx("local:/tmp/dbtmp")
I change a little the main app.
I change import to match with organisation of OrientDb packages.
import com.orientechnologies.orient.core.id.ORecordId
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery
import scala.collection.JavaConverters._
import scala.collection.JavaConversions._
import com.orientechnologies.orient.core.db.`object`.ODatabaseObject
import com.orientechnologies.orient.`object`.db.ODatabaseObjectTx
And, I change the way to open connexion.
Be careful ODatabaseObjectTx is deprecated.
I use db2 instead db after this snippet.
var db2:ODatabaseObject =
if (!db.exists) {
db.create()
} else {
db.open("admin", "admin")
}
I import these packages :
orient-commons:1.1.0
orientdb-core:1.1.0
orientdb-object:1.1.0
hibernate-jpa-2.0-api:1.0.0.Final
scala-library:2.9.2