No fields in scala class are set when returned from query - scala

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

Related

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

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.

Redirect in Scala play framework

I have a problem with Redirect in Scala play framework.
How can I redirect to view BooksController.index() ? In documentation they suggest to use Redirect but I don't know how.
def edit(Id: Int) = Action {
val book: Book = Book.findById(Id)
Ok(views.html.edit())
}
def update = Action {
implicit request =>
val (id, title, price, author) = bookForm.bindFromRequest.get
val book: Book = Book.findById(id)
book.id = id
book.title = title
book.price = price
book.author = author
Redirect(routes.BooksController.index())
}
Now can recognize --> import play.api.mvc.Results._
But i have an error --> "object java.lang.ProcessBuilder.Redirect is not a value"
If you would really like to continue using reverse routing in your code instead of having string uri values all over the place, see this:
Redirect with Bad Request Status.
The Redirect function accepts only a String or Call.
Try the following steps:
0) Add in the BookController
import play.api.mvc._
1) Add the following string in your route config file(hard disk location: controllers/BooksController)
GET /redirectedPage controllers.BooksController.index
2) Define a variable in the BookController
val Home = Redirect(routes.BookController.index())
3) Describe in the BookController
def update = Action {
implicit request => Home
}
Also do "sbt clean; sbt compile" to recompile auto-calls in ReverseRoutes.scala.
Well done.
The last line in the update action is the Redirect call which redirects to BooksController index route
import play.api.mvc.Results._
Redirect(routes.BooksController.index())

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
}
});

The requested built-in library is not available on Dartium

I am trying to make a very simple application that looks up values in a database by using polymer elements to get input.
My main polymer class looks like this:
library index;
import 'package:polymer/polymer.dart';
import 'lookup.dart';
import 'dart:html';
#CustomTag('auth-input')
class AuthInput extends PolymerElement {
#observable String username = '';
#observable String password = '';
AuthInput.created() : super.created();
void login(Event e, var detail, Node target)
{
int code = (e as KeyboardEvent).keyCode;
switch (code) {
case 13:
{
Database.lookUp(username, password);
break;
}
}
}
}
and a secondary database helper class looks like this:
library database;
import 'package:mongo_dart/mongo_dart.dart';
class Database {
static void lookUp(String username, String password) {
print("Trying to look up username: " + username + " and password: " + password);
DbCollection collection;
Db db = new Db("mongodb://127.0.0.1/main");
db.open();
collection = db.collection("auth_data");
var val = collection.findOne(where.eq("username", username));
print(val);
db.close();
}
}
I keep getting this error and I cannot think of a way around it:
The requested built-in library is not available on Dartium.'package:mongo_dart/mongo_dart.dart': error: line 6 pos 1: library handler failed
import 'dart:io';
The strange thing is, I don't want to use dart:io. The code works fine either running database processes or running polymer processes. I can't get them to work together. I don't see why this implementation of the code will not run.
The first line at https://pub.dartlang.org/packages/mongo_dart says
Server-side driver library for MongoDb implemented in pure Dart.
This means you can't use it in the browser. Your error message indicates the same. The code in the package uses dart:io and therefore can't be used in the browser.
Also mongodb://127.0.0.1/main is not an URL that can be used from within the browser.
You need a server application that does the DB access and provides an HTTP/WebSocket API to your browser client.

Play: add a global optional GET parameter to all routes

I have a Play 2.0 framework that is working well and I want to be able to add a specific get parameter (known only by be) to all routes. That parameters should be ignore by routes.
I explain.
Suppose I have routes like :
GET /add/:id controllers.MyController.add(id : Int)
GET /remove/:id controllers.MyController.remove(id : Int)
What I want is, for example, that http://mydomain.com/add/77?mySecretParam=ok still goes to controllers.MyController.add(id : Int) and then I could get mySecretParam in request object. And the same for all my routes.
Do you have any idea how can I do ?
Thanks.
Greg
package controllers
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
object Application extends Controller {
def mySecretParam(implicit request: Request[_]): Option[String] = {
val theForm = Form(of("mySecretParam" -> nonEmptyText))
val boundForm = theForm.bindFromRequest
if(!boundForm.hasErrors)
Option(boundForm.get)
else
None
}
def index = Action { implicit request=>
Ok(views.html.index(mySecretParam.getOrElse("the default")))
}
}
Here's Java:
Your route
GET /hello/:id controllers.Application.hello(id: Int)
in Application controller
public static Result hello(int id){
//Retrieves the current HTTP context, for the current thread.
Context ctx = Context.current();
//Returns the current request.
Request req = ctx.request();
//you can get this specific key or e.g. Collection<String[]>
String[] param = req.queryString().get("mySecretParam");
System.out.println("[mySecretParam] " + param[0]);
//[req uri] /hello/123?mySecretParam=ok
System.out.println("[Request URI] "+req.uri().toString());
System.out.println("[Hello-ID]: " + id); //the function parameter in controller
return ok("[Hello-ID]: " + id + "\n[mySecretParam] " + param[0]);
}
Your console output
[info] play - Application started (Dev)
[Request] GET /hello/123?mySecretParam=imhereyee
[mySecretParam] imhereyee
[Request URI] /hello/123?mySecretParam=imhereyee
[Hello-ID]: 123
The key to your question is Context object and Request object from that