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();
 }
 @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());
 }
    @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 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;
   }
 }
  @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);
    }
  }
 @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());
   }
 }
 private void handleError(final StreamSinkChannel channel, final IOException e) {
   try {
     listener.onError(e);
   } finally {
     IoUtils.safeClose(channel);
   }
 }
 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;
 }
 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);
 }
Beispiel #10
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);
   }
 }
  /** 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);
    }
  }
Beispiel #12
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();
   }
 }
Beispiel #13
0
 @Override
 void stopListening() {
   server.suspendAccepts();
   UndertowLogger.ROOT_LOGGER.listenerSuspend("AJP", getName());
   IoUtils.safeClose(server);
   UndertowLogger.ROOT_LOGGER.listenerStopped(
       "AJP", getName(), getBinding().getValue().getSocketAddress());
 }
Beispiel #14
0
 @Override
 public void couldNotResolveBackend(HttpServerExchange exchange) {
   if (exchange.isResponseStarted()) {
     IoUtils.safeClose(exchange.getConnection());
   } else {
     exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
     exchange.endExchange();
   }
 }
Beispiel #15
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();
   }
 }
Beispiel #16
0
 public synchronized void stop() {
   for (AcceptingChannel<? extends StreamConnection> channel : channels) {
     IoUtils.safeClose(channel);
   }
   channels = null;
   worker.shutdownNow();
   worker = null;
   xnio = null;
 }
  @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);
                }
              }
            });
  }
 void closeAsync() {
   IoUtils.safeClose(pipeOutputStream);
   synchronized (this) {
     channel.free(this);
     closed = true;
     // wake up waiters
     notifyAll();
   }
 }
 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);
 }
Beispiel #20
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());
   }
 }
Beispiel #21
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);
   }
 }
  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));
      }
    }
  }
 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()));
   }
 }
 @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();
   }
 }
 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);
   }
 }
  @Override
  public synchronized void stop(final StopContext context) {
    // un-register ourselves to the TimerServiceRegistry (if any)
    if (timerServiceRegistry != null) {
      timerServiceRegistry.unRegisterTimerService(this);
    }

    timerPersistence.getValue().timerUndeployed(timedObjectInvoker.getValue().getTimedObjectId());
    started = false;
    this.transactionManager = null;
    IoUtils.safeClose(listenerHandle);
    listenerHandle = null;
    timerInjectedValue.getValue().purge(); // WFLY-3823
  }
 @Override
 public void handleEvent(final StreamSourceChannel channel) {
   if (anyAreClear(state, FLAG_FINISHED)) {
     try {
       state |= FLAG_READY;
       channel.suspendReads();
       listener.onDataAvailable();
     } catch (IOException e) {
       UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
       IoUtils.safeClose(channel);
     }
   }
   if (anyAreSet(state, FLAG_FINISHED) && anyAreClear(state, FLAG_ON_DATA_READ_CALLED)) {
     state |= FLAG_ON_DATA_READ_CALLED;
     try {
       channel.shutdownReads();
       listener.onAllDataRead();
     } catch (IOException e) {
       IoUtils.safeClose(channel);
     }
   } else if (allAreClear(state, FLAG_FINISHED)) {
     channel.resumeReads();
   }
 }
 private void sendVersionZeroHeader(Channel channel) throws IOException {
   log.debug("Selecting version 0x00 to receive full version list.");
   CancellableDataOutputStream dos = new CancellableDataOutputStream(channel.writeMessage());
   try {
     dos.writeBytes(JMX);
     dos.writeByte(0x00);
     String remotingJMXVersion = Version.getVersionString();
     byte[] versionBytes = remotingJMXVersion.getBytes("UTF-8");
     dos.writeInt(versionBytes.length);
     dos.write(versionBytes);
   } catch (IOException e) {
     dos.cancel();
     throw e;
   } finally {
     IoUtils.safeClose(dos);
   }
 }
    @Override
    public void handleEvent(StreamSourceChannel channel) {
      if (this.session.isDisconnected()) {
        if (logger.isDebugEnabled()) {
          logger.debug("SockJS sockJsSession closed, closing response.");
        }
        IoUtils.safeClose(this.connection);
        throw new SockJsException("Session closed.", this.session.getId(), null);
      }

      Object pooled = undertowBufferSupport.allocatePooledResource();
      try {
        int r;
        do {
          ByteBuffer buffer = undertowBufferSupport.getByteBuffer(pooled);
          buffer.clear();
          r = channel.read(buffer);
          buffer.flip();
          if (r == 0) {
            return;
          } else if (r == -1) {
            onSuccess();
          } else {
            while (buffer.hasRemaining()) {
              int b = buffer.get();
              if (b == '\n') {
                handleFrame();
              } else {
                this.outputStream.write(b);
              }
            }
          }
        } while (r > 0);
      } catch (IOException exc) {
        onFailure(exc);
      } finally {
        undertowBufferSupport.closePooledResource(pooled);
      }
    }