Exemplo n.º 1
0
 private void configureListeners(Injector injector, QueueConfig... queueConfigs)
     throws JMSException, IllegalAccessException, InstantiationException {
   for (QueueConfig queueConfig : queueConfigs) {
     Queue queue = (Queue) jmsServer.lookup("/queue/" + queueConfig.getName());
     for (int i = 0; i < queueConfig.getListenerCount(); i++) {
       CommandListener listener =
           (CommandListener) queueConfig.getCommandListenerClass().newInstance();
       listener.setInjector(injector);
       Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
       session.createConsumer(queue).setMessageListener(listener);
     }
   }
   consumerConnection.start();
 }
Exemplo n.º 2
0
  public static void main(String[] argv) throws Exception {
    Options options = new Options();
    options.addOption("js", false, "Create f5less.js");
    options.addOption("p", "port", true, "ws:reload websocket server port");
    options.addOption("h", "host", true, "ws:reload websocket server host");
    options.addOption("d", "debounce", true, "debouncing for commands");

    CommandLine cmdLine = new PosixParser().parse(options, argv);
    String[] args = cmdLine.getArgs();

    if (cmdLine.hasOption("js")) {
      Files.copy(
          TheBuilder.class.getClassLoader().getResourceAsStream("f5less.js"),
          Paths.get("./f5less.js"),
          StandardCopyOption.REPLACE_EXISTING);
      System.out.println(
          "\n  f5less.js created...\n  put the following\n"
              + "     <script type=\"text/javascript\" src=\"f5less.js\"></script>\n"
              + "     <script type=\"text/javascript\">f5less.connect()</script>\n"
              + "  in the page for which you want automatic reloading (assuming 'f5less.js' is in the same directory)\n");
    }

    if (args.length < 2) {
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("f5less [options] path1 cmd1 path2 cmd2 ...", options);
      System.exit(-1);
    }

    final List<String> reloadPaths = new LinkedList<String>();
    final int commandsDebounce = Integer.parseInt(cmdLine.getOptionValue("d", "100"));

    for (int i = 0; i < args.length / 2; i++) {
      final String path = args[i * 2];
      final String rawCmd = args[i * 2 + 1];

      if (rawCmd.equals("ws:reload")) reloadPaths.add(path);
      else Watcher.register(path, new CommandListener(path, rawCmd, commandsDebounce));
    }

    ReloadServer reloadServer = null;
    if (!reloadPaths.isEmpty()) {
      reloadServer =
          new ReloadServer(
              cmdLine.getOptionValue("h", "localhost"),
              Integer.parseInt(cmdLine.getOptionValue("p", "9999")),
              commandsDebounce + 50);
      reloadServer.monitor(reloadPaths);
    }

    System.out.println("Press enter to exit...");
    System.in.read();

    if (reloadServer != null) reloadServer.stop();

    Watcher.stop();
    CommandListener.stop();

    System.out.println("Bye bye");
  }
Exemplo n.º 3
0
 /**
  * Método que trata las acciones a ejecutar al producirse un evento
  *
  * @param c Es el evento que se ha producido (o botón que se ha pulsado)
  * @param d Es la pantalla en la que se ha producido el evento
  */
 public void commandAction(Command c, Displayable d) {
   if (c.equals(this.SELECT_COMMAND)) {
     cliente.conecta(getSelectedIndex());
   } else if (c.equals(volver)) {
     padre.commandAction(volver, this);
   } else if (c.equals(buscar)) {
     cliente.buscaDisp();
   }
 }
Exemplo n.º 4
0
 public void undo() {
   try {
     MethodInvocationManager.invokeMethod( // frame,
         parentObject, addMethod, addParams);
     listener.commandActionPerformed();
   } catch (Exception e) {
     System.out.println("Could not undo: " + subtractMethod + " " + e);
   }
 }
  public void register(CommandListener listener) {

    for (Method method : listener.getClass().getMethods()) {
      if (!method.isAnnotationPresent(Command.class)) {
        continue;
      }

      Command cmdAnnotation = method.getAnnotation(Command.class);

      Map<CommandSyntax, CommandBinding> commandListeners = listeners.get(cmdAnnotation.name());
      if (commandListeners == null) {
        commandListeners = new HashMap<CommandSyntax, CommandBinding>();
        listeners.put(cmdAnnotation.name(), commandListeners);
      }

      this.registerCommandHelp(cmdAnnotation);

      commandListeners.put(
          new CommandSyntax(cmdAnnotation.syntax()), new CommandBinding(listener, method));
    }
  }
Exemplo n.º 6
0
  public void run() {
    try {

      // Note, either envp or workingDirectory or both may be null; thats
      // OK.
      Process process =
          Runtime.getRuntime()
              .exec(getCommandArray(), getEnvironmentParameters(), getWorkingDirectory());

      Thread stdoutConsumer =
          new ConsumerThread(process.getInputStream()) {
            public void consume(String line) {
              _commandListener.eatStdOut(line);
            }
          };
      Thread stderrConsumer =
          new ConsumerThread(process.getErrorStream()) {
            public void consume(String line) {
              _commandListener.eatStdErr(line);
            }
          };

      stdoutConsumer.start();
      stderrConsumer.start();

      InputStream stdIn = getStdIn();

      if (stdIn != null) {
        try {

          OutputStream processOS = process.getOutputStream();
          byte[] buffer = new byte[1000];

          while (true) {
            int bytes = stdIn.read(buffer, 0, buffer.length);
            if (bytes == -1) {
              break; // EOF
            }
            processOS.write(buffer, 0, bytes);
          }

          stdIn.close();
          processOS.close();

        } catch (Exception e) {
          _logger.info("Exception - possibly irrelevant : " + e);
        }
      }

      int exitStatus;
      try {
        exitStatus = process.waitFor();

      } catch (Exception e) {
        _logger.error("process waitFor failed : " + e);
        process.destroy();
        throw e;
      }

      /*
       * // There is the possibility that the consumer threads have not
       * quite // caught up yet - so they may still be running, even
       * though the // process has finished. // This code works, but takes
       * AGES to run, so I've disabled it. while( stderrConsumer.isAlive()
       * ) { stderrConsumer.join(); } while( stdoutConsumer.isAlive() ) {
       * stdoutConsumer.join(); }
       */

      if (_commandListener != null) {
        _commandListener.finished(exitStatus);
      }

    } catch (Exception e) {

      _logger.error("Command failed : " + e);
      e.printStackTrace();

      if (_commandListener != null) {
        _commandListener.eatStdErr(e.toString());
        _commandListener.finished(-999);
      }
    }
  }
Exemplo n.º 7
0
 public void redo() {
   execute();
   listener.commandActionPerformed();
 }
Exemplo n.º 8
0
  /**
   * Register your CommandListener. This will make all annotated commands available to CanaryMod and
   * the help system. Sub Command relations can only be sorted out after availability. That means if
   * you try to register a command that is a sub-command of something that is not registered yet, it
   * will fail. So make sure you add commands in the correct order.
   *
   * @param listener the {@link CommandListener}
   * @param owner the {@link CommandOwner}
   * @param translator the {@link LocaleHelper} instance used in Translations
   * @param force {@code true} to override existing commands; {@code false} for not
   * @throws CommandDependencyException
   */
  public void registerCommands(
      final CommandListener listener, CommandOwner owner, LocaleHelper translator, boolean force)
      throws CommandDependencyException {
    Method[] methods = listener.getClass().getDeclaredMethods();
    ArrayList<CanaryCommand> newCommands = new ArrayList<CanaryCommand>();

    for (final Method method : methods) {
      if (!method.isAnnotationPresent(Command.class)) {
        continue;
      }
      Class<?>[] params = method.getParameterTypes();
      if (params.length != 2) {
        log.warn(
            "You have a Command method with invalid number of arguments! - " + method.getName());
        continue;
      }
      if (!(MessageReceiver.class.isAssignableFrom(params[0])
          && String[].class.isAssignableFrom(params[1]))) {
        log.warn("You have a Command method with invalid argument types! - " + method.getName());
        continue;
      }

      Command meta = method.getAnnotation(Command.class);
      TabCompleteDispatch tabComplete = null;

      darkdiplomatIsAWizard:
      // If tab complete method fails, it shouldn't kill the command itself
      if (!meta.tabCompleteMethod().isEmpty()) {
        final Method tabCompMeth;
        try {
          tabCompMeth =
              listener
                  .getClass()
                  .getMethod(meta.tabCompleteMethod(), MessageReceiver.class, String[].class);
        } catch (NoSuchMethodException e) {
          log.warn(
              String.format(
                  "[%s/%s/%s] TabComplete initialization failure: Unable to locate specified Method",
                  owner.getName(), listener.getClass().getSimpleName(), meta.tabCompleteMethod()));
          break darkdiplomatIsAWizard;
        }

        if (!tabCompMeth.isAnnotationPresent(TabComplete.class)) {
          log.warn(
              String.format(
                  "[%s/%s/%s] TabComplete initialization failure: TabComplete annotation missing",
                  owner.getName(), listener.getClass().getSimpleName(), meta.tabCompleteMethod()));
          break darkdiplomatIsAWizard;
        }

        if (!List.class.isAssignableFrom(tabCompMeth.getReturnType())) {
          log.warn(
              String.format(
                  "[%s/%s/%s] AutoComplete initialization failure: Return type was not of List",
                  owner.getName(), listener.getClass().getSimpleName(), meta.tabCompleteMethod()));
          break darkdiplomatIsAWizard;
        }

        tabComplete =
            new TabCompleteDispatch() {
              @Override
              public List<String> complete(MessageReceiver msgrec, String[] args)
                  throws TabCompleteException {
                try {
                  return (List<String>) tabCompMeth.invoke(listener, msgrec, args);
                } catch (Exception ex) {
                  throw new TabCompleteException("AutoComplete failed to execute...", ex);
                }
              }
            };
      }

      CanaryCommand command =
          new CanaryCommand(meta, owner, translator, tabComplete) {
            @Override
            protected void execute(MessageReceiver caller, String[] parameters) {
              try {
                method.invoke(listener, new Object[] {caller, parameters});
              } catch (Exception ex) {
                log.error("Could not execute command...", ex.getCause());
              }
            }
          };

      newCommands.add(command);
    }
    // Sort load order so dependencies can be resolved properly
    Collections.sort(newCommands);

    // Take care of parenting
    for (CanaryCommand cmd : newCommands) {
      if (cmd.meta.parent().isEmpty()) {
        continue;
      }
      String[] cmdp = cmd.meta.parent().split("\\.");
      boolean depMissing = true;
      // Check for local dependencies
      for (CanaryCommand parent : newCommands) {
        CanaryCommand tmp = null;
        for (int i = 0; i < cmdp.length; i++) {
          if (i == 0) {
            for (String palias : parent.meta.aliases()) {
              if (palias.equals(cmdp[i])) {
                tmp = parent;
              }
            }
          } else {
            // First element wasn't found. Get out.
            if (tmp == null) {
              break;
            }
            if (tmp.hasSubCommand(cmdp[i])) {
              tmp = tmp.getSubCommand(cmdp[i]);
            } else {
              tmp = null;
              break;
            }
          }
        }
        if (tmp != null) {
          cmd.setParent(tmp);
          depMissing = false;
        }
      }

      // Check for remote dependencies
      if (depMissing) { // checking if it had found a local first
        CanaryCommand temp = null;
        for (int i = 0; i < cmdp.length; i++) {
          if (i == 0) {
            temp = commands.get(cmdp[0]);
          } else {
            if (temp == null) {
              break;
            }
            if (temp.hasSubCommand(cmdp[i])) {
              temp = temp.getSubCommand(cmdp[i]);
            } else {
              temp = null;
              break;
            }
          }
        }
        if (temp != null) {
          cmd.setParent(temp);
          depMissing = false;
        }
      }

      // Throw Error if we did not find the Dependency
      if (depMissing) {
        throw new CommandDependencyException(
            cmd.meta.aliases()[0]
                + " has an unsatisfied dependency, "
                + "( "
                + cmd.meta.parent()
                + " )"
                + "please adjust registration order of your listeners or fix your plugins dependencies");
      }
    }
    // KDone. Lets update commands list
    boolean hasDuplicate = false;
    StringBuilder dupes = new StringBuilder();
    for (CanaryCommand cmd : newCommands) {
      for (String alias : cmd.meta.aliases()) {
        boolean currentIsDupe = false;
        if (commands.containsKey(alias.toLowerCase()) && cmd.meta.parent().isEmpty() && !force) {
          hasDuplicate = true;
          currentIsDupe = true;
          dupes.append(alias).append(" ");
        }
        if (!currentIsDupe || force) {
          if (cmd.meta.parent().isEmpty()) { // Only add root commands
            commands.put(alias.toLowerCase(), cmd);
          }
          if (!cmd.meta.helpLookup().isEmpty() && !Canary.help().hasHelp(cmd.meta.helpLookup())) {
            Canary.help().registerCommand(owner, cmd, cmd.meta.helpLookup());
          } else {
            Canary.help().registerCommand(owner, cmd);
          }
        }
      }
    }
    if (hasDuplicate && !force) {
      throw new DuplicateCommandException(dupes.toString());
    }
  }
Exemplo n.º 9
0
  /* Receive a packet (will be decrypted with stream cipher). */
  public void receivePacket() throws DespotifyException {
    byte[] header = new byte[3];
    PacketType packetType;
    int payloadLength, headerLength = 3, macLength = 4;

    /* Read header. */
    int received =
        this.receive(header, headerLength, log.isDebugEnabled() ? "packet header" : null);
    if (received != headerLength) {
      // todo reconnect?
      throw new RecievedInvalidHeaderException(
          "Failed to read header. Expected "
              + headerLength
              + " bytes, received "
              + received
              + ". todo try to reconnect once?");
    }

    /* Set IV. */
    this.session.shannonRecv.nonce(IntegerUtilities.toBytes(this.session.keyRecvIv));

    /* Decrypt header. */
    this.session.shannonRecv.decrypt(header);

    /* Get command and payload length from header. */
    ByteBuffer headerBuffer = ByteBuffer.wrap(header);

    byte commandByte = headerBuffer.get();
    packetType = PacketType.valueOf(commandByte & 0xff);

    if (packetType == null) {
      log.info(
          "Unknown command in received packet: "
              + packetType
              + " 0x"
              + Hex.toHex(new byte[] {commandByte}));
      // todo should we just ignore these?
    }

    payloadLength = headerBuffer.getShort() & 0xffff;

    /* Allocate buffer. Account for MAC. */
    byte[] bytes = new byte[payloadLength + macLength];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);

    /* Limit buffer to payload length, so we can read the payload. */
    buffer.limit(payloadLength);

    try {
      for (int n = payloadLength, r; n > 0 && (r = this.channel.read(buffer)) > 0; n -= r) ;
    } catch (IOException e) {
      throw new DespotifyException("Failed to read payload: " + e.getMessage());
    }

    /* Extend it again to payload and mac length. */
    buffer.limit(payloadLength + macLength);

    try {
      for (int n = macLength, r; n > 0 && (r = this.channel.read(buffer)) > 0; n -= r) ;
    } catch (IOException e) {
      throw new DespotifyException("Failed to read MAC: " + e.getMessage());
    }

    /* Decrypt payload. */
    this.session.shannonRecv.decrypt(bytes);

    /* Get payload bytes from buffer (throw away MAC). */
    byte[] payload = new byte[payloadLength];

    buffer.flip();
    buffer.get(payload);

    /* Increment IV. */
    this.session.keyRecvIv++;

    if (log.isInfoEnabled()) {
      log.info(
          "received "
              + packetType
              + "-command packet payload, "
              + payloadLength
              + " bytes:\n"
              + Hex.log(payload, log));
    }

    /* Fire events. */
    for (CommandListener listener : this.listeners) {
      listener.commandReceived(packetType, payload);
    }
  }