Code Monkey home page Code Monkey logo

java-cloudant's Introduction

⚠️ NO LONGER MAINTAINED ⚠️

This library is end-of-life and no longer supported.

This repository will not be updated. The repository will be kept available in read-only mode.

Please see the Migration Guide for advice about migrating to our replacement library cloudant-java-sdk.

For FAQs and additional information please refer to the Cloudant blog.

Cloudant Java Client

Build Status Maven Central Javadocs

This is the official Cloudant library for Java.

Installation and Usage

Gradle:

dependencies {
    compile group: 'com.cloudant', name: 'cloudant-client', version: '2.20.1'
}

Gradle with optional okhttp-urlconnection dependency:

dependencies {
    compile group: 'com.cloudant', name: 'cloudant-client', version: '2.20.1'
    compile group: 'com.squareup.okhttp3', name: 'okhttp-urlconnection', version: '3.12.12'
}

Maven:

<dependency>
  <groupId>com.cloudant</groupId>
  <artifactId>cloudant-client</artifactId>
  <version>2.20.1</version>
</dependency>

Maven with optional okhttp-urlconnection dependency:

<dependency>
  <groupId>com.cloudant</groupId>
  <artifactId>cloudant-client</artifactId>
  <version>2.20.1</version>
</dependency>

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp-urlconnection</artifactId>
  <version>3.12.12</version>
</dependency>
Optional OkHttp dependency

HTTP requests to the database are made using java.net.HttpURLConnection. Adding the optional dependency for the okhttp-urlconnection changes the HttpURLConnection from the default JVM implementation to the OkHttp implementation. Note that to use OkHttp requires a minimum of Java 1.7.

The main use case that is supported by this optional dependency is configuration of connection pools on a per CloudantClient basis (see the javadoc for ClientBuilder.maxConnections). If the OkHttp dependency is available at runtime it will be used automatically. Not using OkHttp will result in a smaller application size.

Note: The configuration options ClientBuilder.customSSLSocketFactory and ClientBuilder.disableSSLAuthentication are not usable with the combination of the optional OkHttp dependency and Java versions of 8u252 or newer.

Getting Started

This section contains a simple example of creating a com.cloudant.client.api.CloudantClient instance and interacting with Cloudant.

For further examples and more advanced use cases see the javadoc for the version you are using. The source code for the tests in this github project also contains many examples of API usage.

// Create a new CloudantClient instance for account endpoint example.cloudant.com
CloudantClient client = ClientBuilder.account("example")
                                     .username("exampleUser")
                                     .password("examplePassword")
                                     .build();

// Note: for Cloudant Local or Apache CouchDB use:
// ClientBuilder.url(new URL("yourCloudantLocalAddress.example"))
//              .username("exampleUser")
//              .password("examplePassword")
//              .build();

// Note: there are some convenience methods for IBM Bluemix
//
// To use the URL and credentials provided in VCAP metadata:
// ClientBuilder.bluemix(String vcapMetadata)
//              .build();
//
// To use an IAM API key:
// ClientBuilder.url("examplebluemixaccount.cloudant.com")
//              .iamApiKey("exampleApiKey")
//              .build();

// Show the server version
System.out.println("Server Version: " + client.serverVersion());

// Get a List of all the databases this Cloudant account
List<String> databases = client.getAllDbs();
System.out.println("All my databases : ");
for ( String db : databases ) {
	System.out.println(db);
}

// Working with data

// Delete a database we created previously.
client.deleteDB("example_db");

// Create a new database.
client.createDB("example_db");

// Get a Database instance to interact with, but don't create it if it doesn't already exist
Database db = client.database("example_db", false);

// A Java type that can be serialized to JSON
public class ExampleDocument {
  private String _id = "example_id";
  private String _rev = null;
  private boolean isExample;

  public ExampleDocument(boolean isExample) {
    this.isExample = isExample;
  }

  public String toString() {
    return "{ id: " + _id + ",\nrev: " + _rev + ",\nisExample: " + isExample + "\n}";
  }
}

// Create an ExampleDocument and save it in the database
db.save(new ExampleDocument(true));
System.out.println("You have inserted the document");

// Get an ExampleDocument out of the database and deserialize the JSON into a Java type
ExampleDocument doc = db.find(ExampleDocument.class,"example_id");
System.out.println(doc);

Output:

Server version = 1.0.2
All my databases: example_db, stuff, scores
You have inserted the document.
{ id: example_id,
  rev: 1-6e4cb465d49c0368ac3946506d26335d,
  isExample: true
}

There is significantly more documentation, including additional code samples and explanations, in the javadoc. The first page you land on when following the javadoc link includes a table of contents with further links to help guide you to the documentation you need. To find the additional information be sure to scroll down past the auto-generated summary tables and do not overlook the package overviews.

Related documentation

Development

For information about contributing, building, and running tests see the CONTRIBUTING.md.

Using in Other Projects

The preferred approach for using java-cloudant in other projects is to use the Gradle or Maven dependency as described above.

Migrating to cloudant-java-sdk library

We have a newly supported Cloudant Java SDK named cloudant-java-sdk. For advice on migrating from this module see MIGRATION.md.

License

Copyright © 2014, 2016 IBM Corp. All rights reserved.

Licensed under the apache license, version 2.0 (the "license"); you may not use this file except in compliance with the license. you may obtain a copy of the license at

http://www.apache.org/licenses/LICENSE-2.0.html

Unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "as is" basis, without warranties or conditions of any kind, either express or implied. See the license for the specific language governing permissions and limitations under the license.

Issues

Before opening a new issue please consider the following:

  • Only the latest release is supported. If at all possible please try to reproduce the issue using the latest version.
  • Please check the existing issues to see if the problem has already been reported. Note that the default search includes only open issues, but it may already have been closed.
  • Cloudant customers should contact Cloudant support for urgent issues.
  • When opening a new issue here in github please complete the template fully.

Caching, Encryption, and Compression

Caching data at the client, when it is appropriate for the application, can often improve performance considerably. In some cases, it may also be desirable to encrypt or compress data at the client. There is no built-in support for caching, encryption or compression at the client in java-cloudant. Other Java libraries that are not officially supported by Cloudant, but can provide these capabilities are:

java-cloudant's People

Contributors

ahmedyha avatar behrica avatar brynh avatar ctipka avatar emlaver avatar esrose avatar ganeshkumarc avatar henryabra avatar hiranya avatar iddo avatar lightcouch avatar majido avatar mariobriggs avatar markewallace avatar michaelwj avatar mikerhodes avatar mojito317 avatar msargentibm avatar neekrish avatar rhyshort avatar ricellis avatar rnewson avatar sebastien-cote avatar seize-the-dave avatar slaupster avatar smithsz avatar snowch avatar srl295 avatar tomblench avatar valery1707 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-cloudant's Issues

How to handle error responses?

The README gives very simple examples like
Response response = db.remove(foo);

However it does not say what is supposed to happen in case of issues, such as a document not found, or any other error for any method.

Can someone clarify that?
Exceptions? Null response? Response with some error property?

How to check whether the request was completed successfully or not...

Query and return the index of the doc in a data set

Hi, I'm trying to figure out if it is possible to run a query for a particular key-value-pair with a customized sort setting and then in the returned doc it will returns the index of the doc in the database along with the doc. Do you think it is doable? Thanks.

For example:
I have a database that has 10 docs, and I am looking up the one with name=john, with sorting on address. I wish Cloudant can return me the doc that has name=john while also letting me know its index in this data set with sorting applied is 5.

wsjar protocol

Could a check for wsjar be added, in addition to jar and file, to the org.lightcouch.internal.CouchDbUtil.listResources(String path) method. I am using WebSphere Liberty 8.5.5.5 and that method returns null for a path like the following:
wsjar:file:/somepath/myapp.war!/WEB-INF/classes/design-docs/my-filter/

Support setting read & write quorum

@mikerhodes
1- any ideas on how to test this one. Will we get a dedicated/sharded account?
2 - Should i just make available 2 properties on the DB object, rather than adding a 'readQuorum/writeQuorum' paramter to every read/update method? Do we have any precedents here ?

Fetching docs from cloudant using java-cloudant APIs

I tried calling db.view("_all_docs").includeDocs(true).query(JSONObject.class) on my code but I'm getting weird errors about Gson, and it raised an exception:
java.lang.IllegalArgumentException: Invalid type of value. Type: [com.google.gson.internal.LinkedTreeMap] with value: [my_json_but_with_all_quotes_stripped]

When I called the function with Object.class instead of JSONObject.class, I got an Object which, when printed, looks almost like JSON but with all of the quotes stripped out (even for strings with whitespace).

When I called the function with String.class, I got some error along the lines of "Expected STRING but found BEGIN_OBJECT".

Readme & doc updates for 2.0

The README.md, CHANGES.md and javadoc need to be slimmed down and up-to-date for a 2.0 release.

The API reference should be moved entirely into javadoc so the examples don't need to be maintained in two places.
A javadoc overview.html and some package-info.java classes are needed.
There are also a lot of javadoc warnings that need resolution so we can maintain the javadoc in a clean state.

Cloudant object pooling?

We started seeing memory run ups after putting the library under low load over a number of hours. The datasets are not trivial, maybe 50k docs with 20 fields.

But the question is really about using the cloudant client efficiently.
Is it best to use a single singleton instances across a tomcat app?
Or should we create a pool of them?
Or just create as needed?
Always call shutdown (i saw apache http client is used underneath which recommends cleaning up.)
Thanks.

Connection pooling support for 2.0

After replacing Apache HttpClient with HttpUrlConnection connection pooling is relying on the JVM wide persistent connection settings.
It would be preferable to use the previous style of configuring connection pooling on a per CloudantClient instance basis.

AuthCookie may not be null

I am currently getting a java.lang.IllegalArgumentException: AuthCookie may not be null.

Here is my code

public class Cloudant {
public static void main (String[] args){

String password = System.getProperty("gffgasdas");
CloudantClient client = new CloudantClient("test1234.cloudant.com",password);

System.out.println("Connected to Cloudant");
System.out.println("Server Version: " + client.serverVersion());

List<String> databases = client.getAllDbs();
System.out.println("All my databases : ");
for ( String db : databases ) {
    System.out.println(db);

startKey and endKey - filtering a view using a complex key

Hello,
I have a view that returns complex keys that follow this format/pattern:

["1000","2000”,0]
["1000","2000",1]
["1000","2000”,2]
["1000","2001”,0]
["1000","2001”,1]
["1000","2001”,2]
["1001”,”2000”,0]
["1001”,”2000",1]
["1001”,”2000”,2]
["1001”,”2001”,0]
["1001”,”2001”,1]
["1001”,”2001”,2]
...

I can query directly my view [using curl from the command line] by submitting a REST request and specifying the following start and end key values:

startkey=["1000","0",0]&endkey=["1000",{}]"

The above start and end key values return the data I am expecting. Basically, I am filtering the results and getting only those records that have "1000" as the first value in the complex key.

However, when I try to run the same query against the view using the Java API, I don’t get the expected results:
...
Object[] startKeys = new Object[] { "1000", "0", 0 };
Object[] endKeys = new Object[] { "1000", “{}” };
view.startKey(startKeys);
view.endKey(endKeys);
....

I get no results back when using the start and end key values shown above in the Java code. I am wondering if there is a defect in the API code that builds the URL to query and filter the view. Could you provide some guidance on how to resolve this issue? Thanks.

DesginDocument.getFromDesk needs to be replaced

DesignDocoument.getFromDesk expects views to be in a specific sub folder of the current working directory. The folder is called design-docs. This is not spelt out in the documentation and seems to be an arbitrary restriction on where the library will load views from. It should be replaced with DesignDocument.fromFile(...) or something similar.

selector API takes JSON fragment only?

The findByIndex() API takes a 'selector' which the query docs give as a JSON object such as

{"name": "Paul"}

however the README gives the example:

List<Movie> movies = db.findByIndex("\"selector\": 
                { \"Movie_year\": {\"$gt\": 1960}, \"Person_name\": \"Alec Guinness\" }",

.. where the selector is more of a "fragment" than a well formed object. In fact, I found that the server returned JSON errors unless I called findByIndex with "\'selector\':" + someJson (where someJson is the well formed JSON selector body).

Could this API be clarified, or even better accept just the JSON body and not require the key? Otherwise it is awkward to create this "Fragment" for use with the API.

docs: queryView()

com.cloudant.client.api.View.queryView(Class k, Class v, Class t) can use some more docs. In particular, t is the type of the doc, k the type of the key, and v of the value. This is handy when querying something that has a complex key.

Port URI builder from sync-android

The java-cloudant client should use the same URI builder as sync-android. A number of fixes have gone into that URI builder for special cases (e.g. ":") and we should take advantage of them. Additionally it is another step towards making java-cloudant a suitable base for sync-android.

Default ports are not used when creating client instance from a URL

Creating a CloudantClient instance from a URL without specifying a port results in the port being set to -1 which is invalid e.g.

new CloudantClient("http://192.0.2.0", "user", "pass");

It is possible to workaround by specifying the port e.g.

new CloudantClient("http://192.0.2.0:80", "user", "pass");

It shouldn't be necessary to specify the default port.

Support retrieving the shards of a DB and the shard a document belongs to

@mikerhodes
1 - looking at /db/_shards here (http://docs.cloudant.com/api/database.html), I am assuming the # of shards will be variable i.e 00000000 to ffffffff can be split over as many shards as required. So wouldnt 'shards' be an array?... having problems mapping to a domain object if the set of ranges are not fixed and then it is not an array.

2- What about the endpoints after this one in http://docs.cloudant.com/api/database.html i.e. starting with 'Cleaning up cached view output'
If yes, is there some overlap between 'set_permissions' and 'PUT /db/_security'

No debug information included in jar

Hi

I'm trying to set breakpoints in the Cloudant lib code from within IntelliJ IDEA, but it's not working. This can happen if a jar is built but no debug information is included. If this is a case, could you release a new jar version that includes debug information?

Thanks!

Add HTTP response codes to Repsonse objects

The Response class does not include the HTTP response code. We should add this information to help people align client behaviour to the more general Cloudant documentation, especially useful for cases like 201 and 202.

We should validate that the status code has been added to CouchDbException and its subclasses where possible as well.

Cloudant query sample code not correct

The Cloundant query sample snippet code below is not correct:

List<Movie> movies = db.findByIndex("{
                     \"Movie_year\": {\"$gt\": 1960}, \"Person_name\": \"Alec Guinness\"
                     }",
                    Movie.class,
                    new FindByIndexOptions()
                        .sort(new IndexField("Movie_year", SortOrder.desc))
                        .fields("Movie_name").fields("Movie_year"));

I tried something similar:

String Selector="{\"Place_id\": {\"$gt\": 100}}";
   List<places> p1 = db_use.findByIndex(Selector,places.class);

and got a JSON exception:

org.lightcouch.CouchDbException: Bad Request{"error":"bad_request","reason":"invalid UTF-8 JSON"} 

After adding "selector" to the query it then worked:

String Selector="\"selector\": {\"Place_id\": {\"$gt\": 100}}";

Allow to query view with multiple key

It seems that a view can only be queried with a single key, using the key(Object...) method of com.cloudant.client.api.View. In the meantime, cloudant allows querying using multiple keys (using query parameter keys=...), so it would be helpful to have a method that allow querying using multiple keys (for example a method keys(Object[]) on the com.cloudant.client.api.View class).

startKey/endKey with complex keys

I think there's a bug with the startKey and endKey functions as well as key()

Even in the ViewsTest there is this snippet in byComplexKey()

    public void byComplexKey() {
        int[] complexKey = new int[] { 2011, 10, 15 };
        List<Foo> foos = db.view("example/by_date")
                .key(complexKey)
//              .key(2011, 10, 15) 

I think the problem is that one (Object...) function is calling another (Object...) function. I can't remember how to fix this yet, but want to capture.

I had to do similar code to the above workaround in my own project.

client constructor: clarify user vs api

CloudantClient(String account, String loginUsername, String password)

  • The second parameter here could be documented as "apikey or account" if I understand properly: "If using an API key, this is the api key, otherwise pass in the account for this parameter also" ?
  • Actually, could you take a "null" loginUsername here and then: if loginUsername==null { loginUsername = account} ? Maybe that would be more confusing than helpful, though.

Documentation: connection pooling

Please include documentation how to setup and configure connection pooling for this library. For example:

  1. information on instantiating the library so that it can be shared, e.g. using a singleton
  2. calling out which methods are threadsafe and which aren't
  3. describe how to configure connection pooling
  4. describe how the library authenticates to Cloudant (using cookie or basic authentication)
  5. describe if session expiry gets handled automatically by the library [1]. if not, what does the library consumer need to do to handle this?
  6. how to use the library in JEE environments so that connection pooling can be configured at the app server level [2]

There is some information in this ticket: #34. However, it would be good if the README.md covered the above info.


[1] this assumes the library uses cookie authentication. The docs state that the cookie can be used until it expires.
[2] presumably this will require wrapping the library in a technology like JCA - [more info]

more efficient sync?

This is maybe a lightCouch q, but I wonder if synchronizeWithDb could be made more efficient with something such as:

  • md5 hash the document, do a query including that hash?
  • keep a 'revision number' in the js file (manually updated) and only sync if it changes?

POST with invokeUpdateHandler?

Is there any way in this API to POST to an update handler? Passing in no docId just results in an error docId is required where I would expect it to POST instead of PUT.

java.lang.IllegalArgumentException: docId may not be null.
    at org.lightcouch.internal.CouchDbUtil.assertNotEmpty(Unknown Source)
    at org.lightcouch.CouchDatabaseBase.invokeUpdateHandler(Unknown Source)
    at com.cloudant.client.api.Database.invokeUpdateHandler(Unknown Source)

Logging levels

Every request and response from the database is logged at INFO level. Can this be changed to DEBUG please.

log.debug("> " + req.getMethod() + " " + URLDecoder.decode(req.getUri(), "UTF-8"));
log.debug("< Status: " + response.getStatusLine().getStatusCode());

Timestamp JSON string to Java Timestamp Value - View.query(class)

Hello, I am having an issue when using the query method of the View class:

List images = myView.query(Image.class);

The above method invocation results in a JSON exception: my Image class has a timestamp instance variable, and the Gson instance used internally by the couchdb library fails to translate a string like “2015-01-23T18:25:43.511Z” to a timestamp variable.

If I could somehow configure the Gson instance used internally by the couchdb library, this exception would not occur. I understand I can configure my own Gson instance in the following way to handle timestamp strings like “2015-01-23T18:25:43.511Z” correctly:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();

However, I am afraid I don’t know how to configure the Gson instance used internally by the couchdb library. Could you provide some guidance on how to address this issue? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.