Java Code Examples for com.couchbase.client.core.CouchbaseException

The following examples show how to use com.couchbase.client.core.CouchbaseException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: localization_nifi   Source File: CouchbaseClusterService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Establish a connection to a Couchbase cluster.
 * @param context the configuration context
 * @throws InitializationException if unable to connect a Couchbase cluster
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    for(PropertyDescriptor p : context.getProperties().keySet()){
        if(p.isDynamic() && p.getName().startsWith(DYNAMIC_PROP_BUCKET_PASSWORD)){
            String bucketName = p.getName().substring(DYNAMIC_PROP_BUCKET_PASSWORD.length());
            String password = context.getProperty(p).getValue();
            bucketPasswords.put(bucketName, password);
        }
    }
    try {
        cluster = CouchbaseCluster.fromConnectionString(context.getProperty(CONNECTION_STRING).getValue());
    } catch(CouchbaseException e) {
        throw new InitializationException(e);
    }
}
 
Example 2
Source Project: localization_nifi   Source File: TestGetCouchbaseKey.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCouchbaseInvalidInputError() throws Exception {
    String docIdExp = "doc-c";

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new RequestTooBigException();
    when(bucket.get(docIdExp, RawJsonDocument.class))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.setProperty(DOC_ID, docIdExp);

    String inputFileDataStr = "input FlowFile data";
    byte[] inFileData = inputFileDataStr.getBytes(StandardCharsets.UTF_8);
    testRunner.enqueue(inFileData);
    testRunner.run();

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_ORIGINAL, 0);
    testRunner.assertTransferCount(REL_RETRY, 0);
    testRunner.assertTransferCount(REL_FAILURE, 1);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_FAILURE).get(0);
    orgFile.assertContentEquals(inputFileDataStr);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 3
Source Project: localization_nifi   Source File: TestGetCouchbaseKey.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCouchbaseTempClusterError() throws Exception {
    String docIdExp = "doc-c";

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new BackpressureException();
    when(bucket.get(docIdExp, RawJsonDocument.class))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.setProperty(DOC_ID, docIdExp);

    String inputFileDataStr = "input FlowFile data";
    byte[] inFileData = inputFileDataStr.getBytes(StandardCharsets.UTF_8);
    testRunner.enqueue(inFileData);
    testRunner.run();

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_ORIGINAL, 0);
    testRunner.assertTransferCount(REL_RETRY, 1);
    testRunner.assertTransferCount(REL_FAILURE, 0);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_RETRY).get(0);
    orgFile.assertContentEquals(inputFileDataStr);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 4
Source Project: localization_nifi   Source File: TestGetCouchbaseKey.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCouchbaseTempFlowFileError() throws Exception {
    String docIdExp = "doc-c";

    Bucket bucket = mock(Bucket.class);
    // There is no suitable CouchbaseException for temp flowfile error, currently.
    CouchbaseException exception = new DurabilityException();
    when(bucket.get(docIdExp, RawJsonDocument.class))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.setProperty(DOC_ID, docIdExp);

    String inputFileDataStr = "input FlowFile data";
    byte[] inFileData = inputFileDataStr.getBytes(StandardCharsets.UTF_8);
    testRunner.enqueue(inFileData);
    testRunner.run();

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_ORIGINAL, 0);
    testRunner.assertTransferCount(REL_RETRY, 1);
    testRunner.assertTransferCount(REL_FAILURE, 0);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_RETRY).get(0);
    orgFile.assertContentEquals(inputFileDataStr);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 5
Source Project: localization_nifi   Source File: TestGetCouchbaseKey.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCouchbaseFatalError() throws Exception {
    String docIdExp = "doc-c";

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new NotConnectedException();
    when(bucket.get(docIdExp, RawJsonDocument.class))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.setProperty(DOC_ID, docIdExp);

    String inputFileDataStr = "input FlowFile data";
    byte[] inFileData = inputFileDataStr.getBytes(StandardCharsets.UTF_8);
    testRunner.enqueue(inFileData);
    testRunner.run();

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_ORIGINAL, 0);
    testRunner.assertTransferCount(REL_RETRY, 1);
    testRunner.assertTransferCount(REL_FAILURE, 0);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_RETRY).get(0);
    orgFile.assertContentEquals(inputFileDataStr);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 6
Source Project: couchbase-jvm-core   Source File: ConnectionString.java    License: Apache License 2.0 6 votes vote down vote up
static Map<String, String> parseParams(final String input) {
    try {
        String[] parts = input.split("\\?");
        Map<String, String> params = new HashMap<String, String>();
        if (parts.length > 1) {
            String found = parts[1];
            String[] exploded = found.split("&");
            for (int i = 0; i < exploded.length; i++) {
                String[] pair = exploded[i].split("=");
                params.put(pair[0], pair[1]);
            }
        }
        return params;
    } catch(Exception ex) {
        throw new CouchbaseException("Could not parse Params of connection string: " + input, ex);
    }
}
 
Example 7
Source Project: couchbase-jvm-core   Source File: DefaultNodeInfo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link DefaultNodeInfo} with no SSL services.
 *
 * @param viewUri  the URI of the view service.
 * @param hostname the hostname of the node.
 * @param ports    the port list of the node services.
 */
@JsonCreator
public DefaultNodeInfo(
    @JsonProperty("couchApiBase") String viewUri,
    @JsonProperty("hostname") String hostname,
    @JsonProperty("ports") Map<String, Integer> ports,
    @JsonProperty("alternateAddresses") Map<String, AlternateAddress> alternateAddresses) {
    if (hostname == null) {
        throw new CouchbaseException(new IllegalArgumentException("NodeInfo hostname cannot be null"));
    }
    this.alternateAddresses = alternateAddresses == null
        ? Collections.<String, AlternateAddress>emptyMap()
        : alternateAddresses;

    this.hostname = trimPort(hostname);
    this.directServices = parseDirectServices(viewUri, ports);
    this.sslServices = new HashMap<>();
}
 
Example 8
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
    if (KeyValueStatus.SUCCESS.code() == msg.getStatus()) {
        String content = msg.content().toString(CharsetUtil.UTF_8);
        ErrorMap errorMap = ErrorMap.fromJson(content);
        LOGGER.debug("Trying to update Error Map With Version {}, Revision {}.",
            errorMap.version(), errorMap.revision());
        ResponseStatusConverter.updateBinaryErrorMap(errorMap);
        originalPromise.setSuccess();
        ctx.pipeline().remove(this);
        ctx.fireChannelActive();
    } else {
        LOGGER.warn("Could not load extended error map, because the server responded with an error. Error " +
            "code {}", Integer.toHexString(msg.getStatus()));
        originalPromise.setFailure(new CouchbaseException("Could not load extended error map, " +
            "because the server responded with an error. "));
    }
}
 
Example 9
@Test
public void shouldFailObservableIfCouldNotConnect() {
    InstrumentedService service = new InstrumentedService(host, bucket, password, port, ctx, factory);

    Endpoint endpoint = mock(Endpoint.class);
    final EndpointStates endpointStates = new EndpointStates(LifecycleState.DISCONNECTED);
    when(endpoint.states()).thenReturn(endpointStates.states());
    when(endpoint.connect()).thenReturn(Observable.just(LifecycleState.DISCONNECTED));
    when(factory.create(host, bucket, bucket, password, port, ctx)).thenReturn(endpoint);

    CouchbaseRequest req = mock(CouchbaseRequest.class);
    AsyncSubject<CouchbaseResponse> reqObservable = AsyncSubject.create();
    when(req.observable()).thenReturn(reqObservable);

    try {
        service.send(req);
        reqObservable.toBlocking().single();
        assertTrue("Should've failed but did not", false);
    } catch(CouchbaseException ex) {
        assertEquals("Could not connect endpoint.", ex.getMessage());
    } catch(Throwable tr) {
        assertTrue(tr.getMessage(), false);
    }
}
 
Example 10
Source Project: couchbase-jvm-core   Source File: KeyValueHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = CouchbaseException.class)
public void shouldFailWhenOpaqueDoesNotMatch() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);
    response.setOpaque(1);

    PrependRequest requestMock = mock(PrependRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    AsyncSubject<CouchbaseResponse> responseSubject = AsyncSubject.<CouchbaseResponse>create();
    when(requestMock.observable()).thenReturn(responseSubject);
    when(requestMock.content()).thenReturn(requestContent);
    when(requestMock.opaque()).thenReturn(3);
    requestQueue.add(requestMock);

    channel.writeInbound(response);
    assertEquals(0, content.refCnt());
    responseSubject.toBlocking().single();
}
 
Example 11
Source Project: nifi   Source File: CouchbaseClusterService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Establish a connection to a Couchbase cluster.
 * @param context the configuration context
 * @throws InitializationException if unable to connect a Couchbase cluster
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    bucketPasswords = new HashMap<>();
    for(PropertyDescriptor p : context.getProperties().keySet()){
        if(p.isDynamic() && p.getName().startsWith(DYNAMIC_PROP_BUCKET_PASSWORD)){
            String bucketName = p.getName().substring(DYNAMIC_PROP_BUCKET_PASSWORD.length());
            String password = context.getProperty(p).evaluateAttributeExpressions().getValue();
            bucketPasswords.put(bucketName, password);
        }
    }

    final String userName = context.getProperty(USER_NAME).evaluateAttributeExpressions().getValue();
    final String userPassword = context.getProperty(USER_PASSWORD).evaluateAttributeExpressions().getValue();

    try {
        cluster = CouchbaseCluster.fromConnectionString(context.getProperty(CONNECTION_STRING).evaluateAttributeExpressions().getValue());
        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPassword)) {
            cluster.authenticate(userName, userPassword);
        }
    } catch(CouchbaseException e) {
        throw new InitializationException(e);
    }
}
 
Example 12
Source Project: nifi   Source File: TestGetCouchbaseKey.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCouchbaseInvalidInputError() throws Exception {
    String docIdExp = "doc-c";

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new RequestTooBigException();
    when(bucket.get(docIdExp, RawJsonDocument.class))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.setProperty(DOC_ID, docIdExp);

    String inputFileDataStr = "input FlowFile data";
    byte[] inFileData = inputFileDataStr.getBytes(StandardCharsets.UTF_8);
    testRunner.enqueue(inFileData);
    testRunner.run();

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_ORIGINAL, 0);
    testRunner.assertTransferCount(REL_RETRY, 0);
    testRunner.assertTransferCount(REL_FAILURE, 1);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_FAILURE).get(0);
    orgFile.assertContentEquals(inputFileDataStr);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 13
Source Project: nifi   Source File: TestGetCouchbaseKey.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCouchbaseTempClusterError() throws Exception {
    String docIdExp = "doc-c";

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new BackpressureException();
    when(bucket.get(docIdExp, RawJsonDocument.class))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.setProperty(DOC_ID, docIdExp);

    String inputFileDataStr = "input FlowFile data";
    byte[] inFileData = inputFileDataStr.getBytes(StandardCharsets.UTF_8);
    testRunner.enqueue(inFileData);
    testRunner.run();

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_ORIGINAL, 0);
    testRunner.assertTransferCount(REL_RETRY, 1);
    testRunner.assertTransferCount(REL_FAILURE, 0);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_RETRY).get(0);
    orgFile.assertContentEquals(inputFileDataStr);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 14
Source Project: nifi   Source File: TestGetCouchbaseKey.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCouchbaseFatalError() throws Exception {
    String docIdExp = "doc-c";

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new NotConnectedException();
    when(bucket.get(docIdExp, RawJsonDocument.class))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.setProperty(DOC_ID, docIdExp);

    String inputFileDataStr = "input FlowFile data";
    byte[] inFileData = inputFileDataStr.getBytes(StandardCharsets.UTF_8);
    testRunner.enqueue(inFileData);
    testRunner.run();

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_ORIGINAL, 0);
    testRunner.assertTransferCount(REL_RETRY, 1);
    testRunner.assertTransferCount(REL_FAILURE, 0);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_RETRY).get(0);
    orgFile.assertContentEquals(inputFileDataStr);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 15
/**
 * Returns a registered error handling strategy.
 * @param e the CouchbaseException
 * @return a registered strategy, if it's not registered, then return Fatal
 */
public static ErrorHandlingStrategy getStrategy(CouchbaseException e){
    ErrorHandlingStrategy strategy = mapping.get(e.getClass());
    if(strategy == null) {
        // Treat unknown Exception as Fatal.
        return ErrorHandlingStrategy.Fatal;
    }
    return strategy;
}
 
Example 16
/**
 * Handles the thrown CouchbaseException accordingly.
 *
 * @param context a process context
 * @param session a process session
 * @param logger a logger
 * @param inFile an input FlowFile
 * @param e the thrown CouchbaseException
 * @param errMsg a message to be logged
 */
protected void handleCouchbaseException(final ProcessContext context, final ProcessSession session,
    final ComponentLog logger, FlowFile inFile, CouchbaseException e,
    String errMsg) {
    logger.error(errMsg, e);
    if (inFile != null) {
        ErrorHandlingStrategy strategy = CouchbaseExceptionMappings.getStrategy(e);
        switch (strategy.penalty()) {
            case Penalize:
                if (logger.isDebugEnabled()) {
                    logger.debug("Penalized: {}", new Object[] {inFile});
                }
                inFile = session.penalize(inFile);
                break;
            case Yield:
                if (logger.isDebugEnabled()) {
                    logger.debug("Yielded context: {}", new Object[] {inFile});
                }
                context.yield();
                break;
            case None:
                break;
        }

        switch (strategy.result()) {
            case ProcessException:
                throw new ProcessException(errMsg, e);
            case Failure:
                inFile = session.putAttribute(inFile, CouchbaseAttributes.Exception.key(), e.getClass().getName());
                session.transfer(inFile, REL_FAILURE);
                break;
            case Retry:
                inFile = session.putAttribute(inFile, CouchbaseAttributes.Exception.key(), e.getClass().getName());
                session.transfer(inFile, REL_RETRY);
                break;
        }
    }
}
 
Example 17
Source Project: localization_nifi   Source File: TestPutCouchbaseKey.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCouchbaseTempFlowFileError() throws Exception {

    String docId = "doc-a";

    String inFileData = "{\"key\":\"value\"}";
    byte[] inFileDataBytes = inFileData.getBytes(StandardCharsets.UTF_8);

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new DurabilityException();
    when(bucket.upsert(any(RawJsonDocument.class), eq(PersistTo.NONE), eq(ReplicateTo.ONE)))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.enqueue(inFileDataBytes);
    testRunner.setProperty(DOC_ID, docId);
    testRunner.setProperty(PutCouchbaseKey.REPLICATE_TO, ReplicateTo.ONE.toString());
    testRunner.run();

    verify(bucket, times(1)).upsert(any(RawJsonDocument.class), eq(PersistTo.NONE), eq(ReplicateTo.ONE));

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_RETRY, 1);
    testRunner.assertTransferCount(REL_FAILURE, 0);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_RETRY).get(0);
    orgFile.assertContentEquals(inFileData);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}
 
Example 18
Source Project: samza   Source File: TestCouchbaseTableWriteFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAsyncException() {
  String key = "throwExceptionKey";
  JsonObject value = JsonObject.create();
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableWriteFunction<JsonObject> writeFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.upsert(any(Document.class), anyLong(), any(TimeUnit.class))).thenReturn(
      Observable.error(new CouchbaseException()));
  assertTrue(writeFunction.putAsync(key, value).isCompletedExceptionally());
}
 
Example 19
Source Project: samza   Source File: TestCouchbaseTableWriteFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteAsyncException() {
  String key = "throwExceptionKey";
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableWriteFunction<JsonObject> writeFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.remove(eq(key), anyLong(), any(TimeUnit.class))).thenReturn(
      Observable.error(new CouchbaseException()));
  assertTrue(writeFunction.deleteAsync(key).isCompletedExceptionally());
}
 
Example 20
Source Project: samza   Source File: TestCouchbaseTableReadFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAsyncException() {
  String key = "throwExceptionKey";
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableReadFunction readFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.get(eq(key), anyObject(), anyLong(), any(TimeUnit.class))).thenReturn(
      Observable.error(new CouchbaseException()));
  assertTrue(readFunction.getAsync(key).isCompletedExceptionally());
}
 
Example 21
Source Project: couchbase-jvm-core   Source File: ConnectionString.java    License: Apache License 2.0 5 votes vote down vote up
static Scheme parseScheme(final String input) {
    if (input.startsWith("couchbase://")) {
        return Scheme.COUCHBASE;
    } else if (input.startsWith("couchbases://")) {
        return Scheme.COUCHBASES;
    } else if (input.startsWith("http://")) {
        return Scheme.HTTP;
    } else {
        throw new CouchbaseException("Could not parse Scheme of connection string: " + input);
    }
}
 
Example 22
Source Project: couchbase-jvm-core   Source File: Events.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Takes a {@link CouchbaseEvent} and generates a JSON string.
 *
 * @param source the source event.
 * @param pretty if pretty print should be used.
 * @return the generated json string.
 */
public static String toJson(CouchbaseEvent source, boolean pretty) {
    try {
        if (pretty) {
            return DefaultObjectMapper.prettyWriter().writeValueAsString(source.toMap());
        } else {
            return DefaultObjectMapper.writeValueAsString(source.toMap());
        }
    } catch (JsonProcessingException e) {
        throw new CouchbaseException("Could not convert CouchbaseEvent " + source.toString() + " to JSON: ", e);
    }
}
 
Example 23
Source Project: couchbase-jvm-core   Source File: DefaultNodeInfo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link DefaultNodeInfo} with SSL services.
 *
 * @param hostname the hostname of the node.
 * @param direct   the port list of the direct node services.
 * @param ssl      the port list of the ssl node services.
 */
public DefaultNodeInfo(String hostname, Map<ServiceType, Integer> direct,
    Map<ServiceType, Integer> ssl, Map<String, AlternateAddress> alternateAddresses) {
    if (hostname == null) {
        throw new CouchbaseException(new IllegalArgumentException("NodeInfo hostname cannot be null"));
    }

    this.hostname = hostname;
    this.directServices = direct;
    this.sslServices = ssl;
    this.alternateAddresses = alternateAddresses == null
        ? Collections.<String, AlternateAddress>emptyMap()
        : alternateAddresses;
}
 
Example 24
Source Project: couchbase-jvm-core   Source File: BucketConfigParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parse a raw configuration into a {@link BucketConfig}.
 *
 * @param input the raw string input.
 * @param env the environment to use.
 * @param origin the origin of the configuration. If null / none provided then localhost is assumed.
 * @return the parsed bucket configuration.
 */
public static BucketConfig parse(final String input, final ConfigParserEnvironment env, final String origin) {
    try {
        InjectableValues inject = new InjectableValues.Std()
                .addValue("env", env)
                .addValue("origin", origin == null ? "127.0.0.1" : origin);
        return DefaultObjectMapper.reader()
                .forType(BucketConfig.class)
                .with(inject)
                .with(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
                .readValue(input);
    } catch (IOException e) {
        throw new CouchbaseException("Could not parse configuration", e);
    }
}
 
Example 25
Source Project: couchbase-jvm-core   Source File: ObservablesTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Heper method to test fail-safe functionality.
 *
 * @param scheduler the scheduler to test against. if null, it will be failed on the current thread.
 * @param threadName the part of a thread name to match against for additional verification.
 */
private static void testFailSafe(final Scheduler scheduler, final String threadName) {
    Subject<CouchbaseResponse, CouchbaseResponse> subject = AsyncSubject.create();
    TestSubscriber<CouchbaseResponse> subscriber = TestSubscriber.create();
    subject.subscribe(subscriber);
    Exception failure = new CouchbaseException("Some Error");

    Observables.failSafe(scheduler, scheduler != null, subject, failure);

    subscriber.awaitTerminalEvent();
    subscriber.assertError(failure);
    assertTrue(subscriber.getLastSeenThread().getName().contains(threadName));
}
 
Example 26
Source Project: couchbase-jvm-core   Source File: CarrierRefresherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFallbackToNextOnPollWhenFirstFails() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    BucketConfig config = mock(BucketConfig.class);

    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.provider(provider);

    when(config.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();

    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "1.2.3.4:8091", ports, null));
    nodeInfos.add(new DefaultNodeInfo(null, "2.3.4.5:8091", ports, null));
    when(config.nodes()).thenReturn(nodeInfos);

    ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8);
    Observable<CouchbaseResponse> goodResponse = Observable.just((CouchbaseResponse) new GetBucketConfigResponse(
        ResponseStatus.SUCCESS, KeyValueStatus.SUCCESS.code(),
        "bucket",
        content,
        "1.2.3.4"
    ));
    Observable<CouchbaseResponse> badResponse = Observable.error(new CouchbaseException("Failure"));
    when(cluster.send(any(GetBucketConfigRequest.class))).thenReturn(badResponse, goodResponse);
    refresher.markTainted(config);

    Thread.sleep(1500);

    verify(provider, times(1)).proposeBucketConfig(any(ProposedBucketConfigContext.class));
    assertEquals(0, content.refCnt());
}
 
Example 27
Source Project: couchbase-jvm-core   Source File: CarrierRefresherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIgnoreNodeWithoutKVServiceEnabled() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    BucketConfig config = mock(BucketConfig.class);

    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.provider(provider);

    when(config.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();

    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "1.2.3.4:8091", ports, null));
    nodeInfos.add(new DefaultNodeInfo(null, "6.7.8.9:8091", new HashMap<String, Integer>(), null));
    nodeInfos.add(new DefaultNodeInfo(null, "2.3.4.5:8091", ports, null));
    when(config.nodes()).thenReturn(nodeInfos);

    ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8);
    Observable<CouchbaseResponse> goodResponse = Observable.just((CouchbaseResponse) new GetBucketConfigResponse(
            ResponseStatus.SUCCESS, KeyValueStatus.SUCCESS.code(),
            "bucket",
            content,
        "1.2.3.4"
    ));
    Observable<CouchbaseResponse> badResponse = Observable.error(new CouchbaseException("Failure"));
    when(cluster.send(any(GetBucketConfigRequest.class))).thenReturn(badResponse, goodResponse);
    refresher.markTainted(config);

    Thread.sleep(1500);

    verify(provider, times(1)).proposeBucketConfig(any(ProposedBucketConfigContext.class));
    assertEquals(0, content.refCnt());
}
 
Example 28
Source Project: nifi   Source File: CouchbaseExceptionMappings.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a registered error handling strategy.
 * @param e the CouchbaseException
 * @return a registered strategy, if it's not registered, then return Fatal
 */
public static ErrorHandlingStrategy getStrategy(CouchbaseException e){
    ErrorHandlingStrategy strategy = mapping.get(e.getClass());
    if(strategy == null) {
        // Treat unknown Exception as Fatal.
        return ErrorHandlingStrategy.Fatal;
    }
    return strategy;
}
 
Example 29
Source Project: nifi   Source File: AbstractCouchbaseProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles the thrown CouchbaseException accordingly.
 *
 * @param context a process context
 * @param session a process session
 * @param logger a logger
 * @param inFile an input FlowFile
 * @param e the thrown CouchbaseException
 * @param errMsg a message to be logged
 */
protected void handleCouchbaseException(final ProcessContext context, final ProcessSession session,
    final ComponentLog logger, FlowFile inFile, CouchbaseException e,
    String errMsg) {
    logger.error(errMsg, e);
    if (inFile != null) {
        ErrorHandlingStrategy strategy = CouchbaseExceptionMappings.getStrategy(e);
        switch (strategy.penalty()) {
            case Penalize:
                if (logger.isDebugEnabled()) {
                    logger.debug("Penalized: {}", new Object[] {inFile});
                }
                inFile = session.penalize(inFile);
                break;
            case Yield:
                if (logger.isDebugEnabled()) {
                    logger.debug("Yielded context: {}", new Object[] {inFile});
                }
                context.yield();
                break;
            case None:
                break;
        }

        switch (strategy.result()) {
            case ProcessException:
                throw new ProcessException(errMsg, e);
            case Failure:
                inFile = session.putAttribute(inFile, CouchbaseAttributes.Exception.key(), e.getClass().getName());
                session.transfer(inFile, REL_FAILURE);
                break;
            case Retry:
                inFile = session.putAttribute(inFile, CouchbaseAttributes.Exception.key(), e.getClass().getName());
                session.transfer(inFile, REL_RETRY);
                break;
        }
    }
}
 
Example 30
Source Project: nifi   Source File: TestPutCouchbaseKey.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCouchbaseTempFlowFileError() throws Exception {

    String docId = "doc-a";

    String inFileData = "{\"key\":\"value\"}";
    byte[] inFileDataBytes = inFileData.getBytes(StandardCharsets.UTF_8);

    Bucket bucket = mock(Bucket.class);
    CouchbaseException exception = new DurabilityException();
    when(bucket.upsert(any(RawJsonDocument.class), eq(PersistTo.NONE), eq(ReplicateTo.ONE)))
        .thenThrow(exception);
    setupMockBucket(bucket);

    testRunner.enqueue(inFileDataBytes);
    testRunner.setProperty(DOC_ID, docId);
    testRunner.setProperty(PutCouchbaseKey.REPLICATE_TO, ReplicateTo.ONE.toString());
    testRunner.run();

    verify(bucket, times(1)).upsert(any(RawJsonDocument.class), eq(PersistTo.NONE), eq(ReplicateTo.ONE));

    testRunner.assertTransferCount(REL_SUCCESS, 0);
    testRunner.assertTransferCount(REL_RETRY, 1);
    testRunner.assertTransferCount(REL_FAILURE, 0);
    MockFlowFile orgFile = testRunner.getFlowFilesForRelationship(REL_RETRY).get(0);
    orgFile.assertContentEquals(inFileData);
    orgFile.assertAttributeEquals(Exception.key(), exception.getClass().getName());
}