io.vertx.core.net.impl.ConnectionBase Java Examples

The following examples show how to use io.vertx.core.net.impl.ConnectionBase. 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: RestClientInvocation.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void handleResponse(HttpClientResponse httpClientResponse) {
  this.clientResponse = httpClientResponse;

  if (HttpStatus.isSuccess(clientResponse.statusCode()) && restOperationMeta.isDownloadFile()) {
    ReadStreamPart part = new ReadStreamPart(httpClientWithContext.context(), httpClientResponse);
    invocation.getHandlerContext().put(RestConst.READ_STREAM_PART, part);
    processResponseBody(null);
    return;
  }

  httpClientResponse.exceptionHandler(e -> {
    invocation.getTraceIdLogger().error(LOGGER, "Failed to receive response, local:{}, remote:{}.",
        getLocalAddress(), httpClientResponse.netSocket().remoteAddress(), e);
    fail((ConnectionBase) clientRequest.connection(), e);
  });

  clientResponse.bodyHandler(this::processResponseBody);
}
 
Example #2
Source File: ReactiveWriteStreamImpl.java    From vertx-reactive-streams with Apache License 2.0 6 votes vote down vote up
@Override
public ReactiveWriteStream<T> close() {
  synchronized (this) {
    if (closed) {
      return this;
    }
    closed = true;
    complete();
    subscriptions.clear();
    Future<Void> closedFut = Future.failedFuture(ConnectionBase.CLOSED_EXCEPTION);
    for (Item<T> item: pending) {
      Handler<AsyncResult<Void>> handler = item.handler;
      if (handler != null) {
        ctx.runOnContext(v -> {
          handler.handle(closedFut);
        });
      }
    }
    pending.clear();
  }
  return this;
}
 
Example #3
Source File: RestClientInvocation.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * after this method, connection will be recycled to connection pool
 * @param responseBuf response body buffer, when download, responseBuf is null, because download data by ReadStreamPart
 */
protected void processResponseBody(Buffer responseBuf) {
  DefaultHttpSocketMetric httpSocketMetric = (DefaultHttpSocketMetric) ((ConnectionBase) clientRequest.connection())
      .metric();
  invocation.getInvocationStageTrace().finishGetConnection(httpSocketMetric.getRequestBeginTime());
  invocation.getInvocationStageTrace().finishWriteToBuffer(httpSocketMetric.getRequestEndTime());
  invocation.getInvocationStageTrace().finishReceiveResponse();

  invocation.getResponseExecutor().execute(() -> {
    try {
      invocation.getInvocationStageTrace().startClientFiltersResponse();
      HttpServletResponseEx responseEx =
          new VertxClientResponseToHttpServletResponse(clientResponse, responseBuf);
      for (HttpClientFilter filter : httpClientFilters) {
        if (filter.enabled()) {
          Response response = filter.afterReceiveResponse(invocation, responseEx);
          if (response != null) {
            complete(response);
            return;
          }
        }
      }
    } catch (Throwable e) {
      // already collection time from httpSocketMetric
      // and connection maybe already belongs to other invocation in this time
      // so set connection to null
      fail(null, e);
    }
  });
}
 
Example #4
Source File: RestClientInvocation.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected void fail(ConnectionBase connection, Throwable e) {
  if (invocation.isFinished()) {
    return;
  }

  InvocationStageTrace stageTrace = invocation.getInvocationStageTrace();
  // connection maybe null when exception happens such as ssl handshake failure
  if (connection != null) {
    DefaultHttpSocketMetric httpSocketMetric = (DefaultHttpSocketMetric) connection.metric();
    stageTrace.finishGetConnection(httpSocketMetric.getRequestBeginTime());
    stageTrace.finishWriteToBuffer(httpSocketMetric.getRequestEndTime());
  }

  // even failed and did not received response, still set time for it
  // that will help to know the real timeout time
  if (stageTrace.getFinishReceiveResponse() == 0) {
    stageTrace.finishReceiveResponse();
  }
  if (stageTrace.getStartClientFiltersResponse() == 0) {
    stageTrace.startClientFiltersResponse();
  }

  stageTrace.finishClientFiltersResponse();

  try {
    if (e instanceof TimeoutException) {
      // give an accurate cause for timeout exception
      asyncResp.consumerFail(new InvocationException(Status.REQUEST_TIMEOUT,
          String.format("Request Timeout. Details: %s", e.getMessage())));
      return;
    }
    asyncResp.fail(invocation.getInvocationType(), e);
  } catch (Throwable e1) {
    invocation.getTraceIdLogger().error(LOGGER, "failed to invoke asyncResp.fail.", e1);
  }
}
 
Example #5
Source File: WebSocketTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void sendFrame(String body, Handler<AsyncResult<Void>> handler) {
  if (log.isTraceEnabled()) log.trace("WS, sending frame");
  if (!closed) {
    ws.writeTextMessage(body, handler);
  } else {
    if (handler != null) {
      handler.handle(Future.failedFuture(ConnectionBase.CLOSED_EXCEPTION));
    }
  }
}
 
Example #6
Source File: RawWebSocketTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private synchronized boolean canWrite(Handler<AsyncResult<Void>> handler) {
  if (closed) {
    if (handler != null) {
      vertx.runOnContext(v -> {
        handler.handle(Future.failedFuture(ConnectionBase.CLOSED_EXCEPTION));
      });
    }
    return false;
  }
  return true;
}
 
Example #7
Source File: SockJSSession.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Buffer buffer, Handler<AsyncResult<Void>> handler) {
  synchronized (this) {
    if (closed) {
      if (handler != null) {
        context.runOnContext(v -> handler.handle(Future.failedFuture(ConnectionBase.CLOSED_EXCEPTION)));
      }
      return;
    }
    String msgStr = buffer.toString();
    pendingWrites.add(msgStr);
    messagesSize += msgStr.length();
    if (handler != null) {
      if (writeAcks == null) {
        writeAcks = new ArrayList<>();
      }
      writeAcks.add(handler);
    }
    if (listener != null) {
      Context ctx = transportCtx;
      if (Vertx.currentContext() != ctx) {
        ctx.runOnContext(v -> writePendingMessages());
      } else {
        writePendingMessages();
      }
    }
  }
  return;
}
 
Example #8
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public Handler<RoutingContext> createBodyHandler(HttpConfiguration httpConfiguration) {
    BodyHandler bodyHandler = BodyHandler.create();
    Optional<MemorySize> maxBodySize = httpConfiguration.limits.maxBodySize;
    if (maxBodySize.isPresent()) {
        bodyHandler.setBodyLimit(maxBodySize.get().asLongValue());
    }
    final BodyConfig bodyConfig = httpConfiguration.body;
    bodyHandler.setHandleFileUploads(bodyConfig.handleFileUploads);
    bodyHandler.setUploadsDirectory(bodyConfig.uploadsDirectory);
    bodyHandler.setDeleteUploadedFilesOnEnd(bodyConfig.deleteUploadedFilesOnEnd);
    bodyHandler.setMergeFormAttributes(bodyConfig.mergeFormAttributes);
    bodyHandler.setPreallocateBodyBuffer(bodyConfig.preallocateBodyBuffer);
    return new Handler<RoutingContext>() {
        @Override
        public void handle(RoutingContext event) {
            if (!Context.isOnEventLoopThread()) {
                ((ConnectionBase) event.request().connection()).channel().eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //this can happen if blocking authentication is involved for get requests
                            if (!event.request().isEnded()) {
                                event.request().resume();
                                if (CAN_HAVE_BODY.contains(event.request().method())) {
                                    bodyHandler.handle(event);
                                } else {
                                    event.next();
                                }
                            } else {
                                event.next();
                            }
                        } catch (Throwable t) {
                            event.fail(t);
                        }
                    }
                });
            } else {
                event.request().resume();
                if (CAN_HAVE_BODY.contains(event.request().method())) {
                    bodyHandler.handle(event);
                } else {
                    event.next();
                }
            }
        }
    };
}