Beispiel #1
0
  public void sendRequest(MetaInfo meta) {
    System.out.println(Thread.currentThread().getId() + " start sendRequest");
    URI uri = null;
    try {
      System.out.println(meta.getParams());
      uri = new URI(meta.getUrl());
    } catch (URISyntaxException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
    String host = uri.getHost();
    int port = 80;

    HttpRequest request =
        new DefaultHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.valueOf(meta.getMethod()), uri.toASCIIString());
    meta.buildHttpRequestHeader(request);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    Channel channel = future.getChannel();
    channel.getPipeline().addLast("handler", new DownloaderHandler());
    GlobalVar.metaInfoVar.set(channel, meta);

    future.addListener(new ConnectOk(request));
    channel.getCloseFuture().awaitUninterruptibly().addListener(new ConnectClose());
    System.out.println(Thread.currentThread().getId() + " end sendRequest");
  }
 /**
  * Builds a new AgentMBeanServerConnectionFactory and returns the underlying
  * MBeanServerConnection
  *
  * @return a new MBeanServerConnection
  */
 public MBeanServerConnection build() {
   final String key = buildKey();
   MBeanServerConnection conn = INSTANCES.get(key);
   if (conn == null) {
     synchronized (INSTANCES) {
       conn = INSTANCES.get(key);
       if (conn == null) {
         conn =
             (MBeanServerConnection)
                 Proxy.newProxyInstance(
                     Thread.currentThread().getContextClassLoader(),
                     new Class[] {MBeanServerConnection.class},
                     new AgentMBeanServerConnectionFactory(this));
         INSTANCES.put(key, conn);
         channel
             .getCloseFuture()
             .addListener(
                 new ChannelFutureListener() {
                   @Override
                   public void operationComplete(ChannelFuture future) throws Exception {
                     INSTANCES.remove(key);
                   }
                 });
       }
     }
   }
   return conn;
 }
Beispiel #3
0
 @Override
 public synchronized NettyWebServer join() throws InterruptedException {
   if (channel != null) {
     channel.getCloseFuture().await();
   }
   return this;
 }
Beispiel #4
0
  /** Connects to the IMAP server logs in with the given credentials. */
  @Override
  public synchronized boolean connect(final DisconnectListener listener) {
    reset();

    ChannelFuture future =
        bootstrap.connect(new InetSocketAddress(config.getHost(), config.getPort()));

    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
      throw new RuntimeException("Could not connect channel", future.getCause());
    }

    this.channel = channel;
    this.disconnectListener = listener;
    if (null != listener) {
      // https://issues.jboss.org/browse/NETTY-47?page=com.atlassian.jirafisheyeplugin%3Afisheye-issuepanel#issue-tabs
      channel
          .getCloseFuture()
          .addListener(
              new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                  mailClientHandler.idleAcknowledged.set(false);
                  mailClientHandler.disconnected();
                  listener.disconnected();
                }
              });
    }
    return login();
  }
Beispiel #5
0
  public File get() throws IOException {
    ClientBootstrap bootstrap =
        new ClientBootstrap(
            new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
    bootstrap.setOption("connectTimeoutMillis", 5000L); // set 5 sec
    bootstrap.setOption("receiveBufferSize", 1048576); // set 1M
    ChannelPipelineFactory factory = new HttpClientPipelineFactory(file);
    bootstrap.setPipelineFactory(factory);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
      bootstrap.releaseExternalResources();
      throw new IOException(future.getCause());
    }

    String query = uri.getPath() + (uri.getQuery() != null ? "?" + uri.getQuery() : "");
    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, query);
    request.setHeader(HttpHeaders.Names.HOST, host);
    LOG.info("Fetch: " + request.getUri());
    request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    // Send the HTTP request.
    channel.write(request);

    // Wait for the server to close the connection.
    channel.getCloseFuture().awaitUninterruptibly();

    // Shut down executor threads to exit.
    bootstrap.releaseExternalResources();

    return file;
  }
  @Theory
  public void shouldAcceptEchoThenClose(final ContentStrategy strategy) throws Exception {
    ChannelHandler echoHandler =
        new SimpleChannelHandler() {
          @Override
          public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
            Channel channel = ctx.getChannel();
            ChannelBuffer message = (ChannelBuffer) e.getMessage();

            HttpChannelConfig config = (HttpChannelConfig) channel.getConfig();
            HttpHeaders writeHeaders = config.getWriteHeaders();
            switch (strategy) {
              case BUFFERED:
                config.setMaximumBufferedContentLength(8192);
                break;
              case CLOSE:
                writeHeaders.set(Names.CONNECTION, Values.CLOSE);
                break;
              case CHUNKED:
                writeHeaders.set(Names.TRANSFER_ENCODING, Values.CHUNKED);
                break;
              case EXPLICIT:
                writeHeaders.set(Names.CONTENT_LENGTH, 12);
                break;
            }

            write(ctx, future(channel), message);
            close(ctx, future(channel));
          }
        };

    final ChannelGroup childChannels = new DefaultChannelGroup();
    SimpleChannelHandler parent =
        new SimpleChannelHandler() {

          @Override
          public void childChannelOpen(ChannelHandlerContext ctx, ChildChannelStateEvent e)
              throws Exception {
            childChannels.add(e.getChildChannel());
            super.childChannelOpen(ctx, e);
          }
        };
    SimpleChannelHandler parentSpy = spy(parent);

    SimpleChannelHandler child = new SimpleChannelHandler();
    SimpleChannelHandler childSpy = spy(child);

    server.setParentHandler(parentSpy);
    server.setPipeline(pipeline(childSpy, echoHandler));

    ChannelAddressFactory channelAddressFactory = newChannelAddressFactory();
    ChannelAddress channelAddress =
        channelAddressFactory.newChannelAddress(URI.create("http://localhost:8000/path"));
    Channel binding = server.bind(channelAddress).syncUninterruptibly().getChannel();

    URL location = createURL("http://localhost:8000/path");
    URLConnection connection = location.openConnection();
    connection.setDoOutput(true);
    OutputStream output = connection.getOutputStream();
    output.write("Hello, world".getBytes(UTF_8));
    output.close();

    DataInputStream input = new DataInputStream(connection.getInputStream());
    byte[] buf = new byte[12];
    input.readFully(buf);
    input.close();

    // wait for child channels to close
    for (Channel childChannel : childChannels) {
      ChannelFuture childCloseFuture = childChannel.getCloseFuture();
      childCloseFuture.syncUninterruptibly();
    }

    // wait for server channel to close
    binding.close().syncUninterruptibly();

    server.shutdown();

    assertEquals("Hello, world", new String(buf, UTF_8));

    verify(parentSpy, times(6))
        .handleUpstream(any(ChannelHandlerContext.class), any(ChannelEvent.class));
    verify(parentSpy, times(2))
        .handleDownstream(any(ChannelHandlerContext.class), any(ChannelEvent.class));

    InOrder parentBind = inOrder(parentSpy);
    parentBind
        .verify(parentSpy)
        .channelOpen(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    parentBind
        .verify(parentSpy)
        .bindRequested(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    parentBind
        .verify(parentSpy)
        .channelBound(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));

    InOrder parentChild = inOrder(parentSpy);
    parentChild
        .verify(parentSpy)
        .childChannelOpen(any(ChannelHandlerContext.class), any(ChildChannelStateEvent.class));
    parentChild
        .verify(parentSpy)
        .childChannelClosed(any(ChannelHandlerContext.class), any(ChildChannelStateEvent.class));

    InOrder parentClose = inOrder(parentSpy);
    parentClose
        .verify(parentSpy)
        .closeRequested(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    parentClose
        .verify(parentSpy)
        .channelUnbound(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    parentClose
        .verify(parentSpy)
        .channelClosed(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));

    verify(childSpy, times(9))
        .handleUpstream(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    verify(childSpy, times(2))
        .handleDownstream(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));

    InOrder childConnect = inOrder(childSpy);
    childConnect
        .verify(childSpy)
        .channelOpen(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    childConnect
        .verify(childSpy)
        .channelBound(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    childConnect
        .verify(childSpy)
        .channelConnected(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));

    InOrder childRead = inOrder(childSpy);
    childRead
        .verify(childSpy)
        .messageReceived(any(ChannelHandlerContext.class), any(MessageEvent.class));
    childRead
        .verify(childSpy)
        .inputShutdown(any(ChannelHandlerContext.class), any(ShutdownInputEvent.class));

    InOrder childWrite = inOrder(childSpy);
    childWrite
        .verify(childSpy)
        .writeRequested(any(ChannelHandlerContext.class), any(MessageEvent.class));
    childWrite
        .verify(childSpy)
        .writeComplete(any(ChannelHandlerContext.class), any(WriteCompletionEvent.class));

    InOrder childClose = inOrder(childSpy);
    childClose
        .verify(childSpy)
        .closeRequested(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    childClose
        .verify(childSpy)
        .channelDisconnected(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    childClose
        .verify(childSpy)
        .channelUnbound(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));
    childClose
        .verify(childSpy)
        .channelClosed(any(ChannelHandlerContext.class), any(ChannelStateEvent.class));

    verifyNoMoreInteractions(parentSpy, childSpy);
  }