private ChannelFuture sendFile(ChannelHandlerContext ctx, Channel ch, FileChunk file)
      throws IOException {
    RandomAccessFile raf;
    try {
      raf = new RandomAccessFile(file.getFile(), "r");
    } catch (FileNotFoundException fnfe) {
      return null;
    }

    ChannelFuture writeFuture;
    if (ch.getPipeline().get(SslHandler.class) != null) {
      // Cannot use zero-copy with HTTPS.
      writeFuture = ch.write(new ChunkedFile(raf, file.startOffset(), file.length(), 8192));
    } else {
      // No encryption - use zero-copy.
      final FileRegion region =
          new DefaultFileRegion(raf.getChannel(), file.startOffset(), file.length());
      writeFuture = ch.write(region);
      writeFuture.addListener(
          new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
              region.releaseExternalResources();
            }
          });
    }

    return writeFuture;
  }
  /**
   * 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);
        }
      }
    }
  }
Beispiel #3
0
  /**
   * Copy a file to specific destination with WinSCP command
   *
   * @param lfile file you want to transfer
   * @param rfile destination file
   */
  public synchronized void scpTo(String lfile, String rfile) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    try {
      // exec 'scp -t rfile' remotely
      String command = "scp -p -t " + rfile;

      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      // get I/O streams for remote scp
      OutputStream out = channel.getOutputStream();
      InputStream in = channel.getInputStream();

      channel.connect();

      // byte[] tmp = new byte[1];
      checkAck(in);

      // send "C0644 filesize filename", where filename should not include '/'
      int filesize = (int) (new File(lfile)).length();
      command = "C0644 " + filesize + " ";
      if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
      } else {
        command += lfile;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      checkAck(in);

      // send a content of lfile
      FileInputStream fis = new FileInputStream(lfile);
      byte[] buf = new byte[1024];
      while (true) {
        int len = fis.read(buf, 0, buf.length);
        if (len <= 0) break;
        out.write(buf, 0, len);
        out.flush();
      }
      fis.close();

      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();

      checkAck(in);
    } catch (Exception e) {
      throw new ItemNotFoundException("Failed to copy file: " + e.getMessage());
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
 public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2) {
   this.channel = channel;
   prot_adapter = new ProtocolAdapter();
   if (channel != null) {
     local_addr = channel.getAddress();
     channel.addChannelListener(this);
   }
   setMessageListener(l);
   setMembershipListener(l2);
   if (channel != null) installUpHandler(prot_adapter, true);
   start();
 }
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    Channel ch = e.getChannel();
    Throwable cause = e.getCause();
    if (cause instanceof TooLongFrameException) {
      sendError(ctx, BAD_REQUEST);
      return;
    }

    cause.printStackTrace();
    if (ch.isConnected()) {
      sendError(ctx, INTERNAL_SERVER_ERROR);
    }
  }
Beispiel #6
0
  public void textInserted(Message.TextPasteMsg m) {

    try {

      int SenderId = m.getClientId();
      int offset = m.getOffset();
      String textPasted = m.getText();

      if (EditorServer_Debug)
        System.err.println("EditorServer->textinserted : PASTED by : " + SenderId);

      Vector pars = null;
      try {
        pars = lockManager.textInserted(m.getPar(), offset, textPasted, SenderId);
        if (EditorServer_Debug)
          System.err.println("\n+=*%EditorServer--> textInserted recovered VECTOR...");
      } catch (Exception e) {
        System.err.println("\n+=*%EditorServer--> textInserted VECTOR error ");
      }

      textChannel.sendToOthers(client, new Data(m));

      EditorClient SenderClient = getEditorClient(SenderId);
      SenderClient.addTextPasteAction(System.currentTimeMillis(), pars, offset, textPasted);
      clientsPanel.updateActionTableFor(SenderClient);
      updateParagraphList();
    } catch (Exception e) {
      System.err.println("\nEditorServer--> textPasted: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #7
0
  public void textInserted(Message.TextInsertMsg m) {
    if (EditorServer_Debug) System.err.println("EditorServer-> textInserted.");

    try {
      int ClientId = m.getClientId();
      int offset = m.getOffset();
      String characterInserted = m.getText();

      if (EditorServer_Debug)
        System.out.println("EditorServer-> textInserted : *" + characterInserted + "*");

      Vector pars = lockManager.textInserted(m.getPar(), offset, characterInserted, ClientId);

      textChannel.sendToOthers(client, new Data(m));
      EditorClient c = getEditorClient(ClientId);

      // new condition inserted to avoid timestamp generation if the character
      // is a newline

      if (characterInserted.equals("\n")) {
        if (EditorServer_Debug)
          System.out.println("EditorServer-> textInserted : attempting to insert a newLine");
      }
      c.addTextInsertAction(System.currentTimeMillis(), pars, offset, characterInserted);
      clientsPanel.updateActionTableFor(c);
      updateParagraphList();

    } catch (Exception e) {
      System.err.println("EditorServer-> textInserted: error receiving-sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #8
0
  public void sendHighlights() {

    // send highlights to everybody
    try {
      Iterator i = highlights.getHighlights().iterator();
      while (i.hasNext()) {
        Highlights.Highlight h = (Highlights.Highlight) i.next();
        Paragraph sPar = lockManager.getParFromOffset(h.getStart());
        Paragraph ePar = lockManager.getParFromOffset(h.getEnd());

        if (EditorServer_Debug) {
          System.out.println("StartPar: " + sPar.toString());
          System.out.println("EndPar: " + ePar.toString());
        }

        Message.HighlightAddMsg msg =
            new Message.HighlightAddMsg(
                -1,
                h.getId(),
                h.getType().getId(),
                sPar.getID(),
                ePar.getID(),
                h.getStart() - sPar.getOffset(),
                h.getEnd() - ePar.getOffset());
        textChannel.sendToOthers(client, new Data(msg));
      }
    } catch (Exception e) {
      System.err.println("EditorServer: sendHighlights: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
 /** {@inheritDoc} */
 @Override
 public void expire() {
   try {
     eventDispatcher.shutdown();
   } finally {
     super.expire();
   }
 }
  public void stop() {
    if (corr != null) corr.stop();

    if (channel instanceof JChannel) {
      TP transport = channel.getProtocolStack().getTransport();
      transport.unregisterProbeHandler(probe_handler);
      corr.unregisterProbeHandler(transport);
    }
  }
Beispiel #11
0
 public void sendClientReject(int keyValue, int reason) {
   Message.ClientRejectMsg msg = new Message.ClientRejectMsg(-1, keyValue, reason);
   try {
     clientChannel.sendToOthers(client, new Data(msg));
   } catch (Exception e) {
     System.err.println("EditorServer: clientRejected: error sending msg");
     if (EditorServer_Debug) e.printStackTrace();
   }
 }
 public void setChannel(Channel ch) {
   if (ch == null) return;
   this.channel = ch;
   local_addr = channel.getAddress();
   if (prot_adapter == null) prot_adapter = new ProtocolAdapter();
   // Don't force installing the UpHandler so subclasses can use this
   // method and still integrate with a MuxUpHandler
   installUpHandler(prot_adapter, false);
 }
Beispiel #13
0
 public void scrollMoved(Message.ScrollMoveMsg m) {
   // if(EditorServer_Debug) System.err.println("EditorServer: scrollMoved.") ;
   try {
     clientChannel.sendToOthers(client, new Data(m));
   } catch (Exception e) {
     System.err.println("EditorServer: scrollMoved: error sending msg");
     if (EditorServer_Debug) e.printStackTrace();
   }
 }
Beispiel #14
0
 public void sendDocumentState(int clientId) {
   Message.DocumentStateMsg msg =
       new Message.DocumentStateMsg(clientId, lockManager.getDocumentAsXML());
   try {
     clientChannel.sendToOthers(client, new Data(msg));
   } catch (Exception e) {
     System.err.println("EditorServer: sendDocumentState: error sending msg");
     if (EditorServer_Debug) e.printStackTrace();
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.outgoing.AbstractOutgoingFileTransfer
   * #openStreams()
   */
  protected void openStreams() throws IncomingFileTransferException {
    try {
      // Set input stream from local file
      final URL url = getRemoteFileURL();
      this.username = url.getUserInfo();

      scpUtil = new ScpUtil(this);
      final Session s = scpUtil.getSession();
      s.connect();

      final String command = SCP_COMMAND + scpUtil.trimTargetFile(url.getPath());
      channel = s.openChannel(SCP_EXEC);
      ((ChannelExec) channel).setCommand(command);
      channel.connect();

      final InputStream ins = channel.getInputStream();
      responseStream = channel.getOutputStream();
      scpUtil.sendZeroToStream(responseStream);

      final int c = checkAck(ins);
      if (c != 'C') throw new IOException(Messages.ScpRetrieveFileTransfer_EXCEPTION_SCP_PROTOCOL);
      // read '0644 '
      final byte[] buf = new byte[1024];
      ins.read(buf, 0, 5);

      setFileLength(readFileSize(ins, buf));
      readFileName(ins, buf);
      // set input stream for reading rest of file
      remoteFileContents = ins;

      scpUtil.sendZeroToStream(responseStream);

      fireReceiveStartEvent();
    } catch (final Exception e) {
      channel = null;
      username = null;
      throw new IncomingFileTransferException(
          NLS.bind(
              Messages.ScpRetrieveFileTransfer_EXCEPTION_CONNECTING, getRemoteFileURL().toString()),
          e);
    }
  }
  public void start() {
    if (corr == null)
      corr =
          createRequestCorrelator(prot_adapter, this, local_addr)
              .asyncDispatching(async_dispatching);
    correlatorStarted();
    corr.start();

    if (channel != null) {
      List<Address> tmp_mbrs = channel.getView() != null ? channel.getView().getMembers() : null;
      setMembers(tmp_mbrs);
      if (channel instanceof JChannel) {
        TP transport = channel.getProtocolStack().getTransport();
        corr.registerProbeHandler(transport);
      }
      TP transport = channel.getProtocolStack().getTransport();
      hardware_multicast_supported = transport.supportsMulticasting();
      transport.registerProbeHandler(probe_handler);
    }
  }
Beispiel #17
0
  /**
   * This procedure is invoked to process the "flush" Tcl command. See the user documentation for
   * details on what it does.
   *
   * @param interp the current interpreter.
   * @param argv command arguments.
   */
  public void cmdProc(Interp interp, TclObject argv[]) throws TclException {

    Channel chan; /* The channel being operated on this method */

    if (argv.length != 2) {
      throw new TclNumArgsException(interp, 1, argv, "channelId");
    }

    chan = TclIO.getChannel(interp, argv[1].toString());
    if (chan == null) {
      throw new TclException(interp, "can not find channel named \"" + argv[1].toString() + "\"");
    }

    try {
      chan.flush(interp);
    } catch (IOException e) {
      throw new TclRuntimeError(
          "FlushCmd.cmdProc() Error: IOException when flushing " + chan.getChanName());
    }
  }
Beispiel #18
0
  public void lockReleased(Message.LockReleaseMsg m) {
    if (EditorServer_Debug) System.err.println("EditorServer: lockReleased.");

    lockManager.lockReleased(m.getStartPar(), m.getEndPar(), m.getClientId());
    try {
      textChannel.sendToOthers(client, new Data(m));
    } catch (Exception e) {
      System.err.println("EditorServer: lockReleased: error sending lock released");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #19
0
  public void highlightDeleted(Message.HighlightDeleteMsg m) {
    if (EditorServer_Debug) System.err.println("EditorServer: highlightDeleted.");

    highlights.deleteHighlight(m.getId());
    EditorClient c = getEditorClient(m.getClientId());
    try {
      textChannel.sendToOthers(client, new Data(m));
    } catch (Exception e) {
      System.err.println("EditorServer: highlightDeleted: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
 private void cleanup(int code, String message) {
   try {
     channel.close(code, message);
   } catch (Exception e) {
     logger.debug("failed to close channel on [{}]", e, message);
   }
   try {
     connection.close(code, message);
   } catch (Exception e) {
     logger.debug("failed to close connection on [{}]", e, message);
   }
 }
  /**
   * Creates a channel for shell type in the current session channel types = shell, sftp, exec(X
   * forwarding), direct-tcpip(stream forwarding) etc
   *
   * @param sshContact ID of SSH Contact
   */
  public void createShellChannel(ContactSSH sshContact) throws IOException {
    try {
      Channel shellChannel = sshContact.getSSHSession().openChannel("shell");

      // initalizing the reader and writers of ssh contact
      sshContact.initializeShellIO(shellChannel.getInputStream(), shellChannel.getOutputStream());

      ((ChannelShell) shellChannel)
          .setPtyType(sshContact.getSSHConfigurationForm().getTerminalType());

      // initializing the shell
      shellChannel.connect(1000);

      sshContact.setShellChannel(shellChannel);

      sshContact.sendLine("export PS1=");
    } catch (JSchException ex) {
      sshContact.setSSHSession(null);
      throw new IOException("Unable to create shell channel to remote" + " server");
    }
  }
Beispiel #22
0
  public void highlightTypeAdded(Message.HighlightTypeMsg m) {
    if (EditorServer_Debug) System.err.println("EditorServer: highlightTypeAdded.");

    highlights.addHighlightType(m.getId(), m.getName(), m.getColor());

    try {
      textChannel.sendToOthers(client, new Data(m));
    } catch (Exception e) {
      System.err.println("EditorServer: highlightTypeAdded: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #23
0
  public void highlightEdited(Message.HighlightEditMsg m) {
    if (EditorServer_Debug) System.err.println("EditorServer: highlightEdited.");

    highlights.editHighlight(
        m.getId(), m.getStartPar(), m.getStartOffset(), m.getEndPar(), m.getEndOffset());

    try {
      textChannel.sendToOthers(client, new Data(m));
    } catch (Exception e) {
      System.err.println("EditorServer: highlightEdited: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #24
0
  public void lockRequested(Message.LockRequestMsg m) {
    if (EditorServer_Debug) System.err.println("EditorServer -> lockRequested.");

    /*
      java.util.Timer t = new java.util.Timer() ;
      t.schedule(new TimerTask() {
      public void run() {
      client.lockDenied(id) ;
      }
      }, 3000) ;
    */

    if (lockManager.lockRequested(m.getStartPar(), m.getEndPar(), m.getClientId())) {

      if (EditorServer_Debug) System.out.println("Lock Granted");

      Message.LockGrantMsg reply =
          new Message.LockGrantMsg(
              m.getClientId(), m.getStartPar(), m.getEndPar(), m.getIdNumber());
      try {
        textChannel.sendToOthers(client, new Data(reply));
      } catch (Exception e) {
        System.err.println("EditorServer: lockRequested: error sending lock granted");
        if (EditorServer_Debug) e.printStackTrace();
      }
    } else {
      if (EditorServer_Debug) System.out.println("Lock Denied");
      // send lock denied to sender

      Message.LockDenyMsg reply = new Message.LockDenyMsg(m.getClientId(), m.getIdNumber());
      try {
        textChannel.sendToOthers(client, new Data(reply));
      } catch (Exception e) {
        System.err.println("EditorServer: lockRequested: error sending lock denied");
        if (EditorServer_Debug) e.printStackTrace();
      }
    }
  }
Beispiel #25
0
  public void clientLeft(Message.ClientLeaveMsg m) {
    System.out.println("EditorServer: clientLeft");

    EditorClient ec = getEditorClient(m.getClientId());
    ec.setPresent(false);
    clientsPanel.updateClientList();

    try {
      clientChannel.sendToOthers(client, new Data(m));
    } catch (Exception e) {
      System.err.println("EditorServer: clientLeft: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #26
0
  public void disconnect() {
    if (connected) {
      if (channel != null) {
        channel.disconnect();
        channel = null;
      }

      if (session != null) {
        session.disconnect();
        session = null;
      }

      connected = false;
    }
  }
 /**
  * Sets the given UpHandler as the UpHandler for the channel, or, if the channel already has a
  * Muxer installed as it's UpHandler, sets the given handler as the Muxer's {@link
  * Muxer#setDefaultHandler(Object) default handler}. If the relevant handler is already installed,
  * the <code>canReplace</code> controls whether this method replaces it (after logging a WARN) or
  * simply leaves <code>handler</code> uninstalled.
  *
  * <p>Passing <code>false</code> as the <code>canReplace</code> value allows callers to use this
  * method to install defaults without concern about inadvertently overriding
  *
  * @param handler the UpHandler to install
  * @param canReplace <code>true</code> if an existing Channel upHandler or Muxer default upHandler
  *     can be replaced; <code>false</code> if this method shouldn't install
  */
 protected void installUpHandler(UpHandler handler, boolean canReplace) {
   UpHandler existing = channel.getUpHandler();
   if (existing == null) {
     channel.setUpHandler(handler);
   } else if (existing instanceof Muxer<?>) {
     @SuppressWarnings("unchecked")
     Muxer<UpHandler> mux = (Muxer<UpHandler>) existing;
     if (mux.getDefaultHandler() == null) {
       mux.setDefaultHandler(handler);
     } else if (canReplace) {
       log.warn(
           "Channel Muxer already has a default up handler installed ("
               + mux.getDefaultHandler()
               + ") but now it is being overridden");
       mux.setDefaultHandler(handler);
     }
   } else if (canReplace) {
     log.warn(
         "Channel already has an up handler installed ("
             + existing
             + ") but now it is being overridden");
     channel.setUpHandler(handler);
   }
 }
Beispiel #28
0
  public void gestureLine(Message.GestureLineMsg m) {
    if (EditorServer_Debug)
      System.err.println("EditorServer: gestureLine." + String.valueOf(m.getId()));

    try {
      clientChannel.sendToOthers(client, new Data(m));
      EditorClient c = getEditorClient(m.getClientId());
      long par = getParIdForGesture(m.getPar(), m.getAY());
      c.addGestureAction(System.currentTimeMillis(), m.getId(), par, m.getAX(), m.getAY(), this);
      c.addGestureAction(System.currentTimeMillis(), m.getId(), par, m.getBX(), m.getBY(), this);
      clientsPanel.updateActionTableFor(c);
    } catch (Exception e) {
      System.err.println("EditorServer: gestureLine: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #29
0
  public void clientAppeared() {
    if (EditorServer_Debug) System.out.println("EditorServer: clientAppeared.");

    // send client list to everybody
    try {
      Iterator i = clients.iterator();

      while (i.hasNext()) {
        EditorClient ec = (EditorClient) i.next();
        if (ec.isPresent()) clientChannel.sendToOthers(client, new Data(ec.getMessage()));
      }

    } catch (Exception e) {
      System.err.println("EditorServer: clientAppeared: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }
Beispiel #30
0
  public void sendHighlightTypes() {
    //      send highlightTypes to everybody
    try {
      Iterator i = highlights.getHighlightTypes().iterator();

      while (i.hasNext()) {
        HighlightType type = (HighlightType) i.next();

        if (EditorServer_Debug)
          System.out.println("EditorServer: sendHighlightTypes. " + String.valueOf(type.getId()));

        Message.HighlightTypeMsg msg =
            new Message.HighlightTypeMsg(-1, type.getId(), type.getName(), type.getColor());
        textChannel.sendToOthers(client, new Data(msg));
      }
    } catch (Exception e) {
      System.err.println("EditorServer: sendHighlightTypes: error sending msg");
      if (EditorServer_Debug) e.printStackTrace();
    }
  }