org.apache.qpid.proton.amqp.transport.ErrorCondition Java Examples

The following examples show how to use org.apache.qpid.proton.amqp.transport.ErrorCondition. 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 File: ErrorConditionType.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
public ErrorCondition newInstance(Object described)
{
    List l = (List) described;

    ErrorCondition o = new ErrorCondition();

    if(l.isEmpty())
    {
        throw new DecodeException("The condition field cannot be omitted");
    }

    switch(3 - l.size())
    {

        case 0:
            o.setInfo( (Map) l.get( 2 ) );
        case 1:
            o.setDescription( (String) l.get( 1 ) );
        case 2:
            o.setCondition( (Symbol) l.get( 0 ) );
    }


    return o;
}
 
Example #2
Source File: AbstractProtocolAdapterBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an AMQP error condition for an throwable.
 * <p>
 * Non {@link ServiceInvocationException} instances are mapped to {@link AmqpError#PRECONDITION_FAILED}.
 *
 * @param t The throwable to map to an error condition.
 * @return The error condition.
 */
protected final ErrorCondition getErrorCondition(final Throwable t) {
    if (ServiceInvocationException.class.isInstance(t)) {
        final ServiceInvocationException error = (ServiceInvocationException) t;
        switch (error.getErrorCode()) {
        case HttpURLConnection.HTTP_BAD_REQUEST:
            return ProtonHelper.condition(Constants.AMQP_BAD_REQUEST, error.getMessage());
        case HttpURLConnection.HTTP_FORBIDDEN:
            return ProtonHelper.condition(AmqpError.UNAUTHORIZED_ACCESS, error.getMessage());
        case HttpUtils.HTTP_TOO_MANY_REQUESTS:
            return ProtonHelper.condition(AmqpError.RESOURCE_LIMIT_EXCEEDED, error.getMessage());
        default:
            return ProtonHelper.condition(AmqpError.PRECONDITION_FAILED, error.getMessage());
        }
    } else {
        return ProtonHelper.condition(AmqpError.PRECONDITION_FAILED, t.getMessage());
    }
}
 
Example #3
Source File: AmqpSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateRedirectionExceptionWithNoNetworkHost() throws URISyntaxException {
    AmqpProvider mockProvider = Mockito.mock(AmqpProvider.class);
    Mockito.when(mockProvider.getRemoteURI()).thenReturn(new URI("amqp://localhost:5672"));

    ErrorCondition condition = new ErrorCondition();

    Map<Symbol, Object> info = new HashMap<>();
    info.put(AmqpSupport.PORT, "5672");
    info.put(AmqpSupport.OPEN_HOSTNAME, "localhost");
    info.put(AmqpSupport.SCHEME, "amqp");
    info.put(AmqpSupport.PATH, "websocket");

    condition.setInfo(info);

    Symbol error = AmqpError.INTERNAL_ERROR;
    String message = "Failed to connect";

    Exception result = AmqpSupport.createRedirectException(mockProvider, error, message, condition);

    assertNotNull(result);
    assertFalse(result instanceof ProviderConnectionRedirectedException);
    assertTrue(result instanceof ProviderException);
}
 
Example #4
Source File: AmqpSinkBridgeEndpointMockTest.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@Test
public <K, V> void filters_negativeIntegerPartitionFilter() throws Exception {
    String topic = "my_topic";
    Vertx vertx = Vertx.vertx();
    AmqpSinkBridgeEndpoint<K, V> endpoint = (AmqpSinkBridgeEndpoint) new AmqpSinkBridgeEndpoint<>(vertx, BridgeConfig.fromMap(config),
            EmbeddedFormat.JSON, new StringDeserializer(), new ByteArrayDeserializer());
    endpoint.open();
    ProtonSender mockSender = mockSender(ProtonQoS.AT_MOST_ONCE, topic + "/group.id/blah");
    // Call handle()
    Map<Symbol, Object> filter = new HashMap<>();
    filter.put(Symbol.getSymbol(AmqpBridge.AMQP_PARTITION_FILTER), -1);
    filter.put(Symbol.getSymbol(AmqpBridge.AMQP_OFFSET_FILTER), 10L);
    ((Source) mockSender.getRemoteSource()).setFilter(filter);
    endpoint.handle(new AmqpEndpoint(mockSender));

    ArgumentCaptor<ErrorCondition> errorCap = ArgumentCaptor.forClass(ErrorCondition.class);
    verify(mockSender).setCondition(errorCap.capture());
    verify(mockSender).close();

    assertDetach(mockSender,
            AmqpBridge.AMQP_ERROR_WRONG_FILTER,
            "Wrong filter");
}
 
Example #5
Source File: AmqpSupport.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to read and return the embedded error message in the given ErrorCondition
 * object.  If no message can be extracted a generic message is returned.
 *
 * @param errorCondition
 *      The ErrorCondition to extract the error message from.
 *
 * @return an error message extracted from the given ErrorCondition.
 */
public static String extractErrorMessage(ErrorCondition errorCondition) {
    String message = "Received error from remote peer without description";
    if (errorCondition != null) {
        if (errorCondition.getDescription() != null && !errorCondition.getDescription().isEmpty()) {
            message = errorCondition.getDescription();
        }

        Symbol condition = errorCondition.getCondition();
        if (condition != null) {
            message = message + " [condition = " + condition + "]";
        }
    }

    return message;
}
 
Example #6
Source File: AMQPSessionCallback.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public int sendMessage(MessageReference ref, Message message, ServerConsumer consumer, int deliveryCount) {

   ProtonServerSenderContext plugSender = (ProtonServerSenderContext) consumer.getProtocolContext();

   try {
      return plugSender.deliverMessage(ref, consumer);
   } catch (Exception e) {
      connection.runNow(() -> {
         plugSender.getSender().setCondition(new ErrorCondition(AmqpError.INTERNAL_ERROR, e.getMessage()));
         connection.flush();
      });
      throw new IllegalStateException("Can't deliver message " + e, e);
   }

}
 
Example #7
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the connection is rejected as the connection limit for 
 * the given tenant is exceeded.
 */
@Test
public void testConnectionFailsIfTenantLevelConnectionLimitIsExceeded() {
    // GIVEN an AMQP adapter that requires devices to authenticate
    config.setAuthenticationRequired(true);
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();
    // WHEN the connection limit for the given tenant exceeds
    when(resourceLimitChecks.isConnectionLimitReached(any(TenantObject.class), any(SpanContext.class)))
            .thenReturn(Future.succeededFuture(Boolean.TRUE));
    // WHEN a device connects
    final Device authenticatedDevice = new Device(TEST_TENANT_ID, TEST_DEVICE);
    final Record record = new RecordImpl();
    record.set(AmqpAdapterConstants.KEY_CLIENT_DEVICE, Device.class, authenticatedDevice);
    final ProtonConnection deviceConnection = mock(ProtonConnection.class);
    when(deviceConnection.attachments()).thenReturn(record);
    adapter.onConnectRequest(deviceConnection);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandler = ArgumentCaptor
            .forClass(Handler.class);
    verify(deviceConnection).openHandler(openHandler.capture());
    openHandler.getValue().handle(Future.succeededFuture(deviceConnection));
    // THEN the adapter does not accept the incoming connection request. 
    final ArgumentCaptor<ErrorCondition> errorConditionCaptor = ArgumentCaptor.forClass(ErrorCondition.class);
    verify(deviceConnection).setCondition(errorConditionCaptor.capture());
    assertEquals(AmqpError.UNAUTHORIZED_ACCESS, errorConditionCaptor.getValue().getCondition());
}
 
Example #8
Source File: AmqpSupport.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
/**
 * When a redirect type exception is received this method is called to create the
 * appropriate redirect exception type containing the error details needed.
 *
 * @param provider
 * 		  the AMQP provider instance that originates this exception
 * @param error
 *        the Symbol that defines the redirection error type.
 * @param message
 *        the basic error message that should used or amended for the returned exception.
 * @param condition
 *        the ErrorCondition that describes the redirection.
 *
 * @return an Exception that captures the details of the redirection error.
 */
public static ProviderConnectionRemotelyClosedException createRedirectException(AmqpProvider provider, Symbol error, String message, ErrorCondition condition) {
    ProviderConnectionRemotelyClosedException result = null;
    Map<?, ?> info = condition.getInfo();

    if (info == null) {
        result = new ProviderConnectionRemotelyClosedException(message + " : Redirection information not set.");
    } else {
        @SuppressWarnings("unchecked")
        AmqpRedirect redirect = new AmqpRedirect((Map<Symbol, Object>) info, provider);

        try {
            result = new ProviderConnectionRedirectedException(message, redirect.validate().toURI());
        } catch (Exception ex) {
            result = new ProviderConnectionRemotelyClosedException(message + " : " + ex.getMessage());
        }
    }

    return result;
}
 
Example #9
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleEnd(End end, Binary payload, Integer channel)
{
    TransportSession transportSession = _remoteSessions.get(channel);
    if(transportSession == null)
    {
        // TODO - fail due to attach on non-begun session
    }
    else
    {
        _remoteSessions.remove(channel);
        transportSession.receivedEnd();
        transportSession.unsetRemoteChannel();
        SessionImpl session = transportSession.getSession();
        session.setRemoteState(EndpointState.CLOSED);
        ErrorCondition errorCondition = end.getError();
        if(errorCondition != null)
        {
            session.getRemoteCondition().copyFrom(errorCondition);
        }

        _connectionEndpoint.put(Event.Type.SESSION_REMOTE_CLOSE, session);
    }
}
 
Example #10
Source File: ProtonServerSenderContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void close(ErrorCondition condition) throws ActiveMQAMQPException {
   closed = true;
   if (condition != null) {
      sender.setCondition(condition);
   }
   protonSession.removeSender(sender);

   connection.runLater(() -> {
      sender.close();
      try {
         sessionSPI.closeSender(brokerConsumer);
      } catch (Exception e) {
         log.warn(e.getMessage(), e);
      }
      sender.close();
      connection.flush();
   });
}
 
Example #11
Source File: NettySimpleAmqpServer.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
protected void processConnectionOpen(Connection connection) throws Exception {
    ErrorCondition failure = null;

    protonConnection.setContext(this);
    protonConnection.setOfferedCapabilities(getConnectionCapabilitiesOffered());
    protonConnection.setProperties(getConnetionProperties());
    protonConnection.setContainer("Netty-Server");
    protonConnection.open();

    if (connectionIntercepter != null) {
        failure = connectionIntercepter.apply(connection);
    }

    if (failure == null) {
        failure = handleConnectionRegistration(connection);
    }

    if (failure != null) {
        protonConnection.setProperties(getFailedConnetionProperties());
        protonConnection.setCondition(failure);
        protonConnection.close();
    }
}
 
Example #12
Source File: DetachType.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
public Detach newInstance(Object described)
{
    List l = (List) described;

    Detach o = new Detach();

    if(l.isEmpty())
    {
        throw new DecodeException("The handle field cannot be omitted");
    }

    switch(3 - l.size())
    {

        case 0:
            o.setError( (ErrorCondition) l.get( 2 ) );
        case 1:
            Boolean closed = (Boolean) l.get(1);
            o.setClosed(closed == null ? false : closed);
        case 2:
            o.setHandle( (UnsignedInteger) l.get( 0 ) );
    }


    return o;
}
 
Example #13
Source File: AmqpSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to read and return the embedded error message in the given ErrorCondition
 * object.  If no message can be extracted a generic message is returned.
 *
 * @param errorCondition The ErrorCondition to extract the error message from.
 * @return an error message extracted from the given ErrorCondition.
 */
public static String extractErrorMessage(ErrorCondition errorCondition) {
   String message = "Received error from remote peer without description";
   if (errorCondition != null) {
      if (errorCondition.getDescription() != null && !errorCondition.getDescription().isEmpty()) {
         message = errorCondition.getDescription();
      }

      Symbol condition = errorCondition.getCondition();
      if (condition != null) {
         message = message + " [condition = " + condition + "]";
      }
   }

   return message;
}
 
Example #14
Source File: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the attempt to create a sender fails with a
 * {@code ServiceInvocationException} if the remote peer refuses
 * to open the link with an error condition.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateSenderFailsForErrorCondition(final VertxTestContext ctx) {

    testCreateSenderFails(
            ctx,
            () -> new ErrorCondition(AmqpError.RESOURCE_LIMIT_EXCEEDED, "unauthorized"),
            cause -> {
                return cause instanceof ServiceInvocationException;
            });
}
 
Example #15
Source File: AmqpSinkBridgeEndpoint.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
private void commitHandler(AsyncResult<Void> seekResult) {

        if (seekResult.failed()) {
            ErrorCondition condition =
                    new ErrorCondition(Symbol.getSymbol(AmqpBridge.AMQP_ERROR_KAFKA_COMMIT),
                            "Error in commit");
            sendAmqpError(condition);
        }
    }
 
Example #16
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Closes a link with an error condition.
 *
 * @param link The link to close.
 * @param t The throwable to create the error condition from.
 * @param span The span to log the error condition to (may be {@code null}).
 */
private <T extends ProtonLink<T>> void closeLinkWithError(
        final ProtonLink<T> link,
        final Throwable t,
        final Span span) {

    final ErrorCondition ec = getErrorCondition(t);
    log.debug("closing link with error condition [symbol: {}, description: {}]", ec.getCondition(), ec.getDescription());
    link.setCondition(ec);
    link.close();
    if (span != null) {
        TracingHelper.logError(span, t);
    }
}
 
Example #17
Source File: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void testCreateSenderFails(
        final VertxTestContext ctx,
        final Supplier<ErrorCondition> errorSupplier,
        final Predicate<Throwable> failureAssertion) {

    final ProtonSender sender = mock(ProtonSender.class);
    when(sender.getRemoteCondition()).thenReturn(errorSupplier.get());
    when(con.createSender(anyString())).thenReturn(sender);
    final Handler<String> remoteCloseHook = VertxMockSupport.mockHandler();
    when(vertx.setTimer(anyLong(), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        // do not run timers immediately
        return 0L;
    });

    // GIVEN an established connection
    honoConnection.connect()
        .compose(c -> {
            final Future<ProtonSender> s = honoConnection.createSender(
                    "target", ProtonQoS.AT_LEAST_ONCE, remoteCloseHook);
            ctx.verify(() -> {
                verify(vertx).setTimer(eq(props.getLinkEstablishmentTimeout()), VertxMockSupport.anyHandler());
                final ArgumentCaptor<Handler<AsyncResult<ProtonSender>>> openHandler = VertxMockSupport.argumentCaptorHandler();
                verify(sender).openHandler(openHandler.capture());
                openHandler.getValue().handle(Future.failedFuture(new IllegalStateException()));
            });
            return s;
        })
        .onComplete(ctx.failing(t -> {
            ctx.verify(() -> {
                assertThat(failureAssertion.test(t)).isTrue();
                verify(remoteCloseHook, never()).handle(anyString());
            });
            ctx.completeNow();
        }));
}
 
Example #18
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Processes an AMQP message received from a device.
 * <p>
 * This method settles the transfer with the following outcomes:
 * <ul>
 * <li><em>accepted</em> if the message has been successfully processed.</li>
 * <li><em>rejected</em> if the message could not be processed due to a problem caused by the device.</li>
 * <li><em>released</em> if the message could not be forwarded to a downstream consumer.</li>
 * </ul>
 *
 * @param ctx The context for the message.
 * @return A future indicating the outcome of processing the message.
 *         The future will succeed if the message has been processed successfully, otherwise it
 *         will fail with a {@link ServiceInvocationException}.
 */
protected Future<ProtonDelivery> onMessageReceived(final AmqpContext ctx) {

    final SpanContext spanContext = TracingHelper.extractSpanContext(tracer, ctx.getMessage());
    final Span msgSpan = newSpan("upload message", ctx.getAuthenticatedDevice(), ctx.getTraceSamplingPriority(),
            spanContext);
    msgSpan.log(Collections.singletonMap(Tags.MESSAGE_BUS_DESTINATION.getKey(), ctx.getAddress()));

    return validateEndpoint(ctx)
    .compose(validatedEndpoint -> validateAddress(validatedEndpoint.getAddress(), validatedEndpoint.getAuthenticatedDevice()))
    .compose(validatedAddress -> uploadMessage(ctx, validatedAddress, msgSpan))
    .map(d -> {
        ProtonHelper.accepted(ctx.delivery(), true);
        msgSpan.finish();
        return d;
    }).recover(t -> {
        if (t instanceof ClientErrorException) {
            final ErrorCondition condition = getErrorCondition(t);
            MessageHelper.rejected(ctx.delivery(), condition);
        } else {
            ProtonHelper.released(ctx.delivery(), true);
        }
        TracingHelper.logError(msgSpan, t);
        msgSpan.finish();
        return Future.failedFuture(t);
    });
}
 
Example #19
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public ErrorCondition getCondition()
{
    // Get the ErrorCondition, but only return it if its condition field is populated.
    // This somewhat retains prior TransportImpl behaviour of returning null when no
    // condition had been set (by TransportImpl itself) rather than the 'empty' ErrorCondition
    // object historically used in the other areas.
    ErrorCondition errorCondition = super.getCondition();
    return isConditionPopulated(errorCondition) ? errorCondition : null;
}
 
Example #20
Source File: Send.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onTransportError(Event event) {
    ErrorCondition condition = event.getTransport().getCondition();
    if (condition != null) {
        System.err.println("Error: " + condition.getDescription());
    } else {
        System.err.println("Error (no description returned).");
    }
}
 
Example #21
Source File: ProtonHandler.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void internalHandlerError(Exception e) {
   log.warn(e.getMessage(), e);
   ErrorCondition error = new ErrorCondition();
   error.setCondition(AmqpError.INTERNAL_ERROR);
   error.setDescription("Unrecoverable error: " + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()));
   connection.setCondition(error);
   connection.close();
   flush();
}
 
Example #22
Source File: AmqpSupport.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Given an ErrorCondition instance create a new Exception that best matches
 * the error type that indicates the connection creation failed for some reason.
 *
 * @param provider
 * 		the AMQP provider instance that originates this exception
 * @param endpoint
 *      The target of the error.
 * @param errorCondition
 *      The ErrorCondition returned from the remote peer.
 *
 * @return a new Exception instance that best matches the ErrorCondition value.
 */
public static ProviderConnectionRemotelyClosedException convertToConnectionClosedException(AmqpProvider provider, Endpoint endpoint, ErrorCondition errorCondition) {
    ProviderConnectionRemotelyClosedException remoteError = null;

    if (errorCondition != null && errorCondition.getCondition() != null) {
        Symbol error = errorCondition.getCondition();
        String message = extractErrorMessage(errorCondition);

        if (error.equals(AmqpError.UNAUTHORIZED_ACCESS)) {
            remoteError = new ProviderConnectionSecurityException(message);
        } else if (error.equals(AmqpError.RESOURCE_LIMIT_EXCEEDED)) {
            remoteError = new ProviderConnectionResourceAllocationException(message);
        } else if (error.equals(ConnectionError.CONNECTION_FORCED)) {
            remoteError = new ProviderConnectionRemotelyClosedException(message);
        } else if (error.equals(AmqpError.NOT_FOUND)) {
            remoteError = new ProviderConnectionResourceNotFoundException(message);
        } else if (error.equals(ConnectionError.REDIRECT)) {
            remoteError = createRedirectException(provider, error, message, errorCondition);
        } else if (error.equals(AmqpError.INVALID_FIELD)) {
            Map<?, ?> info = errorCondition.getInfo();
            if (info != null && CONTAINER_ID.equals(info.get(INVALID_FIELD))) {
                remoteError = new ProviderInvalidClientIDException(message);
            } else {
                remoteError = new ProviderConnectionRemotelyClosedException(message);
            }
        } else {
            remoteError = new ProviderConnectionRemotelyClosedException(message);
        }
    } else if (remoteError == null) {
        remoteError = new ProviderConnectionRemotelyClosedException("Unknown error from remote peer");
    }

    return remoteError;
}
 
Example #23
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void processEnd()
{
    if(_connectionEndpoint != null && _isOpenSent)
    {
        EndpointImpl endpoint = _connectionEndpoint.getTransportHead();
        while(endpoint != null)
        {
            SessionImpl session;
            TransportSession transportSession;

            if((endpoint instanceof SessionImpl)) {
                if ((session = (SessionImpl)endpoint).getLocalState() == EndpointState.CLOSED
                    && (transportSession = session.getTransportSession()).isLocalChannelSet()
                    && !_isCloseSent)
                {
                    if (hasSendableMessages(session)) {
                        endpoint = endpoint.transportNext();
                        continue;
                    }

                    int channel = freeLocalChannel(transportSession);
                    End end = new End();
                    ErrorCondition localError = endpoint.getCondition();
                    if( localError.getCondition() !=null )
                    {
                        end.setError(localError);
                    }

                    writeFrame(channel, end, null, null);
                }

                endpoint.clearModified();
            }

            endpoint = endpoint.transportNext();
        }
    }
}
 
Example #24
Source File: EndpointImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void setCondition(ErrorCondition condition)
{
    if(condition != null)
    {
        _localError.copyFrom(condition);
    }
    else
    {
        _localError.clear();
    }
}
 
Example #25
Source File: CloseType.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public Close newInstance(Object described)
{
    List l = (List) described;

    Close o = new Close();

    if(!l.isEmpty())
    {
        o.setError( (ErrorCondition) l.get( 0 ) );
    }

    return o;
}
 
Example #26
Source File: EndType.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public End newInstance(Object described)
{
    List l = (List) described;

    End o = new End();

    if(!l.isEmpty())
    {
        o.setError( (ErrorCondition) l.get( 0 ) );
    }


    return o;
}
 
Example #27
Source File: IOHandler.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Selectable selectable) {
    Reactor reactor = selectable.getReactor();
    Transport transport = ((SelectableImpl)selectable).getTransport();
    int pending = transport.pending();
    if (pending > 0) {
        SocketChannel channel = (SocketChannel)selectable.getChannel();
        try {
            int n = channel.write(transport.head());
            if (n < 0) {
                transport.close_head();
            } else {
                transport.pop(n);
            }
        } catch(IOException ioException) {
            ErrorCondition condition = new ErrorCondition();
            condition.setCondition(Symbol.getSymbol("proton:io"));
            condition.setDescription(ioException.getMessage());
            transport.setCondition(condition);
            transport.close_head();
        }
    }

    int newPending = transport.pending();
    if (newPending != pending) {
        update(selectable);
        reactor.update(selectable);
    }
}
 
Example #28
Source File: ProtonHelper.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
static <T> AsyncResult<T> future(T value, ErrorCondition err) {
  if (err.getCondition() != null) {
    return Future.failedFuture(err.toString());
  } else {
    return Future.succeededFuture(value);
  }
}
 
Example #29
Source File: SslTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void assertConditions(Transport transport)
{
    ErrorCondition remoteCondition = transport.getRemoteCondition();
    if (remoteCondition != null)
    {
        assertNull(remoteCondition.getCondition());
    }

    ErrorCondition condition = transport.getCondition();
    if (condition != null)
    {
        assertNull(condition.getCondition());
    }
}
 
Example #30
Source File: AmqpSecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testConsumerNotAuthorizedToCreateQueues() throws Exception {
   AmqpClient client = createAmqpClient(noprivUser, noprivPass);
   client.setValidator(new AmqpValidator() {

      @Override
      public void inspectOpenedResource(Sender sender) {
         ErrorCondition condition = sender.getRemoteCondition();

         if (condition != null && condition.getCondition() != null) {
            if (!condition.getCondition().equals(AmqpError.UNAUTHORIZED_ACCESS)) {
               markAsInvalid("Should have been tagged with unauthorized access error");
            }
         } else {
            markAsInvalid("Sender should have been opened with an error");
         }
      }
   });

   AmqpConnection connection = client.connect();

   try {
      AmqpSession session = connection.createSession();

      try {
         session.createReceiver(getQueueName(getPrecreatedQueueSize() + 1));
         fail("Should not be able to consume here.");
      } catch (Exception ex) {
         instanceLog.debug("Caught expected exception");
      }

      connection.getStateInspector().assertValid();
   } finally {
      connection.close();
   }
}