EzDevInfo.com

cradle

a high-level CouchDB client for Node.js

Get all recently changed documents in a CouchDB database

Using following code:

db.changes({'include_docs':true}).on('response', function (res) {
    res.on('data', function (change) {
        console.log(change);
    });
});

I am able to get all (old & new) documents that are changed in the database but how can I get documents that have changed recently?


Source: (StackOverflow)

Getting all documents of a database in CouchDB

The get() method of the Cradle library requires me to provide an _id. CouchDB provides an _all_docs view, but there's nothing in the Cradle documentation about this.

How can I get all documents from a single CouchDB database with Cradle?


Source: (StackOverflow)

Advertisements

Retrieving all Documents from couchdb using Node.js

I am writing a simple test app to experiment with the functionality of node.js and couchdb, so far i am loving it, but i ran in a snag. i have looked for and wide but can't seem to find an answer. My test server(a simple address book) does 2 things:

  1. if the user goes to localhost:8000/{id} then my app returns the name and address of the user with that id.
  2. if the user goes to localhost:8000/ then my app needs to return a list a names that are hyperlinks and takes them to the page localhost:8000/{id}.

I was able to get the first requirement working. i cant not seem to find how to retrieve a list of all names from my couchdb. that is what i need help with. here is my code:

var http = require('http');
var cradle = require('cradle');
var conn = new(cradle.Connection)();
var db = conn.database('users');

function getUserByID(id) {
    var rv = "";

    db.get(id, function(err,doc) {
        rv = doc.name;
    rv += " lives at " + doc.Address;
});

return rv;
}

function GetAllUsers() {
var rv = ""
return rv;
}

var server =  http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type':'text/plain'});
var rv = "" ;
var id = req.url.substr(1);

    if (id != "")
    rv = getUserByID(id);
else
    rv = GetAllUsers();

    res.end(rv);


});

server.listen(8000);
console.log("server is runnig");

As you can see, I need to fill in the GetAllUsers() function. Any help would be appreciated. Thanks in advance.


Source: (StackOverflow)

Android Studio 1.1.0 Gradle project sync failed Error importing a Gradle project on a OSX

I just installed gradle in this folder: /Users/joanet/Development/gradle-2.3

edit the file launchd.conf

sudo vim /etc/launchd.conf

to set the variable GRAILS_HOME

setenv GRAILS_HOME /Users/joanet/Development/gradle-2.3

then I've imported the project https://github.com/NordicSemiconductor/Android-nRF-Toolbox

using File -> Import project

but I got this error: Gradle project sync failed and Error: Configuration with name 'default' not found in Android Studio

I have tried this https://www.youtube.com/watch?v=8RwVvZtNTaM but it has not worked

enter image description here

Here the file build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

and here /app/build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion '22.0.0'
    defaultConfig {
        applicationId "no.nordicsemi.android.nrftoolbox"
        minSdkVersion 18
        targetSdkVersion 22
        versionCode 30
        versionName "1.12.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile project(':..:DFULibrary:dfu')
    compile files('libs/achartengine-1.1.0.jar')
    compile files('libs/nrf-logger-v2.0.jar')
}

here settings.gradle:

include ':app', '..:DFULibrary:dfu'

and here gradle-wrapper.properties:

#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip


// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Source: (StackOverflow)

What's a recommended way to put CouchDB views under source control?

I'm writing a node CRUD app that requires a few CouchDB views (I'm using express and cradle).

I've got the node app itself controlled with git, but my DB views are currently uncontrolled.

What's the recommended way to put these under source control? I don't want to put the entire database (including data) under source control.


Source: (StackOverflow)

switching to gradle from maven to manage a osgi big project (>200 bundles)

We have a big (~215 bundles and counting) osgi (felix+springdm) project, build with maven and maven-osgi plugin.

We've several problems with maven way:

1. submodules pom have to inherit from parent pom to take advantage of common variables and dependencies (that's ok) but then parent pom has to include all bundles pom to be able to build everything in together. This kind of circular reference makes much hard to keep all in sync.

2. the individual versioning of subbundles was so complex that it was decided (before I joined the project) to use the same version for all bundles. This means we now update version of all bundles for every release also if just a bunch of them are actually changed. This makes the whole concept of osgi a bit meanless IMHO. Please note that I'm not saying we continue to touch just a minority of bundles, we work on all of them but every release usually contains 1 or 2 features, that affects just some bundles.

3. to do the package and the deploy of the final artifact we need still another submodule that imports all the bundles needed for the deploy (all but a few for tests and mocks). [edited] Note that this aggregation is different from the one in the main pom as it doesn't compile bundles but just pick them from the maven repository.

4. the maven dependency system and the osgi plugin imports are sometimes hard to keep aligned. It's just too easy to forget an import or putting a wrong dependency.

[edited] In every bundle pom there is a section like this: `

         <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Export-Package>
                    </Export-Package>
                    <Import-Package>
                        com.google.gson,
                        org.apache.log4j,
                        org.apache.log4j.spi,
                        org.dom4j,
                        com.myinterfaces
                    </Import-Package>
                </instructions>
            </configuration>
        </plugin>`

For all those reasons, we are ok but not perfectly happy with maven. Recently someone proposed Gradle not as a panacea but as a definite improvements over the current situation.

Would you recommend moving to gradle? and in case which would be the best way?

Has someone else experienced the same situation? I think it should be common for all big projects with Osgi.

Disclaimer: I looked for similar questions like:

Buildr, Gradle or wait for Maven 3?

Looking for a good dev environment for OSGi bundles

Maven : OSGI, bundles and multi-modules projects

but either where where not about osgi submodules or not about gradle.


Source: (StackOverflow)

How can I call functions on documents retrieved from CouchDB?

I am using Cradle to store objects in CouchDB from my Node.js server. The objects contain functions....

function AnObject(a, b){
this.a = a; this.b = b;
this.addparts = function(){return this.a + this.b;};}

var cradle = require('cradle');
var db = new(cradle.Connection)('http://localhost', 5984, {cache: true, raw: false}).database('myDB');

var myObject = new AnObject(1, 2);
console.log("addparts:" + myObject.addparts());
db.save('myObjectId', myObject);

This works fine and the document is stored but when I retrieve it, I can no longer call the function on the returned document...

db.get('myObjectId', function(err, myRetrievedObject){
console.log("addparts:" + myRetrievedObject.addparts());
});

This fails with a (Property is not a function) Error..

node cradle_test

cradle_test.js:21
console.log("addparts:" + myRetrievedObject.addparts());
                                         ^
TypeError: Property 'addparts' of object {"_id":"myObjectId","_rev":"2-83535db5101fedfe30a1548fa2641f29","a":1,"b":2,"addparts":"function (){return this.a + this.b;}"} is not a function

Source: (StackOverflow)

Getting binary files with cradles getAttachment from a CouchDB?

I uploaded a png as attachment to a CouchDb database. When I have look at it via Futon it is fine, if I try to get it back via cradle it is corrupted. I used a snipptlet from the crade-test.js shipped with crade and modified it a bit:

      var response = {};
      var streamer = db.getAttachment(data.id,filename);
      streamer.addListener('response', function (res) {
        response.headers = res.headers;
        response.headers.status = res.statusCode;
        response.body = "";
      });
      streamer.addListener('data', function (chunk) { response.body += chunk; });
      streamer.addListener('end', function () {
        fs.writeFile('new-'+filename, response.body, function (err) {
          if (err) throw err;
            console.log('It\'s saved!');
          });
        });

The result is a corrupted png that is bigger than the input. I provided a working example here: http://jsfiddle.net/x8GZc/


Source: (StackOverflow)

How can I pass parameters to a view using cradle (CouchDB)

Using cradle, how am I able to pass parameters to a view in CouchDB?


Update

Say I want to return documents which match other properties than _key (the default)...

// document format
{
    _key,
    postHeading,
    postBody,
    postDate
}

What if I wanted to match documents against the postHeading property... How would I go about this? What would the view look like, and how would I pass a search string to that view?


At the moment I'm doing this...

database.get("980f2ba66d5c8f9c91b9204a4d00022a", function (error, document)
{           
});

I would like to access a view instead, and instead of the 40 character long auto-generated key, I'd like to pass a string, matching another property.

Something along the lines of this...

database.save("_design/posts", {
    single: {
        map: function (document)
        {
            if (document.postHeading == PARAMETER_PASSED_GOES_HERE)
                emit(null, document);
        }
    }
});

database.view("posts/single", function (error, documents)
{           
});

Source: (StackOverflow)

Eclipse, libgdx and Gradle. Cannot get Google play services admob to work

I want to use admob in a Libgdx (1.4.1) project using Eclipse (Indigo). I have donwload Google play services and Google repositry using the SDK. I have added the following to my gradle.build file in the Android project:

project(":android") { apply plugin: "android"

configurations { natives }

dependencies {
    compile project(":core")
    compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
    compile 'com.google.android.gms:play-services:6.+'

    {more not listed}

This is the output of Gradle task :android:androidDependencies:

:android:androidDependencies
debug
\--- com.google.android.gms:play-services:6.1.71
     \--- com.android.support:support-v4:20.0.0

debugTest
No dependencies

release
\--- com.google.android.gms:play-services:6.1.71
     \--- com.android.support:support-v4:20.0.0

In the Android project, directory 'Gradle dependencies (persisted)' I can see

support-v4-20.0.0.aar

play-services-6.1.71.aar

However, when I try to create a 'protected AdView adview' variable, it does not find the class AdView. When pressing CTRL-Shift-O I get a message '0 imports added'. When I manually import the AdView class it does not find it either.

Could anyone point out what I am doing wrong?


Source: (StackOverflow)

How to handle Document update conflict when using CouchDB client cradle for Node.js?

1000000 clients try to update a couchdb document using flatiron/cradle at the same time. How to handle all update conflicts?


Source: (StackOverflow)

NodeJS and Cradle Not Connecting

Using Cradle 5.5 and NodeJS 0.4.8, I can't seem to get a connection to work. I've successfully used RESTLER, but I can't seem to configure cradle. I'd like to take advantage of the caching aspects of Cradle.

I've tried both my Cloudant Account and a normal, admin party CouchDB database, both with the same results.

Admin Party Database:

var conn1 = new (cradle.Connection)("XX.XX.XXX.XXX", 5984);

Cloudant:

var account = {
    username: "user", 
    password: "pwd"
};
var conn = new (cradle.Connection)("user.cloudant.com", 443, {
    secure: true,
    auth: account
});

I've tried all combinations, nothing seems to get me anything other than undefined when I do things like console.log(conn.config()); or console.log(conn.databases());

Any ideas on what might be causing this? I am starting to think it might be the versions of Cradle/NodeJS, but I can't seem to find a reference to them to not working together anywhere.

UPDATE: Still having issues, but I changed the code a bit to see if I could pinpoint the problem.

cradle.setup({host:'username.cloudant.com', port: 443,
                auth: { username: 'username', password: 'password'},
                options: {secure: true, cache: true, raw: false}
});

c = new(cradle.Connection)().config();

console.log(c);

console.log(cradle);

My output is the following:

undefined

{ extend: [Function],

  Response: [Function: Response],

  Cache: [Function],

  host: 'username.cloudant.com',

  port: 443,

  auth: { username: 'username', password: 'password' },

  options: 

   { cache: true,

     raw: false,

     timeout: 0,

     secure: false,

     headers: {},

     host: 'username.cloudant.com',

     port: 443,

     auth: { username: 'username', password: 'password' },

     options: { secure: true, cache: true, raw: false } },

  setup: [Function],

  Connection: [Function: Connection],

  merge: [Function] }

I'm incredibly stumped-anyone else at least experienced this before?


Source: (StackOverflow)

Is it possible to make cradle calls synchronously?

I'm using Express for a project, and I've been trying out the CouchDB database using Cradle. While the idea of asynchronous execution is cool for performance reasons, it's making my code really a mess for routines where I need to make several database calls in a row.

Is it possible to make cradle calls without using a callback? Or, I suppose more correctly, is there a better way to organize the code that doesn't involve nesting 3 or 4 anonymous functions within one another just to get at database query results? The code is only used in one place, so it doesn't make sense to me to use named functions that will only be called once.


Source: (StackOverflow)

How to create multiple attachments in one call with cradle

I'm working on a nodejs application and am inserting two attachments to a couchdb with cradle. Currently I am inserting the first attachment, getting the updated doc, and then inserting the second attachment with the updated _rev key. This is inefficient causing me to have to make two separate calls to couchdb.

Is there a way to create multiple attachments with a single cradle call?


Source: (StackOverflow)

emit doc twice with different key in couchdb

Say I have a doc to save with couchDB and the doc looks like this:

{
   "email": "lorem@gmail.com",
   "name": "lorem",
   "id": "lorem",
   "password": "sha1$bc5c595c$1$d0e9fa434048a5ae1dfd23ea470ef2bb83628ed6"
}

and I want to be able to query the doc either by 'id' or 'email'. So when save this as a view I write so:

db.save('_design/users', {
    byId: {
        map: function(doc) {
            if (doc.id && doc.email) {
                emit(doc.id, doc);
                emit(doc.email, doc);
            }
        }
    }
});

And then I could query like this:

db.view('users/byId', {
    key: key
}, function(err, data) {
    if (err || data.length === 0) return def.reject(new Error('not found'));
    data = data[0] || {};
    data = data.value || {};

    self.attrs = _.clone(data);
    delete self.attrs._rev;
    delete self.attrs._id;

    def.resolve(data);
});

And it works just fine. I could load the data either by id or email. But I'm not sure if I should do so.

I have another solution which by saving the same doc with two different view like byId and byEmail, but in this way I save the same doc twice and obviously it will cost space of the database.

Not sure which solution is better.


Source: (StackOverflow)