/** * Queries for scalar values. Internal use. */ private <V> V queryValue(Class<V> classOfV) { InputStream instream = null; try { Reader reader = new InputStreamReader(instream = queryForStream(), Charsets.UTF_8); JsonArray array = new JsonParser().parse(reader). getAsJsonObject().get("rows").getAsJsonArray(); if(array.size() != 1) { throw new NoDocumentException("Expecting a single result but was: " + array.size()); } return JsonToObject(gson, array.get(0), "value", classOfV); } finally { close(instream); } }
/** * Performs a HTTP PUT request, saves or updates a document. * @return {@link Response} */ Response put(URI uri, Object object, boolean newEntity) { assertNotEmpty(object, "object"); HttpResponse response = null; try { final JsonObject json = getGson().toJsonTree(object).getAsJsonObject(); String id = getAsString(json, "_id"); String rev = getAsString(json, "_rev"); if(newEntity) { // save assertNull(rev, "rev"); id = (id == null) ? generateUUID() : id; } else { // update assertNotEmpty(id, "id"); assertNotEmpty(rev, "rev"); } final HttpPut put = new HttpPut(buildUri(uri).pathEncoded(id).build()); setEntity(put, json.toString()); response = executeRequest(put); return getResponse(response); } finally { close(response); } }
/** * @param response The {@link HttpResponse} * @return {@link Response} */ private Response getResponse(HttpResponse response) throws CouchDbException { InputStreamReader reader = new InputStreamReader(getStream(response), Charsets.UTF_8); return getGson().fromJson(reader, Response.class); }
public String readContent(List<String> elements, String rootPath, String element) { if(elements.contains(element)) { String path = format("%s%s/", rootPath, element); List<String> dirList = listResources(path); for (String file : dirList) { String contents = readFile(format("/%s%s", path, file)); return contents; } } return null; } }
private Map<String, String> populateMap(String rootPath, List<String> elements, String element) { Map<String, String> functionsMap = null; if(elements.contains(element)) { functionsMap = new HashMap<String, String>(); String path = format("%s%s/", rootPath, element); for (String fileName : listResources(path)) { String contents = readFile(format("/%s%s", path, fileName)); functionsMap.put(removeExtension(fileName), contents); } } return functionsMap; }
/** * Removes a document from the database. * <p>The object must have the correct <code>_id</code> and <code>_rev</code> values. * @param object The document to remove as object. * @throws NoDocumentException If the document is not found in the database. * @return {@link Response} */ public Response remove(Object object) { assertNotEmpty(object, "object"); JsonObject jsonObject = getGson().toJsonTree(object).getAsJsonObject(); final String id = getAsString(jsonObject, "_id"); final String rev = getAsString(jsonObject, "_rev"); return remove(id, rev); }
JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); ViewResult<K, V, T> vr = new ViewResult<K, V, T>(); vr.setTotalRows(getAsLong(json, "total_rows")); vr.setOffset(getAsInt(json, "offset")); vr.setUpdateSeq(getAsString(json, "update_seq")); JsonArray jsonArray = json.getAsJsonArray("rows"); for (JsonElement e : jsonArray) { ViewResult<K, V, T>.Rows row = vr.new Rows(); row.setId(JsonToObject(gson, e, "id", String.class)); if (classOfK != null) { row.setKey(JsonToObject(gson, e, "key", classOfK)); row.setValue(JsonToObject(gson, e, "value", classOfV)); row.setDoc(JsonToObject(gson, e, "doc", classOfT)); close(instream);
/** * Requests CouchDB creates a new database; if one doesn't exist. * @param dbName The Database name */ public void createDB(String dbName) { assertNotEmpty(dbName, "dbName"); InputStream getresp = null; HttpResponse putresp = null; final URI uri = buildUri(dbc.getBaseUri()).path(dbName).build(); try { getresp = dbc.get(uri); } catch (NoDocumentException e) { // db doesn't exist final HttpPut put = new HttpPut(uri); putresp = dbc.executeRequest(put); log.info(String.format("Created Database: '%s'", dbName)); } finally { close(getresp); close(putresp); } }
/** * Triggers a replication request. * @return {@link ReplicationResult} */ public ReplicationResult trigger() { assertNotEmpty(source, "Source"); assertNotEmpty(target, "Target"); HttpResponse response = null; try { JsonObject json = createJson(); if(log.isDebugEnabled()) { log.debug(json); } final URI uri = buildUri(dbc.getBaseUri()).path("_replicate").build(); response = dbc.post(uri, json.toString()); final InputStreamReader reader = new InputStreamReader(getStream(response), Charsets.UTF_8); return dbc.getGson().fromJson(reader, ReplicationResult.class); } finally { close(response); } }
/** * This method finds any document given a URI. * <p>The URI must be URI-encoded. * @param <T> The class type. * @param classType The class of type T. * @param uri The URI as string. * @return An object of type T. */ public <T> T findAny(Class<T> classType, String uri) { assertNotEmpty(classType, "Class"); assertNotEmpty(uri, "uri"); return get(URI.create(uri), classType); }
/** * 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"); assertNotEmpty(docId, "docId"); final String[] v = updateHandlerUri.split("/"); final String path = String.format("_design/%s/_update/%s/", v[0], v[1]); final URI uri = buildUri(getDBUri()).path(path).path(docId).query(params).build(); final HttpResponse response = executeRequest(new HttpPut(uri)); return streamToString(getStream(response)); }
assertNotEmpty(id, "id"); final DesignDocument dd = new DesignDocument(); final String rootPath = format("%s/%s/", DESIGN_DOCS_DIR, id); final List<String> elements = listResources(rootPath); if(elements == null) { throw new IllegalArgumentException("Design docs directory cannot be empty."); views = new HashMap<String, MapReduce>(); final String viewsPath = format("%s%s/", rootPath, VIEWS); for (String viewDirName : listResources(viewsPath)) { // views sub-dirs final MapReduce mr = new MapReduce(); final String viewPath = format("%s%s/", viewsPath, viewDirName); final List<String> dirList = listResources(viewPath); for (String fileName : dirList) { // view files final String def = readFile(format("/%s%s", viewPath, fileName)); if(MAP_JS.equals(fileName)) mr.setMap(def);
/** * @return DB Server version. */ public String serverVersion() { InputStream instream = null; try { instream = dbc.get(buildUri(dbc.getBaseUri()).build()); Reader reader = new InputStreamReader(instream, Charsets.UTF_8); return getAsString(new JsonParser().parse(reader).getAsJsonObject(), "version"); } finally { close(instream); } }
/** * Saves an attachment to a new document with a generated <tt>UUID</tt> as the document id. * <p>To retrieve an attachment, see {@link #find(String)}. * @param in The {@link InputStream} holding the binary data. * @param name The attachment name. * @param contentType The attachment "Content-Type". * @return {@link Response} */ public Response saveAttachment(InputStream in, String name, String contentType) { assertNotEmpty(in, "in"); assertNotEmpty(name, "name"); assertNotEmpty(contentType, "ContentType"); final URI uri = buildUri(getDBUri()).path(generateUUID()).path("/").path(name).build(); return put(uri, in, contentType); }
/** * Gets all design documents from desk. * @see #getFromDesk(String) * @return a list of all design documents */ public List<DesignDocument> getAllFromDesk() { final List<DesignDocument> designDocsList = new ArrayList<DesignDocument>(); for (String docName : listResources(format("%s/", DESIGN_DOCS_DIR))) { designDocsList.add(getFromDesk(docName)); } return designDocsList; }
/** * Saves a document with <tt>batch=ok</tt> query param. * @param object The object to save. */ public void batch(Object object) { assertNotEmpty(object, "object"); HttpResponse response = null; try { URI uri = buildUri(getDBUri()).query("batch", "ok").build(); response = post(uri, getGson().toJson(object)); } finally { close(response); } }
/** * Find documents using a declarative JSON querying syntax. * @param <T> The class type. * @param jsonQuery The JSON query string. * @param classOfT The class of type T. * @return The result of the query as a {@code List<T> } * @throws CouchDbException If the query failed to execute or the request is invalid. */ public <T> List<T> findDocs(String jsonQuery, Class<T> classOfT) { assertNotEmpty(jsonQuery, "jsonQuery"); HttpResponse response = null; try { response = post(buildUri(getDBUri()).path("_find").build(), jsonQuery); Reader reader = new InputStreamReader(getStream(response), Charsets.UTF_8); JsonArray jsonArray = new JsonParser().parse(reader) .getAsJsonObject().getAsJsonArray("docs"); List<T> list = new ArrayList<T>(); for (JsonElement jsonElem : jsonArray) { JsonElement elem = jsonElem.getAsJsonObject(); T t = this.gson.fromJson(elem, classOfT); list.add(t); } return list; } finally { close(response); } }
public CouchDbConfig(CouchDbProperties dbProperties) { assertNotEmpty(dbProperties, "Properties"); assertNotEmpty(dbProperties.getDbName(), "Database"); assertNotEmpty(dbProperties.getProtocol(), "Protocol"); assertNotEmpty(dbProperties.getHost(), "Host"); assertNotEmpty(dbProperties.getPort(), "Port"); this.dbProperties = dbProperties; }
/** * Closes the response input stream. * * @param response The {@link HttpResponse} */ public static void close(HttpResponse response) { try { close(response.getEntity().getContent()); } catch (Exception e) {} }