Пример #1
0
 @Override
 protected void onUserList(String channel, User[] users) {
   Channel c = this.getChannel(channel);
   for (int i = 0; i < users.length; i++) {
     c.addUser(users[i].toString());
   }
 }
Пример #2
0
 private static void setStableGossip(JChannel... channels) {
   for (Channel channel : channels) {
     ProtocolStack stack = channel.getProtocolStack();
     STABLE stable = (STABLE) stack.findProtocol(STABLE.class);
     stable.setDesiredAverageGossip(2000);
   }
 }
Пример #3
0
  public void run() {

    final One2OneChannelInt[] left = Channel.one2oneIntArray(nPhilosophers);
    final One2OneChannelInt[] right = Channel.one2oneIntArray(nPhilosophers);

    final Any2OneChannelInt down = Channel.any2oneInt();
    final Any2OneChannelInt up = Channel.any2oneInt();

    final Fork[] fork = new Fork[nPhilosophers];
    for (int i = 0; i < nPhilosophers; i++) {
      fork[i] =
          new Fork(nPhilosophers, i, left[i].in(), right[(i + 1) % nPhilosophers].in(), forkReport);
    }

    final Philosopher[] phil = new Philosopher[nPhilosophers];
    for (int i = 0; i < nPhilosophers; i++) {
      phil[i] = new Philosopher(i, left[i].out(), right[i].out(), down.out(), up.out(), philReport);
    }

    new Parallel(
            new CSProcess[] {
              new Parallel(phil),
              new Parallel(fork),
              new Security(down.in(), up.in(), securityReport, nPhilosophers - 1),
              new Clock(clockReport, clockPeriod)
            })
        .run();
  }
Пример #4
0
  @Ignore
  @Test
  public void whenReceiveNotCalledFromOwnerThenThrowException3() throws Exception {
    assumeTrue(Debug.isAssertionsEnabled());
    final Channel<String> ch = newChannel();

    Fiber fib =
        new Fiber(
                "fiber",
                fjPool,
                new SuspendableRunnable() {
                  @Override
                  public void run() throws SuspendExecution, InterruptedException {
                    Fiber.sleep(100);

                    ch.send("a message");

                    boolean thrown = false;
                    try {
                      ch.receive();
                    } catch (Throwable e) {
                      thrown = true;
                    }
                    assertTrue(thrown);
                  }
                })
            .start();

    String m = ch.receive();

    assertThat(m, equalTo("a message"));

    fib.join();
  }
Пример #5
0
  @Test
  public void testBlockingChannelSendingThread() throws Exception {
    assumeThat(policy, is(OverflowPolicy.BLOCK));
    final Channel<Integer> ch = newChannel();

    Fiber<Integer> fib =
        new Fiber<Integer>(
                fjPool,
                new SuspendableCallable<Integer>() {
                  @Override
                  public Integer run() throws SuspendExecution, InterruptedException {
                    int i = 0;
                    while (ch.receive() != null) {
                      i++;
                      Fiber.sleep(50);
                    }
                    return i;
                  }
                })
            .start();

    for (int i = 0; i < 10; i++) ch.send(i);
    ch.close();

    assertThat(fib.get(), is(10));
  }
Пример #6
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");
  }
Пример #7
0
  private void ban(MessageContext context, String args) {
    if (args.isEmpty()) {
      return;
    }
    String[] split = args.split(" ");
    List<String> banned = new ArrayList<>();
    List<String> failed = new ArrayList<>();
    Channel channel = context.getChannel();
    for (String userStr : split) {
      User user = findUser(context, userStr);
      String userId = user.getId();
      if (user == NO_USER) {
        userId = userStr;
      }

      if (banChecked(channel, context.getAuthor(), user, context.getServer())) {
        banned.add(userId + " " + user.getUsername());
      } else {
        failed.add(userId + " " + user.getUsername());
      }
    }

    if (channel.getId() != null) {
      StringJoiner joiner = new StringJoiner("\n");
      for (String s : banned) {
        String[] pair = s.split(" ", 2);
        joiner.add(loc.localize("commands.mod.ban.response", pair[1], pair[0]));
      }
      apiClient.sendMessage(joiner.toString(), channel);
    }
  }
Пример #8
0
  public Channel openDirectTCPIPChannel(
      String host_to_connect,
      int port_to_connect,
      String originator_IP_address,
      int originator_port)
      throws IOException {
    Channel c = new Channel(this);

    synchronized (c) {
      c.localID = addChannel(c);
      // end of synchronized block forces writing out to main memory
    }

    PacketOpenDirectTCPIPChannel dtc =
        new PacketOpenDirectTCPIPChannel(
            c.localID,
            c.localWindow,
            c.localMaxPacketSize,
            host_to_connect,
            port_to_connect,
            originator_IP_address,
            originator_port);

    tm.sendMessage(dtc.getPayload());

    waitUntilChannelOpen(c);

    return c;
  }
Пример #9
0
  public void requestSubSystem(Channel c, String subSystemName) throws IOException {
    PacketSessionSubsystemRequest ssr;

    synchronized (c) {
      if (c.state != Channel.STATE_OPEN)
        throw new IOException(
            "Cannot request subsystem on this channel (" + c.getReasonClosed() + ")");

      ssr = new PacketSessionSubsystemRequest(c.remoteID, true, subSystemName);

      c.successCounter = c.failedCounter = 0;
    }

    synchronized (c.channelSendLock) {
      if (c.closeMessageSent)
        throw new IOException(
            "Cannot request subsystem on this channel (" + c.getReasonClosed() + ")");
      tm.sendMessage(ssr.getPayload());
    }

    try {
      waitForChannelSuccessOrFailure(c);
    } catch (IOException e) {
      throw (IOException) new IOException("The subsystem request failed.").initCause(e);
    }
  }
Пример #10
0
  private void waitForChannelSuccessOrFailure(Channel c) throws IOException {
    boolean wasInterrupted = false;

    try {
      synchronized (c) {
        while ((c.successCounter == 0) && (c.failedCounter == 0)) {
          if (c.state != Channel.STATE_OPEN) {
            String detail = c.getReasonClosed();

            if (detail == null) detail = "state: " + c.state;

            throw new IOException("This SSH2 channel is not open (" + detail + ")");
          }

          try {
            c.wait();
          } catch (InterruptedException ignore) {
            wasInterrupted = true;
          }
        }

        if (c.failedCounter != 0) {
          throw new IOException("The server denied the request.");
        }
      }
    } finally {
      if (wasInterrupted) Thread.currentThread().interrupt();
    }
  }
Пример #11
0
  public void closeChannel(Channel c, String reason, boolean force) throws IOException {
    byte msg[] = new byte[5];

    synchronized (c) {
      if (force) {
        c.state = Channel.STATE_CLOSED;
        c.EOF = true;
      }

      c.setReasonClosed(reason);

      msg[0] = Packets.SSH_MSG_CHANNEL_CLOSE;
      msg[1] = (byte) (c.remoteID >> 24);
      msg[2] = (byte) (c.remoteID >> 16);
      msg[3] = (byte) (c.remoteID >> 8);
      msg[4] = (byte) (c.remoteID);

      c.notifyAll();
    }

    synchronized (c.channelSendLock) {
      if (c.closeMessageSent == true) return;
      tm.sendMessage(msg);
      c.closeMessageSent = true;
    }

    log.debug("Sent SSH_MSG_CHANNEL_CLOSE (channel " + c.localID + ")");
  }
Пример #12
0
  private void waitUntilChannelOpen(Channel c) throws IOException {
    boolean wasInterrupted = false;

    synchronized (c) {
      while (c.state == Channel.STATE_OPENING) {
        try {
          c.wait();
        } catch (InterruptedException ignore) {
          wasInterrupted = true;
        }
      }

      if (c.state != Channel.STATE_OPEN) {
        removeChannel(c.localID);

        String detail = c.getReasonClosed();

        if (detail == null) detail = "state: " + c.state;

        throw new IOException("Could not open channel (" + detail + ")");
      }
    }

    if (wasInterrupted) Thread.currentThread().interrupt();
  }
Пример #13
0
 @Override
 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   Channel channel = ctx.getChannel();
   if (!sessions.removeSession(channel.getId())) {
     Log.error("删除Session失败! sockId: " + channel.getId());
   }
 }
  /**
   * Sets the values of the properties of a specific <tt>ColibriConferenceIQ</tt> to the values of
   * the respective properties of this instance. Thus, the specified <tt>iq</tt> may be thought of
   * as a description of this instance.
   *
   * <p><b>Note</b>: The copying of the values is deep i.e. the <tt>Contents</tt>s of this instance
   * are described in the specified <tt>iq</tt>.
   *
   * @param iq the <tt>ColibriConferenceIQ</tt> to set the values of the properties of this instance
   *     on
   */
  public void describeDeep(ColibriConferenceIQ iq) {
    describeShallow(iq);

    if (isRecording()) {
      ColibriConferenceIQ.Recording recordingIQ =
          new ColibriConferenceIQ.Recording(State.ON.toString());
      recordingIQ.setDirectory(getRecordingDirectory());
      iq.setRecording(recordingIQ);
    }
    for (Content content : getContents()) {
      ColibriConferenceIQ.Content contentIQ = iq.getOrCreateContent(content.getName());

      for (Channel channel : content.getChannels()) {
        if (channel instanceof SctpConnection) {
          ColibriConferenceIQ.SctpConnection sctpConnectionIQ =
              new ColibriConferenceIQ.SctpConnection();

          channel.describe(sctpConnectionIQ);
          contentIQ.addSctpConnection(sctpConnectionIQ);
        } else {
          ColibriConferenceIQ.Channel channelIQ = new ColibriConferenceIQ.Channel();

          channel.describe(channelIQ);
          contentIQ.addChannel(channelIQ);
        }
      }
    }
  }
Пример #15
0
  public void onMessage(Message message) {
    if (message.getType() == MessageType.MSG && message.get(MessageProperty.ROOM).equals("#main")) {
      long userId = message.get(MessageProperty.USER_ID);
      String name = message.get(MessageProperty.NAME);
      UserCredentials userCredentials = null;
      if (needsFetchingConnectionData(userId)) {
        userCredentials = fetchConnectionDataForUser(name, userId);
      }

      if (userCredentials != null) {
        String id = userCredentials.getId();
        Channel channel = connections.get(id.toLowerCase());
        if (channel == null || !channel.isActive()) {
          try {
            channel = createConnection(id, userCredentials.getToken());
          } catch (InterruptedException e) {
            logger.warn("", e);
          }
        }
        if (channel != null) {
          channel.attr(lastMessageAttrKey).set(System.currentTimeMillis());
          channel.writeAndFlush(
              "PRIVMSG #" + this.channel + " :" + message.get(MessageProperty.TEXT) + "\r\n");
        }
      }
    }
  }
Пример #16
0
  /**
   * @param charsetName The charset used to convert between Java Unicode Strings and byte encodings
   */
  public void requestExecCommand(Channel c, String cmd, String charsetName) throws IOException {
    PacketSessionExecCommand sm;

    synchronized (c) {
      if (c.state != Channel.STATE_OPEN)
        throw new IOException(
            "Cannot execute command on this channel (" + c.getReasonClosed() + ")");

      sm = new PacketSessionExecCommand(c.remoteID, true, cmd);

      c.successCounter = c.failedCounter = 0;
    }

    synchronized (c.channelSendLock) {
      if (c.closeMessageSent)
        throw new IOException(
            "Cannot execute command on this channel (" + c.getReasonClosed() + ")");
      tm.sendMessage(sm.getPayload(charsetName));
    }

    log.debug("Executing command (channel " + c.localID + ", '" + cmd + "')");

    try {
      waitForChannelSuccessOrFailure(c);
    } catch (IOException e) {
      throw (IOException) new IOException("The execute request failed.").initCause(e);
    }
  }
Пример #17
0
  @Override
  public void run() {
    // Wait for clients to connect.
    // When a client has connected, create a new ClientConnection
    Socket clientSock = null;
    channel.startServer();

    while (true) {
      clientSock = channel.accept();
      System.out.println("A new client has connected");

      if (clientSock != null) {
        ClientConnection clientConn = new ClientConnection(clientSock, this, nextClientID);

        nextClientID++;

        Thread thread = new Thread(clientConn);
        thread.start();
        clientSock = null;
      }

      System.out.println(
          "Client has been served by ClientHandler. " + "Now looking for new connections");
    }
  }
Пример #18
0
 public RemotingException(Channel channel, String message, Throwable cause) {
   this(
       channel == null ? null : channel.getLocalAddress(),
       channel == null ? null : channel.getRemoteAddress(),
       message,
       cause);
 }
 private boolean accept() {
   InputStream in = null;
   OutputStream out = null;
   Socket socket = null;
   Channel channel = null;
   try {
     try {
       socket = this.serverSocket.accept();
     } catch (IOException ex) {
       return false;
     } // socket closed
     in = socket.getInputStream();
     out = socket.getOutputStream();
     ContextRunner runner =
         new ContextRunner(channel = new Channel(getChannelName(), in, out, socket), logger);
     if (threadPool != null) {
       threadPool.start(runner);
     } else {
       Thread t = new Util.Thread(runner, "JavaBridgeContextRunner(" + contextName + ")");
       t.start();
     }
   } catch (SecurityException t) {
     if (channel != null) channel.shutdown();
     ContextFactory.destroyAll();
     Util.printStackTrace(t);
     return false;
   } catch (Throwable t) {
     if (channel != null) channel.shutdown();
     Util.printStackTrace(t);
   }
   return true;
 }
Пример #20
0
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("10.71.49.228");
    factory.setUsername("jinhd");
    factory.setPassword("admin");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer =
        new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
              throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
          }
        };
    channel.basicConsume(queueName, true, consumer);
  }
Пример #21
0
  @Test
  public void sendMessageFromThreadToThread() throws Exception {
    final Channel<String> ch = newChannel();

    Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  Thread.sleep(100);

                  ch.send("a message");
                } catch (InterruptedException | SuspendExecution ex) {
                  throw new AssertionError(ex);
                }
              }
            });
    thread.start();

    String m = ch.receive();

    assertThat(m, equalTo("a message"));

    thread.join();
  }
Пример #22
0
 /**
  * Constructs a new message that requires multiple channels to have read it.
  *
  * @param requiredRead The channels that need to have read the message
  */
 public ChannelMessage(Channel... requiredRead) {
   short required = 0;
   for (Channel channel : requiredRead) {
     required |= channel.getMask();
   }
   requiredMask = required;
 }
Пример #23
0
  @Ignore
  @Test
  public void whenReceiveNotCalledFromOwnerThenThrowException4() throws Exception {
    assumeTrue(Debug.isAssertionsEnabled());
    final Channel<String> ch = newChannel();

    Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  ch.receive();
                } catch (InterruptedException ex) {
                  throw new AssertionError(ex);
                } catch (SuspendExecution e) {
                  throw new AssertionError(e);
                }
              }
            });
    thread.start();

    Thread.sleep(100);
    ch.send("a message");

    boolean thrown = false;
    try {
      ch.receive();
    } catch (Throwable e) {
      thrown = true;
    }
    assertTrue(thrown);

    thread.join();
  }
Пример #24
0
  public void doCounsumer() throws IOException, TimeoutException {
    factory.setHost("localhost");
    factory.setVirtualHost("epush");
    factory.setUsername("epush");
    factory.setPassword("epush");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    Consumer consumer =
        new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
              throws IOException {
            try {
              OtpInputStream InputStream = new OtpInputStream(body);
              OtpErlangTuple login = (OtpErlangTuple) OtpErlangTuple.decode(InputStream);

              LoginEvent loginEvent = new LoginEvent(login);

              System.out.println(loginEvent);

              // mapper.writeValueAsString(loginEvent);

            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };

    channel.basicConsume("epush-login-queue", consumer);
  }
Пример #25
0
 private static void setOOBPoolSize(JChannel... channels) {
   for (Channel channel : channels) {
     TP transport = channel.getProtocolStack().getTransport();
     transport.setOOBThreadPoolMinThreads(1);
     transport.setOOBThreadPoolMaxThreads(2);
   }
 }
Пример #26
0
  /**
   * This will execute the given command with given session and session is not closed at the end.
   *
   * @param commandInfo
   * @param session
   * @param commandOutput
   * @throws SSHApiException
   */
  public static Session executeCommand(
      CommandInfo commandInfo, Session session, CommandOutput commandOutput)
      throws SSHApiException {

    String command = commandInfo.getCommand();

    Channel channel = null;
    try {
      if (!session.isConnected()) {
        session.connect();
      }
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
    } catch (JSchException e) {
      session.disconnect();

      throw new SSHApiException("Unable to execute command - ", e);
    }

    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(commandOutput.getStandardError());
    try {
      channel.connect();
    } catch (JSchException e) {

      channel.disconnect();
      session.disconnect();
      throw new SSHApiException("Unable to retrieve command output. Command - " + command, e);
    }

    commandOutput.onOutput(channel);
    // Only disconnecting the channel, session can be reused
    channel.disconnect();
    return session;
  }
Пример #27
0
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);

    final Consumer consumer =
        new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
              throws IOException {
            String message = new String(body, "UTF-8");

            System.out.println(" [x] Received '" + message + "'");
            try {
              doWork(message);
            } finally {
              System.out.println(" [x] Done");
              channel.basicAck(envelope.getDeliveryTag(), false);
            }
          }
        };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
  }
  /**
   * delete a channel from the database
   *
   * @param parent device which was deleted and who's channels should be deleted as well
   * @return if deleted
   */
  public static Boolean deleteChannel(long parent) {
    // get all channels
    Cursor cursor =
        homeMaticDatabase.query(
            DatabaseHelper.TABLE_CHANNEL,
            allColumnsChannel,
            DatabaseHelper.COLUMN_CHANNEL_PARENT_DEVICE + " = " + '"' + parent + '"',
            null,
            null,
            null,
            null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Channel channel = cursorToChannel(cursor);
      List<Position> positions = getAllPositions();
      for (int i = 0; i < positions.size(); i++) {
        if (positions.get(i).getChannel_id().equals(String.valueOf(channel.get_id()))) {
          // delete it's position entry
          deletePosition(positions.get(i));
        }
      }

      // delete channel from database
      homeMaticDatabase.delete(
          DatabaseHelper.TABLE_CHANNEL,
          DatabaseHelper.COLUMN_CHANNEL_ID + " = " + channel.get_id(),
          null);
      // delete its values
      deleteValue(channel.get_id());
      cursor.moveToNext();
    }
    return true;
  }
Пример #29
0
  public void onClick(View v) {
    int id = v.getId();
    DBStorage dbStorage;
    switch (id) {
      case R.id.dialog_delete:
        dbStorage = new DBStorage(context);
        dbStorage.deleteChannel(channel.id);
        dbStorage.destroy();
        listener.onDialogDismissed();
        break;
      case R.id.dialog_change:
        dbStorage = new DBStorage(context);
        channel.name = etName.getText().toString();
        channel.link = etLink.getText().toString();
        channel.encoding = etEncoding.getText().toString();
        dbStorage.changeChannel(channel);
        dbStorage.destroy();
        listener.onDialogDismissed();
        break;

      case R.id.dialog_cancel:
        break;
    }
    dismiss();
  }
Пример #30
0
  static boolean getConnection(String username, String password, String host, int port) {
    try {
      JSch jsch = new JSch();

      session = jsch.getSession(username, host, port);

      UserInfo ui = new MyUserInfo();
      session.setUserInfo(ui);
      MyUserInfo temp = (MyUserInfo) ui;

      temp.setPassword(password);

      session.connect();

      Channel channel = session.openChannel("sftp");
      channel.connect();
      SFTPFileLoader.sftpChannel = (ChannelSftp) channel;

      return true;

    } catch (Exception e) {
      System.out.println(e);
      errorMessage += e.toString();
    }

    return false;
  }