Esempio n. 1
0
  final <T extends ServerResponse> T doPost(CommandArguments args, Class<T> clazz, String url)
      throws FlickrException {
    try {
      OAuthRequest request = new OAuthRequest(Verb.POST, url);

      // check for proxy, use if available
      if (proxy != null) {
        request.setProxy(proxy);
      }

      for (Map.Entry<String, Object> param : args.getParameters().entrySet()) {
        if (param.getValue() instanceof String) {
          request.addQuerystringParameter(param.getKey(), (String) param.getValue());
        }
      }

      oauth.signRequest(request);

      MultipartEntity multipart = args.getBody(request.getOauthParameters());
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      multipart.writeTo(baos);

      request.addPayload(baos.toByteArray());
      request.addHeader("Content-type", multipart.getContentType().getValue());

      Response response = request.send();
      String body = response.getBody();

      return parseBody(args, clazz, body);

    } catch (IOException ex) {
      throw new UnsupportedOperationException("Error preparing multipart request", ex);
    }
  }
Esempio n. 2
0
  private <T extends ServerResponse> T parseBody(CommandArguments args, Class<T> clazz, String body)
      throws FlickrException {
    try {
      if (Flickr.debug) {
        try {
          System.out.println("Server response for method " + args.getMethod() + "\n" + body);
        } catch (Exception ignored) {
        }
      }

      T instance = clazz.newInstance();
      instance.read(body, args.getMethod());

      return instance;

    } catch (FlickrException ex) {
      throw ex;
    } catch (IllegalStateException ex) {
      throw new FlickrException("Server request error", ex);
    } catch (InstantiationException ex) {
      throw new FlickrException("Server request error", ex);
    } catch (IllegalAccessException ex) {
      throw new FlickrException("Server request error", ex);
    }
  }
Esempio n. 3
0
  /**
   * Perform the 'alias' command.
   *
   * @param session JSwat session on which to operate.
   * @param args Tokenized string of command arguments.
   * @param out Output to write messages to.
   */
  public void perform(Session session, CommandArguments args, Log out) {
    CommandManager cmdman = (CommandManager) session.getManager(CommandManager.class);
    if (args.hasMoreTokens()) {
      String aliasName = args.nextToken();
      if (args.hasMoreTokens()) {
        // Grab rest of string as alias value.
        // Be sure to preserve the quotes and escapes.
        args.returnAsIs(true);
        String alias = args.rest().trim();
        if (alias.charAt(0) == '"' && alias.charAt(alias.length() - 1) == '"') {
          // Must remove the enclosing quotes because the
          // command parser doesn't handle that.
          alias = alias.substring(1, alias.length() - 1);
        }

        // Add the command alias to the list.
        cmdman.createAlias(aliasName, alias);
        out.writeln(Bundle.getString("alias.defined") + ' ' + aliasName);
      } else {
        // One argument, show the alias definition.
        String alias = cmdman.getAlias(aliasName);
        if (alias == null) {
          throw new CommandException(Bundle.getString("alias.undefined") + ' ' + aliasName);
        } else {
          out.writeln("alias " + aliasName + ' ' + alias);
        }
      }
    } else {
      // No arguments, show the defined aliases.
      cmdman.listAliases();
    }
  } // perform
Esempio n. 4
0
  /**
   * Executes the command in the executor it is currently set to.
   *
   * @param source that sent the command
   * @param args command arguments
   * @throws CommandException if the command executor is null or if {@link
   *     Executor#execute(CommandSource, Command, CommandArguments)} throws a CommandException.
   */
  public void process(CommandSource source, CommandArguments args) throws CommandException {

    // check permissions
    if (permission != null && !source.hasPermission(permission)) {
      throw new CommandException("You do not have permission to execute this command.");
    }

    args.flags().registerFlags(this.flags);

    // no child found, try to execute
    for (CommandFilter filter : filters) {
      filter.validate(this, source, args);
    }

    // execute a child if applicable
    if (children.size() > 0) {
      Command child = getChild(args.popString("child"), false);
      if (child != null) {
        if (executor != null) {
          executor.execute(source, this, args);
        }
        child.process(source, args);
      } else {
        throw args.failure("child", "Unknown child!", false);
      }
    } else {
      if (executor == null) {
        throw new CommandException("CommandDescription exists but has no set executor.");
      }
      args.flags().parse();
      executor.execute(source, this, args);
    }
  }
Esempio n. 5
0
  /**
   * Perform the 'history' command.
   *
   * @param session JSwat session on which to operate.
   * @param args Tokenized string of command arguments.
   * @param out Output to write messages to.
   */
  public void perform(Session session, CommandArguments args, Log out) {
    CommandManager cmdman = (CommandManager) session.getManager(CommandManager.class);

    if (args.hasMoreTokens()) {
      String arg = args.nextToken();
      try {
        int size = Integer.parseInt(arg);
        cmdman.setHistorySize(size);
        out.writeln(Bundle.getString("history.sizeSet"));
      } catch (NumberFormatException nfe) {
        throw new CommandException(Bundle.getString("history.invalidSize"));
      } catch (IllegalArgumentException iae) {
        throw new CommandException(Bundle.getString("history.invalidRange"));
      }
    } else {
      cmdman.displayHistory();
    }
  } // perform
Esempio n. 6
0
  final <T extends ServerResponse> T doGet(CommandArguments args, Class<T> clazz)
      throws FlickrException {
    OAuthRequest request = new OAuthRequest(Verb.GET, URL_PREFIX);

    // check for proxy, use if available
    if (proxy != null) {
      request.setProxy(proxy);
    }

    for (Map.Entry<String, Object> param : args.getParameters().entrySet()) {
      request.addQuerystringParameter(param.getKey(), String.valueOf(param.getValue()));
    }

    oauth.signRequest(request);
    Response response = request.send();
    String body = response.getBody();

    return parseBody(args, clazz, body);
  }
  public boolean prepareDelegate(
      Object subject, CommandSession session, List<Object> params, CommandArguments args)
      throws Exception {
    args.subject = subject;
    // Introspect
    for (Class type = subject.getClass(); type != null; type = type.getSuperclass()) {
      for (Field field : type.getDeclaredFields()) {
        Option option = field.getAnnotation(Option.class);
        if (option != null) {
          args.options.put(option, field);
        }
        Argument argument = field.getAnnotation(Argument.class);
        if (argument != null) {
          if (Argument.DEFAULT.equals(argument.name())) {
            final Argument delegate = argument;
            final String name = field.getName();
            argument =
                new Argument() {
                  public String name() {
                    return name;
                  }

                  public String description() {
                    return delegate.description();
                  }

                  public boolean required() {
                    return delegate.required();
                  }

                  public int index() {
                    return delegate.index();
                  }

                  public boolean multiValued() {
                    return delegate.multiValued();
                  }

                  public String valueToShowInHelp() {
                    return delegate.valueToShowInHelp();
                  }

                  public Class<? extends Annotation> annotationType() {
                    return delegate.annotationType();
                  }
                };
          }
          args.arguments.put(argument, field);
          int index = argument.index();
          while (args.orderedArguments.size() <= index) {
            args.orderedArguments.add(null);
          }
          if (args.orderedArguments.get(index) != null) {
            throw new IllegalArgumentException("Duplicate argument index: " + index);
          }
          args.orderedArguments.set(index, argument);
        }
      }
    }
    // Check indexes are correct
    for (int i = 0; i < args.orderedArguments.size(); i++) {
      if (args.orderedArguments.get(i) == null) {
        throw new IllegalArgumentException("Missing argument for index: " + i);
      }
    }
    // Populate
    Map<Option, Object> optionValues =
        new TreeMap<Option, Object>(CommandArguments.OPTION_COMPARATOR);
    Map<Argument, Object> argumentValues = new HashMap<Argument, Object>();
    boolean processOptions = true;
    int argIndex = 0;
    for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
      Object param = it.next();
      // Check for help
      if (HELP.name().equals(param) || Arrays.asList(HELP.aliases()).contains(param)) {
        printUsageDelegate(session, subject, args.options, args.arguments, System.out);
        return false;
      }
      if (processOptions && param instanceof String && ((String) param).startsWith("-")) {
        boolean isKeyValuePair = ((String) param).indexOf('=') != -1;
        String name;
        Object value = null;
        if (isKeyValuePair) {
          name = ((String) param).substring(0, ((String) param).indexOf('='));
          value = ((String) param).substring(((String) param).indexOf('=') + 1);
        } else {
          name = (String) param;
        }
        Option option = null;
        for (Option opt : args.options.keySet()) {
          if (name.equals(opt.name()) || Arrays.asList(opt.aliases()).contains(name)) {
            option = opt;
            break;
          }
        }
        if (option == null) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(" undefined option ")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(param)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Undefined option: " + param);
        }
        Field field = args.options.get(option);
        if (value == null
            && (field.getType() == boolean.class || field.getType() == Boolean.class)) {
          value = Boolean.TRUE;
        }
        if (value == null && it.hasNext()) {
          value = it.next();
        }
        if (value == null) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(" missing value for option ")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(param)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Missing value for option: " + param);
        }
        if (option.multiValued()) {
          List<Object> l = (List<Object>) optionValues.get(option);
          if (l == null) {
            l = new ArrayList<Object>();
            optionValues.put(option, l);
          }
          l.add(value);
        } else {
          optionValues.put(option, value);
        }
      } else {
        processOptions = false;
        if (argIndex >= args.orderedArguments.size()) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(": too many arguments specified")
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Too many arguments specified");
        }
        Argument argument = args.orderedArguments.get(argIndex);
        if (!argument.multiValued()) {
          argIndex++;
        }
        if (argument.multiValued()) {
          List<Object> l = (List<Object>) argumentValues.get(argument);
          if (l == null) {
            l = new ArrayList<Object>();
            argumentValues.put(argument, l);
          }
          l.add(param);
        } else {
          argumentValues.put(argument, param);
        }
      }
    }
    // Check required arguments / options
    for (Option option : args.options.keySet()) {
      if (option.required() && optionValues.get(option) == null) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": option ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(option.name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" is required")
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Option " + option.name() + " is required");
      }
    }
    for (Argument argument : args.arguments.keySet()) {
      if (argument.required() && argumentValues.get(argument) == null) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": argument ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(argument.name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" is required")
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Argument " + argument.name() + " is required");
      }
    }
    // Convert and inject values
    for (Map.Entry<Option, Object> entry : optionValues.entrySet()) {
      Field field = args.options.get(entry.getKey());
      Object value;
      try {
        value = convert(subject, entry.getValue(), field.getGenericType());
      } catch (Exception e) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": unable to convert option ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(entry.getKey().name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" with value '")
                .a(entry.getValue())
                .a("' to type ")
                .a(new GenericType(field.getGenericType()).toString())
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Unable to convert option "
                + entry.getKey().name()
                + " with value '"
                + entry.getValue()
                + "' to type "
                + new GenericType(field.getGenericType()).toString(),
            e);
      }
      field.setAccessible(true);
      field.set(subject, value);
    }
    for (Map.Entry<Argument, Object> entry : argumentValues.entrySet()) {
      Field field = args.arguments.get(entry.getKey());
      Object value;
      try {
        value = convert(subject, entry.getValue(), field.getGenericType());
      } catch (Exception e) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": unable to convert argument ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(entry.getKey().name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" with value '")
                .a(entry.getValue())
                .a("' to type ")
                .a(new GenericType(field.getGenericType()).toString())
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Unable to convert argument "
                + entry.getKey().name()
                + " with value '"
                + entry.getValue()
                + "' to type "
                + new GenericType(field.getGenericType()).toString(),
            e);
      }
      field.setAccessible(true);
      field.set(subject, value);
    }
    return true;
  }
Esempio n. 8
0
  /**
   * Perform the 'capture' command.
   *
   * @param session debugging session on which to operate.
   * @param args Tokenized string of command arguments.
   * @param out Output to write messages to.
   */
  public void perform(Session session, CommandArguments args, Log out) {
    // Get the current capture settings.
    boolean captureStdout = Capture.isOutputEnabled(session);
    boolean captureFile = Capture.isFileEnabled(session);
    String filename = Capture.getFilename(session);

    if (args.hasMoreTokens()) {
      // Modify the capture settings.

      while (args.hasMoreTokens()) {
        String token = args.nextToken();
        boolean enable = false;
        boolean disable = false;
        if (token.startsWith("+")) {
          enable = true;
          token = token.substring(1);
        } else if (token.startsWith("-")) {
          disable = true;
          token = token.substring(1);
        }
        if (token.equals("stdout")) {
          captureStdout = enable || !disable && !captureStdout;
        } else if (token.equals("file")) {
          captureFile = enable || !disable && !captureFile;
          if (captureFile) {
            if (args.hasMoreTokens()) {
              filename = args.nextToken();
            } else {
              throw new MissingArgumentsException(Bundle.getString("capture.missingFilename"));
            }
          }
        } else {
          throw new CommandException(Bundle.getString("capture.unknownType") + ' ' + token);
        }
      }

      Capture.setOutputEnabled(captureStdout, session);

      File file = null;
      if (captureFile) {
        // Create the file and check that it exists.
        file = new File(filename);
        if (file.exists() && !file.canWrite()) {
          throw new CommandException(Bundle.getString("capture.readOnlyFile"));
        }
      }

      // Enable or disable the file capture.
      try {
        Capture.setFileEnabled(captureFile, file, session);
      } catch (FileNotFoundException fnfe) {
        throw new CommandException(Bundle.getString("capture.fileNotFound"));
      } catch (IOException ioe) {
        throw new CommandException(ioe);
      }
    } else {
      // Display the capture settings.
      StringBuffer buf = new StringBuffer();
      if (captureStdout) {
        buf.append(Bundle.getString("capture.stdout"));
        buf.append('\n');
      }
      if (captureFile) {
        buf.append(Bundle.getString("capture.file") + ' ' + filename);
        buf.append('\n');
      }
      if (buf.length() > 0) {
        out.write(buf.toString());
      } else {
        out.writeln(Bundle.getString("capture.none"));
      }
    }
  } // perform
Esempio n. 9
0
  /**
   * Perform the 'hotswap' command.
   *
   * @param session JSwat session on which to operate.
   * @param args Tokenized string of command arguments.
   * @param out Output to write messages to.
   */
  public void perform(Session session, CommandArguments args, Log out) {
    if (!session.isActive()) {
      throw new CommandException(Bundle.getString("noActiveSession"));
    }

    if (!args.hasMoreTokens()) {
      throw new MissingArgumentsException();
    }

    // Name of class is required; name of .class file is optional.
    String cname = args.nextToken();
    String cfile = null;
    if (args.hasMoreTokens()) {
      cfile = args.nextToken();
    }

    // Find the ReferenceType for this class.
    VirtualMachine vm = session.getConnection().getVM();
    List classes = vm.classesByName(cname);
    if (classes.size() == 0) {
      throw new CommandException(Bundle.getString("hotswap.noSuchClass"));
    }
    ReferenceType clazz = (ReferenceType) classes.get(0);

    // Did the user give us a .class file?
    InputStream is = null;
    if (cfile == null) {
      // Try to find the .class file.
      PathManager pathman = (PathManager) session.getManager(PathManager.class);
      SourceSource src = pathman.mapClass(clazz);
      if (src == null) {
        throw new CommandException(Bundle.getString("hotswap.fileNotFound"));
      }
      is = src.getInputStream();
    } else {
      // A filename was given, just open it.
      try {
        is = new FileInputStream(cfile);
      } catch (FileNotFoundException fnfe) {
        throw new CommandException(Bundle.getString("hotswap.fileNotFound"));
      }
    }

    // Do the actual hotswap operation.
    try {
      Classes.hotswap(clazz, is, vm);
      out.writeln(Bundle.getString("hotswap.success"));
    } catch (UnsupportedOperationException uoe) {
      if (!vm.canRedefineClasses()) {
        throw new CommandException(Bundle.getString("hotswap.noHotSwap"));
      } else if (!vm.canAddMethod()) {
        throw new CommandException(Bundle.getString("hotswap.noAddMethod"));
      } else if (!vm.canUnrestrictedlyRedefineClasses()) {
        throw new CommandException(Bundle.getString("hotswap.noUnrestricted"));
      } else {
        throw new CommandException(Bundle.getString("hotswap.unsupported"));
      }
    } catch (IOException ioe) {
      throw new CommandException(Bundle.getString("hotswap.errorReadingFile") + ' ' + ioe);
    } catch (NoClassDefFoundError ncdfe) {
      throw new CommandException(Bundle.getString("hotswap.wrongClass"));
    } catch (VerifyError ve) {
      throw new CommandException(Bundle.getString("hotswap.verifyError") + ' ' + ve);
    } catch (UnsupportedClassVersionError ucve) {
      throw new CommandException(Bundle.getString("hotswap.versionError") + ' ' + ucve);
    } catch (ClassFormatError cfe) {
      throw new CommandException(Bundle.getString("hotswap.formatError") + ' ' + cfe);
    } catch (ClassCircularityError cce) {
      throw new CommandException(Bundle.getString("hotswap.circularity") + ' ' + cce);
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException ioe) {
        }
      }
    }
  } // perform