@Override public <T> EntityDocument<T> toEntity(final JsonDocument source, final Class<T> clazz) { JsonObject json = source.content(); // favor embedded type over provided type Class<T> type = type(json.getString(N1Q.CLASS), clazz); T value = mapper.convertValue(json, type); return EntityDocument.create(source.id(), value); }
/** * A convenient method to retrieve String value when Document type is unknown. * This method uses LegacyDocument to get, then tries to convert content based on its class. * @param bucket the bucket to get a document * @param id the id of the target document * @return String representation of the stored value, or null if not found */ public static String getStringContent(Bucket bucket, String id) { final LegacyDocument doc = bucket.get(LegacyDocument.create(id)); if (doc == null) { return null; } final Object content = doc.content(); return getStringContent(content); }
@Override public void save(final Session session) { JsonObject json = JsonObject.from(session.attributes()); // session metadata json.put("_accessedAt", session.accessedAt()); json.put("_createdAt", session.createdAt()); json.put("_savedAt", session.savedAt()); JsonDocument doc = JsonDocument.create(N1Q.qualifyId(SESSION, session.id()), expiry, json); bucket.upsert(doc); }
/** * Performs the {@link #update(String, String, Map)} operation via Key/Value ("replace"). * * @param docId the document ID * @param values the values to update the document with. * @return The result of the operation. */ private Status updateKv(final String docId, final Map<String, ByteIterator> values) { waitForMutationResponse(bucket.async().replace( RawJsonDocument.create(docId, documentExpiry, encode(values)), persistTo, replicateTo )); return Status.OK; }
@Override public Observable<Long> execute(final Class<?> entityClass, final Object id, final PersistTo persistTo, final ReplicateTo replicateTo) { String qId = N1Q.qualifyId(entityClass, id); JsonDocument doc = JsonDocument.create(qId, null, cas); return bucket.remove(doc, persistTo, replicateTo).map(CAS); } };
@Override public Session get(final Builder builder) { return Optional .ofNullable(bucket.getAndTouch(N1Q.qualifyId(SESSION, builder.sessionId()), expiry)) .map(doc -> { Map session = doc.content().toMap(); Long accessedAt = (Long) session.remove("_accessedAt"); Long createdAt = (Long) session.remove("_createdAt"); Long savedAt = (Long) session.remove("_savedAt"); return builder .accessedAt(accessedAt) .createdAt(createdAt) .savedAt(savedAt) .set(session) .build(); }).orElse(null); }
@Test public void testBasicConvertIntKey() throws Exception { int key = 5; String testContent = "hello world"; Record record = new Record(key, testContent); Converter<String, String, Object, RawJsonDocument> recordConverter = new AnyToCouchbaseJsonConverter(); RawJsonDocument returnDoc = recordConverter.convertRecord("", record, null).iterator().next(); Assert.assertEquals(key+"", returnDoc.id(), "key should be equal"); Record convertedRecord = GSON.fromJson(returnDoc.content(), Record.class); Assert.assertEquals(convertedRecord.key, key); Assert.assertEquals(convertedRecord.value, testContent, "value in content should be equal"); }
void onWrite(AbstractDocument doc) throws UnsupportedEncodingException { recordClass = doc.getClass(); if (doc instanceof TupleDocument) { ByteBuf outgoingBuf = (((TupleDocument) doc).content()).value1(); byte[] outgoingBytes = new byte[outgoingBuf.readableBytes()]; outgoingBuf.getBytes(0, outgoingBytes); verificationCache.put(doc.id(), outgoingBytes); } else if (doc instanceof RawJsonDocument) { verificationCache.put(doc.id(), ((RawJsonDocument) doc).content().getBytes("UTF-8")); } else { throw new UnsupportedOperationException("Can only support TupleDocument or RawJsonDocument at this time"); } }
/** * Performs the {@link #read(String, String, Set, Map)} operation via Key/Value ("get"). * * @param docId the document ID * @param fields the fields to be loaded * @param result the result map where the doc needs to be converted into * @return The result of the operation. */ private Status readKv(final String docId, final Set<String> fields, final Map<String, ByteIterator> result) throws Exception { RawJsonDocument loaded = bucket.get(docId, RawJsonDocument.class); if (loaded == null) { return Status.NOT_FOUND; } decode(loaded.content(), fields, result); return Status.OK; }
@Override public <K, V> AtomicCacheEntry<K, V, Long> fetch(K key, Serializer<K> keySerializer, Deserializer<V> valueDeserializer) throws IOException { final String docId = toDocumentId(key, keySerializer); final BinaryDocument doc = bucket.get(BinaryDocument.create(docId)); if (doc == null) { return null; } final V value = deserialize(doc, valueDeserializer); return new AtomicCacheEntry<>(key, value, doc.cas()); }
private <V> Document toDocument(String docId, V value, Serializer<V> valueSerializer, long revision) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); valueSerializer.serialize(value, bos); final ByteBuf byteBuf = Unpooled.wrappedBuffer(bos.toByteArray()); return BinaryDocument.create(docId, byteBuf, revision); }
private static Function<Object, Object> idGen(final Bucket bucket) { return entity -> IdGenerator.getOrGenId(entity, () -> bucket.counter(entity.getClass().getName(), 1, 1).content()); }
public abstract <T> Observable<T> execute(EntityDocument<Object> entity, PersistTo persistTo, ReplicateTo replicateTo);
private <V> V deserialize(BinaryDocument doc, Deserializer<V> valueDeserializer) throws IOException { if (doc == null) { return null; } final ByteBuf byteBuf = doc.content(); final byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes); byteBuf.release(); return valueDeserializer.deserialize(bytes); }
@Override public <T> Observable<AsyncViewQueryResult<T>> query(final ViewQuery query) { return bucket.query(query) .map(result -> { Observable<List<T>> rows = result.rows() .flatMap(r -> r.document() .map(doc -> { EntityDocument<T> entity = converter.toEntity(doc, null); return entity.content(); })) .toList(); return new AsyncViewQueryResult(result.totalRows(), rows); }); }
try { waitForMutationResponse(bucket.async().insert( RawJsonDocument.create(docId, documentExpiry, encode(values)), persistTo, replicateTo
@Override public <K, V> V get(K key, Serializer<K> keySerializer, Deserializer<V> valueDeserializer) throws IOException { final String docId = toDocumentId(key, keySerializer); final BinaryDocument doc = bucket.get(BinaryDocument.create(docId)); return deserialize(doc, valueDeserializer); }
/** * Performs the {@link #upsert(String, String, Map)} operation via Key/Value ("upsert"). * * If this option should be used, the "-p couchbase.upsert=true" property must be set. * * @param docId the document ID * @param values the values to update the document with. * @return The result of the operation. */ private Status upsertKv(final String docId, final Map<String, ByteIterator> values) { waitForMutationResponse(bucket.async().upsert( RawJsonDocument.create(docId, documentExpiry, encode(values)), persistTo, replicateTo )); return Status.OK; }