Search in sources :

Example 16 with DatabaseURIHelper

use of com.cloudant.client.internal.DatabaseURIHelper in project java-cloudant by cloudant.

the class Database method createIndex.

/**
 * <p>
 * Create a new index from a string of JSON representing the index definition
 * </p>
 * <p>
 * Helpers are available to construct the index definition string for JSON and text indexes.
 * </p>
 * <p>
 * Example usage creating a JSON index with a generated name for the field named "Movie_year"
 * with ascending sort order:
 * </p>
 * <pre>
 * {@code
 * db.createIndex(JsonIndex.builder().asc("Movie_year").definition());
 * }
 * </pre>
 * <p>
 * Example usage creating a partial JSON index named "movies-after-2010-json" which will
 * index all movies with "Movie_year" greater than 2010, returning the field "Movie_year" in
 * descending order:
 * </p>
 * <pre>
 * {@code
 * Selector selector = gt("Movie_year", 2010);
 * String indexDefinition = JsonIndex.builder().
 *     name("movies-after-2010-json").
 *     desc("Movie_year").
 *     partialFilterSelector(selector).
 *     definition();
 * db.createIndex(indexDefinition);
 * }
 * </pre>
 * <p>
 * Example usage creating a text index with a generated name for the string field named
 * "Movie_title":
 * </p>
 * <pre>
 * {@code
 * db.createIndex(TextIndex.builder().string("Movie_title").definition());
 * }
 * </pre>
 * <p>
 * Example usage creating a partial text index named "movies-after-2010-text" for the string field
 * named "Movie_title" which will index all movies titles for movies with "Movie_year" greater
 * than 2010:
 * </p>
 * <pre>
 * {@code
 * Selector selector = gt("Movie_year", 2010);
 * String indexDefinition = TextIndex.builder().
 *     string("Movie_title").
 *     name("movies-after-2010-text").
 *     partialFilterSelector(selector).
 *     definition();
 * db.createIndex(indexDefinition);
 * }
 * </pre>
 *
 * @param indexDefinition String representation of the index definition JSON
 * @see com.cloudant.client.api.query.JsonIndex.Builder
 * @see com.cloudant.client.api.query.TextIndex.Builder
 * @see <a
 * href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#creating-an-index"
 * target="_blank">index definition</a>
 */
public void createIndex(String indexDefinition) {
    assertNotEmpty(indexDefinition, "indexDefinition");
    InputStream putresp = null;
    URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
    try {
        putresp = client.couchDbClient.executeToInputStream(createPost(uri, indexDefinition, "application/json"));
        String result = getAsString(putresp, "result");
        if (result.equalsIgnoreCase("created")) {
            log.info(String.format("Created Index: '%s'", indexDefinition));
        } else {
            log.warning(String.format("Index already exists : '%s'", indexDefinition));
        }
    } finally {
        close(putresp);
    }
}
Also used : InputStream(java.io.InputStream) DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) CouchDbUtil.getAsString(com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getAsString) URI(java.net.URI)

Example 17 with DatabaseURIHelper

use of com.cloudant.client.internal.DatabaseURIHelper in project java-cloudant by cloudant.

the class Database method listIndices.

/**
 * List all indices
 * <P>Example usage:</P>
 * <pre>
 * {@code
 * List <Index> indices = db.listIndices();
 * }
 * </pre>
 *
 * @return List of Index objects
 * @see Database#listIndexes()
 */
@Deprecated
public List<Index> listIndices() {
    InputStream response = null;
    try {
        URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
        response = client.couchDbClient.get(uri);
        return getResponseList(response, client.getGson(), DeserializationTypes.INDICES);
    } finally {
        close(response);
    }
}
Also used : InputStream(java.io.InputStream) DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) URI(java.net.URI)

Example 18 with DatabaseURIHelper

use of com.cloudant.client.internal.DatabaseURIHelper in project java-cloudant by cloudant.

the class Database method query.

/**
 * <p>
 *     Query documents using an index and a query selector.
 * </p>
 * <p>
 *     Note: the most convenient way to generate query selectors is using a
 *     {@link com.cloudant.client.api.query.QueryBuilder}.
 * </p>
 * <p>
 *     Example usage to return the name and year of movies starring Alec Guinness since 1960
 *     with the results sorted by year descending:
 * </p>
 * <pre>
 * {@code
 * QueryResult<Movie> movies = db.query(new QueryBuilder(and(
 *   gt("Movie_year", 1960),
 *   eq("Person_name", "Alec Guinness"))).
 *   sort(Sort.desc("Movie_year")).
 *   fields("Movie_name", "Movie_year").
 *   build(), Movie.class);
 * }
 * </pre>
 * @param query    String representation of a JSON object describing criteria used to
 *                 select documents.
 * @param classOfT The class of Java objects to be returned in the {@code docs} field of result.
 * @param <T>      The type of the Java object to be returned in the {@code docs} field of result.
 * @return         A {@link QueryResult} object, containing the documents matching the query
 *                 in the {@code docs} field.
 * @see com.cloudant.client.api.query.QueryBuilder
 * @see <a
 * href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#selector-syntax"
 * target="_blank">selector syntax</a>
 */
public <T> QueryResult<T> query(String query, final Class<T> classOfT) {
    URI uri = new DatabaseURIHelper(db.getDBUri()).path("_find").build();
    InputStream stream = null;
    try {
        stream = client.couchDbClient.executeToInputStream(createPost(uri, query, "application/json"));
        Reader reader = new InputStreamReader(stream, "UTF-8");
        Type type = TypeToken.getParameterized(QueryResult.class, classOfT).getType();
        QueryResult<T> result = client.getGson().fromJson(reader, type);
        return result;
    } catch (UnsupportedEncodingException e) {
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(stream);
    }
}
Also used : Type(java.lang.reflect.Type) QueryResult(com.cloudant.client.api.query.QueryResult) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URI(java.net.URI)

Example 19 with DatabaseURIHelper

use of com.cloudant.client.internal.DatabaseURIHelper in project java-cloudant by cloudant.

the class CouchDatabaseBase method invokeUpdateHandler.

/**
 * Invokes an Update Handler.
 * <pre>
 * Params params = new Params()
 * 	.addParam("field", "foo")
 * 	.addParam("value", "bar");
 * String output = dbClient.invokeUpdateHandler("designDoc/update1", "docId", params);
 * </pre>
 *
 * @param updateHandlerUri The Update Handler URI, in the format: <code>designDoc/update1</code>
 * @param docId            The document id to update.
 * @param params           The query parameters as {@link Params}.
 * @return The output of the request.
 */
public String invokeUpdateHandler(String updateHandlerUri, String docId, Params params) {
    assertNotEmpty(updateHandlerUri, "uri");
    final String[] v = updateHandlerUri.split("/");
    final InputStream response;
    final URI uri;
    DatabaseURIHelper uriHelper = new DatabaseURIHelper(dbUri).path("_design").path(v[0]).path("_update").path(v[1]).query(params);
    if (docId != null && !docId.isEmpty()) {
        // Create PUT request using doc Id
        uri = uriHelper.path(docId).build();
        response = couchDbClient.put(uri);
    } else {
        // If no doc Id, create POST request
        uri = uriHelper.build();
        response = couchDbClient.post(uri, null);
    }
    return streamToString(response);
}
Also used : InputStream(java.io.InputStream) DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) CouchDbUtil.getAsString(com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getAsString) CouchDbUtil.streamToString(com.cloudant.client.org.lightcouch.internal.CouchDbUtil.streamToString) URI(java.net.URI)

Example 20 with DatabaseURIHelper

use of com.cloudant.client.internal.DatabaseURIHelper in project java-cloudant by cloudant.

the class CouchDatabaseBase method find.

/**
 * Finds an Object of the specified type.
 *
 * @param <T>       Object type.
 * @param classType The class of type T.
 * @param id        The document id.
 * @param params    Extra parameters to append.
 * @return An object of type T.
 * @throws NoDocumentException If the document is not found in the database.
 */
public <T> T find(Class<T> classType, String id, Params params) {
    assertNotEmpty(classType, "Class");
    assertNotEmpty(id, "id");
    final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, params);
    return couchDbClient.get(uri, classType);
}
Also used : DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) URI(java.net.URI)

Aggregations

DatabaseURIHelper (com.cloudant.client.internal.DatabaseURIHelper)22 URI (java.net.URI)20 InputStream (java.io.InputStream)11 CouchDbUtil.getAsString (com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getAsString)3 HttpConnection (com.cloudant.http.HttpConnection)3 JsonObject (com.google.gson.JsonObject)3 InputStreamReader (java.io.InputStreamReader)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 CouchDbUtil.getResponse (com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getResponse)2 Reader (java.io.Reader)2 QueryResult (com.cloudant.client.api.query.QueryResult)1 AllDocsRequestResponse (com.cloudant.client.internal.views.AllDocsRequestResponse)1 Response (com.cloudant.client.org.lightcouch.Response)1 CouchDbUtil.streamToString (com.cloudant.client.org.lightcouch.internal.CouchDbUtil.streamToString)1 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonParser (com.google.gson.JsonParser)1 IOException (java.io.IOException)1 Type (java.lang.reflect.Type)1 ArrayList (java.util.ArrayList)1