private void performHttpCall(String host, int port, String path, String expected)
     throws IOException {
   URLConnection conn = null;
   InputStream in = null;
   StringWriter writer = new StringWriter();
   try {
     URL url =
         new URL(
             "http://"
                 + TestSuiteEnvironment.formatPossibleIpv6Address(host)
                 + ":"
                 + port
                 + "/"
                 + path);
     // System.out.println("Reading response from " + url + ":");
     conn = url.openConnection();
     conn.setDoInput(true);
     in = new BufferedInputStream(conn.getInputStream());
     int i = in.read();
     while (i != -1) {
       writer.write((char) i);
       i = in.read();
     }
     assertTrue((writer.toString().indexOf(expected) > -1));
     // System.out.println("OK");
   } finally {
     safeClose(in);
     safeClose(writer);
   }
 }
Пример #2
0
 private String copyConfigFile(File file, File dir) {
   File newFile = new File(dir, "testing-" + file.getName());
   if (newFile.exists()) {
     newFile.delete();
   }
   try {
     InputStream in = new BufferedInputStream(new FileInputStream(file));
     try {
       OutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
       try {
         int i = in.read();
         while (i != -1) {
           out.write(i);
           i = in.read();
         }
       } finally {
         IoUtils.safeClose(out);
       }
     } finally {
       IoUtils.safeClose(in);
     }
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   return newFile.getName();
 }
Пример #3
0
 void cleanup() {
   // All other cleanup handlers have been called.  We will inspect the state of the exchange
   // and attempt to fix any leftover or broken crap as best as we can.
   //
   // At this point if any channels were not acquired, we know that not even default handlers have
   // handled the request, meaning we basically have no idea what their state is; the response
   // headers
   // may not even be valid.
   //
   // The only thing we can do is to determine if the request and reply were both terminated; if
   // not,
   // consume the request body nicely, send whatever HTTP response we have, and close down the
   // connection.
   complete = true;
   int oldVal, newVal;
   do {
     oldVal = state;
     if (allAreSet(oldVal, FLAG_CLEANUP)) {
       return;
     }
     newVal = oldVal | FLAG_CLEANUP | FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED;
   } while (!stateUpdater.compareAndSet(this, oldVal, newVal));
   final StreamSourceChannel requestChannel = underlyingRequestChannel;
   final StreamSinkChannel responseChannel = underlyingResponseChannel;
   if (allAreSet(oldVal, FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED)) {
     // we're good; a transfer coding handler took care of things.
     return;
   } else {
     try {
       // we do not attempt to drain the read side, as one of the reasons this could
       // be happening is because the request was too large
       requestChannel.shutdownReads();
       responseChannel.shutdownWrites();
       if (!responseChannel.flush()) {
         responseChannel
             .getWriteSetter()
             .set(
                 ChannelListeners.<StreamSinkChannel>flushingChannelListener(
                     new ChannelListener<StreamSinkChannel>() {
                       public void handleEvent(final StreamSinkChannel channel) {
                         // this shouldn't be necessary...
                         channel.suspendWrites();
                         channel.getWriteSetter().set(null);
                       }
                     },
                     ChannelListeners.closingChannelExceptionHandler()));
         responseChannel.resumeWrites();
       }
     } catch (Throwable t) {
       // All sorts of things could go wrong, from runtime exceptions to java.io.IOException to
       // errors.
       // Just kill off the connection, it's f****d beyond repair.
       safeClose(requestChannel);
       safeClose(responseChannel);
       safeClose(connection);
     }
   }
 }
 @After
 public void afterTest() {
   IoUtils.safeClose(clientChannel);
   IoUtils.safeClose(serverChannel);
   IoUtils.safeClose(connection);
   serviceRegistration.close();
   System.gc();
   System.runFinalization();
   Logger.getLogger("TEST").infof("Finished test %s", name.getMethodName());
 }
 private void close() {
   if (this.pooledBuffer != null) {
     safeClose(this.pooledBuffer);
     this.pooledBuffer = null;
   }
   if (this.channel != null) {
     safeClose(this.channel);
     this.channel = null;
   }
 }
Пример #6
0
    @Override
    public void handleEvent(SpdyChannel channel) {
      try {
        SpdyStreamSourceChannel result = channel.receive();
        if (result instanceof SpdySynReplyStreamSourceChannel) {
          final int streamId = ((SpdySynReplyStreamSourceChannel) result).getStreamId();
          SpdyClientExchange request = currentExchanges.get(streamId);
          result.addCloseTask(
              new ChannelListener<SpdyStreamSourceChannel>() {
                @Override
                public void handleEvent(SpdyStreamSourceChannel channel) {
                  currentExchanges.remove(streamId);
                }
              });
          if (request == null) {

            // server side initiated stream, we can't deal with that at the moment
            // just fail
            // TODO: either handle this properly or at the very least send RST_STREAM
            channel.sendGoAway(SpdyChannel.CLOSE_PROTOCOL_ERROR);
            IoUtils.safeClose(SpdyClientConnection.this);
            return;
          }
          request.responseReady((SpdySynReplyStreamSourceChannel) result);

        } else if (result instanceof SpdyPingStreamSourceChannel) {
          handlePing((SpdyPingStreamSourceChannel) result);
        } else if (result instanceof SpdyRstStreamStreamSourceChannel) {
          int stream = ((SpdyRstStreamStreamSourceChannel) result).getStreamId();
          UndertowLogger.REQUEST_LOGGER.debugf("Client received RST_STREAM for stream %s", stream);
          SpdyClientExchange exchange = currentExchanges.get(stream);
          if (exchange != null) {
            exchange.failed(UndertowMessages.MESSAGES.spdyStreamWasReset());
          }
        } else if (!channel.isOpen()) {
          throw UndertowMessages.MESSAGES.channelIsClosed();
        }

      } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
        IoUtils.safeClose(SpdyClientConnection.this);
        for (Map.Entry<Integer, SpdyClientExchange> entry : currentExchanges.entrySet()) {
          try {
            entry.getValue().failed(e);
          } catch (Exception ex) {
            UndertowLogger.REQUEST_IO_LOGGER.ioException(new IOException(ex));
          }
        }
      }
    }
    @Override
    public void handleEvent(StreamSinkChannel channel) {
      try {
        int c;
        do {
          ByteBuffer buffer = this.buffers.peek().getBuffer();
          do {
            c = channel.write(buffer);
          } while (buffer.hasRemaining() && c > 0);

          if (!buffer.hasRemaining()) {
            safeClose(this.buffers.remove());
          }
        } while (!this.buffers.isEmpty() && c > 0);

        if (!this.buffers.isEmpty()) {
          channel.resumeWrites();
        } else {
          this.writing.decrementAndGet();

          if (this.closing.get()) {
            closeIfDone();
          } else {
            this.subscription.request(1);
          }
        }
      } catch (IOException ex) {
        onError(ex);
      }
    }
 private void handleError(final StreamSinkChannel channel, final IOException e) {
   try {
     listener.onError(e);
   } finally {
     IoUtils.safeClose(channel);
   }
 }
Пример #9
0
 @Override
 public void handleEvent(final StreamSinkChannel channel) {
   HeaderMap trailers = source.getAttachment(HttpAttachments.REQUEST_TRAILERS);
   if (trailers != null) {
     target.putAttachment(HttpAttachments.RESPONSE_TRAILERS, trailers);
   }
   try {
     channel.shutdownWrites();
     if (!channel.flush()) {
       channel
           .getWriteSetter()
           .set(
               ChannelListeners.flushingChannelListener(
                   new ChannelListener<StreamSinkChannel>() {
                     @Override
                     public void handleEvent(StreamSinkChannel channel) {
                       channel.suspendWrites();
                       channel.getWriteSetter().set(null);
                     }
                   },
                   ChannelListeners.closingChannelExceptionHandler()));
       channel.resumeWrites();
     } else {
       channel.getWriteSetter().set(null);
       channel.shutdownWrites();
     }
   } catch (IOException e) {
     UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
     IoUtils.safeClose(channel);
   }
 }
  @Override
  public void handleMessage(Channel channel, MessageInputStream messageInputStream) {
    try {
      this.processMessage(channel, messageInputStream);
      // enroll for next message (whenever it's available)
      channel.receiveMessage(this);

    } catch (Throwable e) {
      // log it
      EjbLogger.ROOT_LOGGER.exceptionOnChannel(e, channel, messageInputStream);
      // no more messages can be sent or received on this channel
      IoUtils.safeClose(channel);
    } finally {
      IoUtils.safeClose(messageInputStream);
    }
  }
Пример #11
0
 private void handleError(StreamSinkChannel c, String m, Throwable t) {
   if (t instanceof IOException) UndertowLogger.REQUEST_IO_LOGGER.ioException((IOException) t);
   else UndertowLogger.REQUEST_IO_LOGGER.error(m, t);
   cleanup();
   c.getWriteSetter().set(null);
   IoUtils.safeClose(c);
 }
 protected List<ModelNode> readFile(File file, int expectedRecords) throws IOException {
   List<ModelNode> list = new ArrayList<ModelNode>();
   final BufferedReader reader = new BufferedReader(new FileReader(file));
   try {
     StringWriter writer = null;
     String line = reader.readLine();
     while (line != null) {
       if (DATE_STAMP_PATTERN.matcher(line).find()) {
         if (writer != null) {
           list.add(ModelNode.fromJSONString(writer.getBuffer().toString()));
         }
         writer = new StringWriter();
         writer.append("{");
       } else {
         if (writer != null) writer.append("\n" + line);
       }
       line = reader.readLine();
     }
     if (writer != null) {
       list.add(ModelNode.fromJSONString(writer.getBuffer().toString()));
     }
   } finally {
     IoUtils.safeClose(reader);
   }
   Assert.assertEquals(list.toString(), expectedRecords, list.size());
   return list;
 }
 @Override
 public void run() {
   handle = null;
   if (expireTime == -1) {
     return;
   }
   long current = System.currentTimeMillis();
   if (current < expireTime) {
     // timeout has been bumped, re-schedule
     handle =
         WorkerUtils.executeAfter(
             connection.getIoThread(),
             timeoutCommand,
             (expireTime - current) + FUZZ_FACTOR,
             TimeUnit.MILLISECONDS);
     return;
   }
   UndertowLogger.REQUEST_LOGGER.tracef(
       "Timing out channel %s due to inactivity", connection.getSourceChannel());
   IoUtils.safeClose(connection);
   if (connection.getSourceChannel().isReadResumed()) {
     ChannelListeners.invokeChannelListener(
         connection.getSourceChannel(), connection.getSourceChannel().getReadListener());
   }
   if (connection.getSinkChannel().isWriteResumed()) {
     ChannelListeners.invokeChannelListener(
         connection.getSinkChannel(), connection.getSinkChannel().getWriteListener());
   }
 }
Пример #14
0
  /** Notification that the current request is finished */
  public void requestDone() {

    connection.getSinkChannel().setConduit(originalSinkConduit);
    connection.getSourceChannel().setConduit(pushBackStreamSourceConduit);
    connection.getSinkChannel().suspendWrites();
    connection.getSinkChannel().setWriteListener(null);

    if (anyAreSet(state, CLOSE_REQ)) {
      currentRequest = null;
      this.state |= CLOSED;
      IoUtils.safeClose(connection);
    } else if (anyAreSet(state, UPGRADE_REQUESTED)) {
      connection.getSourceChannel().suspendReads();
      currentRequest = null;
      return;
    }
    currentRequest = null;

    HttpClientExchange next = pendingQueue.poll();

    if (next == null) {
      // we resume reads, so if the target goes away we get notified
      connection.getSourceChannel().setReadListener(clientReadListener);
      connection.getSourceChannel().resumeReads();
    } else {
      initiateRequest(next);
    }
  }
 @Override
 public void run() {
   final SessionID sessionID;
   try {
     try {
       sessionID = statefulSessionComponent.createSession();
     } catch (Throwable t) {
       SessionOpenRequestHandler.this.writeException(
           channelAssociation,
           SessionOpenRequestHandler.this.marshallerFactory,
           invocationId,
           t,
           null);
       return;
     }
     // get the affinity of the component
     final Affinity hardAffinity = statefulSessionComponent.getCache().getStrictAffinity();
     SessionOpenRequestHandler.this.writeSessionId(
         channelAssociation, invocationId, sessionID, hardAffinity);
   } catch (IOException ioe) {
     EjbLogger.ROOT_LOGGER.exceptionGeneratingSessionId(
         ioe, invocationId, channelAssociation.getChannel());
     // close the channel
     IoUtils.safeClose(this.channelAssociation.getChannel());
     return;
   }
 }
Пример #16
0
 @Override
 void stopListening() {
   server.suspendAccepts();
   UndertowLogger.ROOT_LOGGER.listenerSuspend("AJP", getName());
   IoUtils.safeClose(server);
   UndertowLogger.ROOT_LOGGER.listenerStopped(
       "AJP", getName(), getBinding().getValue().getSocketAddress());
 }
Пример #17
0
 void cancel(final HttpServerExchange exchange) {
   final ProxyConnection connectionAttachment = exchange.getAttachment(CONNECTION);
   if (connectionAttachment != null) {
     ClientConnection clientConnection = connectionAttachment.getConnection();
     UndertowLogger.PROXY_REQUEST_LOGGER.timingOutRequest(
         clientConnection.getPeerAddress() + "" + exchange.getRequestURI());
     IoUtils.safeClose(clientConnection);
   } else {
     UndertowLogger.PROXY_REQUEST_LOGGER.timingOutRequest(exchange.getRequestURI());
   }
   if (exchange.isResponseStarted()) {
     IoUtils.safeClose(exchange.getConnection());
   } else {
     exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
     exchange.endExchange();
   }
 }
Пример #18
0
 @Override
 public void couldNotResolveBackend(HttpServerExchange exchange) {
   if (exchange.isResponseStarted()) {
     IoUtils.safeClose(exchange.getConnection());
   } else {
     exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
     exchange.endExchange();
   }
 }
  @Override
  public void handleEvent(StreamConnection channel) {
    // set read and write timeouts
    try {
      Integer readTimeout = channel.getOption(Options.READ_TIMEOUT);
      Integer idleTimeout = undertowOptions.get(UndertowOptions.IDLE_TIMEOUT);
      if ((readTimeout == null || readTimeout <= 0) && idleTimeout != null) {
        readTimeout = idleTimeout;
      } else if (readTimeout != null && idleTimeout != null && idleTimeout > 0) {
        readTimeout = Math.min(readTimeout, idleTimeout);
      }
      if (readTimeout != null && readTimeout > 0) {
        channel
            .getSourceChannel()
            .setConduit(
                new ReadTimeoutStreamSourceConduit(
                    channel.getSourceChannel().getConduit(), channel, this));
      }
      Integer writeTimeout = channel.getOption(Options.WRITE_TIMEOUT);
      if ((writeTimeout == null || writeTimeout <= 0) && idleTimeout != null) {
        writeTimeout = idleTimeout;
      } else if (writeTimeout != null && idleTimeout != null && idleTimeout > 0) {
        writeTimeout = Math.min(writeTimeout, idleTimeout);
      }
      if (writeTimeout != null && writeTimeout > 0) {
        channel
            .getSinkChannel()
            .setConduit(
                new WriteTimeoutStreamSinkConduit(
                    channel.getSinkChannel().getConduit(), channel, this));
      }
    } catch (IOException e) {
      IoUtils.safeClose(channel);
      UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    }

    final PortForwardServerConnection connection =
        new PortForwardServerConnection(channel, bufferPool, undertowOptions, bufferSize);
    connection
        .getWorker()
        .execute(
            new Runnable() {
              @Override
              public void run() {
                try {
                  connection.startForwarding(
                      masterPortForwardConnection,
                      urlPath,
                      targetPort,
                      requestId.getAndIncrement());
                } catch (IOException e) {
                } finally {
                  IoUtils.safeClose(connection);
                }
              }
            });
  }
Пример #20
0
 void closeAsync() {
   IoUtils.safeClose(pipeOutputStream);
   synchronized (this) {
     channel.free(this);
     closed = true;
     // wake up waiters
     notifyAll();
   }
 }
Пример #21
0
 public synchronized void stop() {
   for (AcceptingChannel<? extends StreamConnection> channel : channels) {
     IoUtils.safeClose(channel);
   }
   channels = null;
   worker.shutdownNow();
   worker = null;
   xnio = null;
 }
Пример #22
0
 @Override
 public void handleException(Channel channel, IOException exception) {
   IoUtils.safeClose(channel);
   IoUtils.safeClose(clientConnection);
   if (exchange.isResponseStarted()) {
     UndertowLogger.REQUEST_IO_LOGGER.debug("Exception reading from target server", exception);
     if (!exchange.isResponseStarted()) {
       exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
       exchange.endExchange();
     } else {
       IoUtils.safeClose(exchange.getConnection());
     }
   } else {
     UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
     exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
     exchange.endExchange();
   }
 }
Пример #23
0
 @Override
 public void failed(IOException e) {
   UndertowLogger.PROXY_REQUEST_LOGGER.proxyRequestFailed(exchange.getRequestURI(), e);
   if (!exchange.isResponseStarted()) {
     exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
     exchange.endExchange();
   } else {
     IoUtils.safeClose(exchange.getConnection());
   }
 }
 public void onSuccess() {
   if (this.outputStream.size() > 0) {
     handleFrame();
   }
   if (logger.isTraceEnabled()) {
     logger.trace("XHR receive request completed.");
   }
   IoUtils.safeClose(this.connection);
   executeReceiveRequest(this.request, this.url, this.headers, this.session, this.connectFuture);
 }
 public void onFailure(Throwable failure) {
   IoUtils.safeClose(this.connection);
   if (connectFuture.setException(failure)) {
     return;
   }
   if (this.session.isDisconnected()) {
     this.session.afterTransportClosed(null);
   } else {
     this.session.handleTransportError(failure);
     this.session.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
   }
 }
Пример #26
0
  private void handleError(IOException e) {

    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    IoUtils.safeClose(SpdyClientConnection.this);
    for (Map.Entry<Integer, SpdyClientExchange> entry : currentExchanges.entrySet()) {
      try {
        entry.getValue().failed(e);
      } catch (Exception ex) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(new IOException(ex));
      }
    }
  }
Пример #27
0
 @Test
 public void testMBean() throws Exception {
   final JMXConnector connector = JMXConnectorFactory.connect(managementClient.getRemoteJMXURL());
   try {
     MBeanServerConnection mbeanServer = connector.getMBeanServerConnection();
     ObjectName objectName = new ObjectName("jboss:name=test,type=config");
     mbeanServer.getAttribute(objectName, "IntervalSeconds");
     mbeanServer.setAttribute(objectName, new Attribute("IntervalSeconds", 2));
   } finally {
     IoUtils.safeClose(connector);
   }
 }
 @Override
 public void run() {
   UndertowLogger.REQUEST_LOGGER.tracef("Timing out channel %s due to inactivity");
   IoUtils.safeClose(connection);
   if (connection.getSourceChannel().isReadResumed()) {
     ChannelListeners.invokeChannelListener(
         connection.getSourceChannel(), connection.getSourceChannel().getReadListener());
   }
   if (connection.getSinkChannel().isWriteResumed()) {
     ChannelListeners.invokeChannelListener(
         connection.getSinkChannel(), connection.getSinkChannel().getWriteListener());
   }
 }
 @Override
 public void handleEvent(final StreamSourceChannel channel) {
   try {
     doParse(channel);
     if (state == 4) {
       exchange.dispatch(SameThreadExecutor.INSTANCE, handler);
     }
   } catch (IOException e) {
     IoUtils.safeClose(channel);
     UndertowLogger.REQUEST_LOGGER.ioExceptionReadingFromChannel(e);
     exchange.endExchange();
   }
 }
Пример #30
0
 private static void copyFile(File file, File directory) throws IOException {
   File tgt = new File(directory, file.getName());
   if (tgt.exists()) {
     if (!tgt.delete()) {
       throw new IllegalStateException("Could not delete file " + tgt.getAbsolutePath());
     }
   }
   final InputStream in = new BufferedInputStream(new FileInputStream(file));
   try {
     final OutputStream out = new BufferedOutputStream(new FileOutputStream(tgt));
     try {
       int i = in.read();
       while (i != -1) {
         out.write(i);
         i = in.read();
       }
     } finally {
       IoUtils.safeClose(out);
     }
   } finally {
     IoUtils.safeClose(in);
   }
 }