Beispiel #1
0
  /**
   * Register a regular command argument/parameter for this command.
   *
   * <p>When adding multiple arguments the order you add them in determines the indexing of the
   * argument!
   *
   * @param name The argument name/key used to identify the argument. This name must be used with
   *     the {@link CmdData} result to get the argument value.
   * @param requirement The requirement for this argument. (See {@link ArgRequirement} for more
   *     info)
   * @param option The {@link SingleOption} used for parsing the argument. This option determines
   *     the argument value and everything else. For example if it's a {@link PlayerO} the argument
   *     value must be a player and the result value would be a player.
   * @return The added {@link Argument}
   * @throws IllegalArgumentException if an argument with the specified name is already registered
   *     for this command if the argument option is a sub command option and the command already has
   *     an sub command argument or if the argument option is a sub command option and the command
   *     is a sub command.
   */
  public Argument addArgument(String name, ArgRequirement requirement, SingleOption option) {
    Argument argument = new Argument(name, requirement, option);

    if (getAllArguments().containsKey(name.toLowerCase())) {
      throw new IllegalArgumentException(
          "The command already has an argument with the name '" + name + "'!");
    }

    if (argument.option() instanceof SubCmdO) {
      if (isSub()) {
        throw new IllegalArgumentException(
            "Sub commands can not have sub command arguments. [argument=" + name + "]");
      }
      for (Argument arg : arguments.values()) {
        if (arg.option() instanceof SubCmdO) {
          throw new IllegalArgumentException(
              "The command already has a sub command argument."
                  + "Commands can only have one sub command option. [argument="
                  + name
                  + "]");
        }
      }
    }

    arguments.put(name.toLowerCase(), argument);
    return argument;
  }
 private void displayCommand(Command c, Player p) {
   p.sendMessage("-------------Command Arguments---------------");
   p.sendMessage("--------------------------------------------");
   for (Argument arg : c.listArguments()) {
     p.sendMessage(arg.toString());
   }
 }
Beispiel #3
0
  protected void buildPython(IndentingAppender ia) throws IOException {
    String name = getClass().getSimpleName();

    ia.append("def ").append(name).append("(self");
    ia.incrementIndent().incrementIndent();
    for (Argument arg : _arguments) {
      ia.append(", ").append(arg._name);
      if (!arg._required) ia.append("=None");
    }
    ia.appendln("):");
    ia.decrementIndent().decrementIndent();
    ia.incrementIndent();
    ia.appendln("'''");
    ia.appendln(Objects.firstNonNull(_requestHelp, "MISSING HELP STRING"));

    if (!_arguments.isEmpty()) ia.appendln("Arguments:");
    ia.incrementIndent();
    for (Argument arg : _arguments) {
      ia.append(arg._name).append(" -- ");
      if (arg._required) ia.append("required -- ");
      ia.appendln(arg.queryDescription());
      ia.incrementIndent();
      ia.appendln(Objects.firstNonNull(arg._requestHelp, "MISSING HELP STRING"));
      ia.decrementIndent();
    }
    ia.decrementIndent();
    ia.appendln("'''");
    ia.appendln("pass");
    ia.decrementIndent();
  }
 public String toUsageString() {
   StringBuilder sb = new StringBuilder();
   for (Argument a : parameters.values()) {
     sb.append(a.toUsageString("\t"));
   }
   return sb.toString();
 }
  /*
  verifies that each of our registered parameters has a value, either given or default

  throws an exeption otherwise
   */
  private void verify() throws Exception {
    for (Argument parameter : parameters.values()) {
      if (parameter.getValue() == null && parameter.getDefaultValue() == null) {
        throw new Exception(
            String.format("Argument '%s' is required.  Please see usage.", parameter.name));
      }
    }
  }
 @Override
 public <T> T getArgumentValue(String name) {
   Argument arg = cli.getArgument(name);
   if (arg == null) {
     return null;
   }
   return getArgumentValue(arg.getIndex());
 }
Beispiel #7
0
 /**
  * Try to get an array with sub commands that this command has.
  *
  * <p>If this command doesn't have sub commands this will return {@code null}. See {@link
  * #hasSubCmds()}
  *
  * @return Array with {@link SubCmd}s (May be {@code null} when the command doesn't have sub
  *     commands)
  */
 public SubCmd[] getSubCmds() {
   if (isSub() || arguments.size() < 1) {
     return null;
   }
   for (Argument arg : arguments.values()) {
     if (arg.option() instanceof SubCmdO) {
       return ((SubCmdO) arg.option()).getSubCmds();
     }
   }
   return null;
 }
Beispiel #8
0
 protected JsonObject serveHelp() {
   JsonObject r = new JsonObject();
   r.addProperty(NAME, getClass().getSimpleName());
   r.addProperty(DESCRIPTION, _requestHelp);
   JsonArray args = new JsonArray();
   for (Argument arg : _arguments) {
     args.add(arg.requestHelp());
   }
   r.add(ARGUMENTS, args);
   return r;
 }
 public Object getValue(String argumentName) {
   Object value = null;
   argumentName = argumentName.toLowerCase();
   if (parameters.containsKey(argumentName)) {
     Argument argument = parameters.get(argumentName);
     value = argument.getValue();
     if (value == null) {
       String defaultValue = argument.getDefaultValue();
       try {
         value = argument.getHandler().tryArgument(defaultValue);
       } catch (Exception e) {
       }
     }
   }
   return value;
 }
 @Override
 public String getRawValueForArgument(Argument arg) {
   List values = argumentValues.get(arg);
   if (values == null || values.isEmpty()) {
     return arg.getDefaultValue();
   }
   return values.get(0).toString();
 }
 private String[] processParameterTypes(MethodDeclaration methodDeclaration) {
   List<?> args = methodDeclaration.getArguments();
   PHPDocBlock docBlock = ((PHPMethodDeclaration) methodDeclaration).getPHPDoc();
   String[] parameterType = new String[args.size()];
   for (int a = 0; a < args.size(); a++) {
     Argument arg = (Argument) args.get(a);
     if (arg instanceof FormalParameter) {
       SimpleReference type = ((FormalParameter) arg).getParameterType();
       if (type != null) {
         parameterType[a] = type.getName();
       } else if (docBlock != null) {
         for (PHPDocTag tag : docBlock.getTags(PHPDocTag.PARAM)) {
           if (tag.isValidParamTag()
               && tag.getVariableReference().getName().equals(arg.getName())) {
             parameterType[a] = tag.getSingleTypeReference().getName();
             break;
           }
         }
       }
     }
   }
   return parameterType;
 }
Beispiel #12
0
 /**
  * create a predicate argument structure from a canonical string
  *
  * @param s the canonical string of the argument.
  * @throws CorruptDataException
  */
 public static PAStruct ofString(String s) throws CorruptDataException {
   StringTokenizer stok = new StringTokenizer(s);
   int nelts = stok.countTokens();
   if (nelts < 2) {
     throw new CorruptDataException("invalid PAStruct string: " + s);
   }
   String lem = stok.nextToken();
   PAStruct pas = new PAStruct(lem);
   while (stok.hasMoreTokens()) {
     Argument arg = Argument.ofString(stok.nextToken());
     pas.addArg(arg);
   }
   return pas;
 }
  private boolean visitMethodDeclaration(MethodDeclaration method) throws Exception {
    this.fNodes.push(method);
    List<?> args = method.getArguments();

    String[] parameter = new String[args.size()];
    String[] initializers = new String[args.size()];
    for (int a = 0; a < args.size(); a++) {
      Argument arg = (Argument) args.get(a);
      parameter[a] = arg.getName();
      if (arg.getInitialization() != null) {
        if (arg.getInitialization() instanceof Literal) {
          Literal scalar = (Literal) arg.getInitialization();
          initializers[a] = scalar.getValue();
        } else {
          initializers[a] = DEFAULT_VALUE;
        }
      }
    }

    ISourceElementRequestor.MethodInfo mi = new ISourceElementRequestor.MethodInfo();
    mi.parameterNames = parameter;
    mi.name = method.getName();
    mi.modifiers = method.getModifiers();
    mi.nameSourceStart = method.getNameStart();
    mi.nameSourceEnd = method.getNameEnd() - 1;
    mi.declarationStart = method.sourceStart();
    mi.parameterInitializers = initializers;

    modifyMethodInfo(method, mi);

    fInfoStack.push(mi);
    this.fRequestor.enterMethod(mi);

    this.fInMethod = true;
    this.fCurrentMethod = method;
    return true;
  }
 /*
 Tries each handler for the given parameter and returns a success boolean
  */
 private boolean parseKV(String key, String value) throws Exception {
   boolean success = false;
   // must have a registered handler; see registerArgumentHandler()
   if (!parameters.containsKey(key)) {
     throw new Exception(key + " is not a valid argument");
   }
   Argument arg = parameters.get(key);
   // don't allow dupes
   if (arg.getValue() != null) {
     throw new Exception("Duplicate arguments: " + key);
   }
   try {
     // handler returns null if it can't handle the argument
     // it can throw an exception if the argument is an unacceptable value
     Object param = arg.getHandler().tryArgument(value);
     if (param != null) {
       arg.setValue(param);
       success = true;
     }
   } catch (Exception e) {
     throw new Exception("Bad argument value for '" + key + "': " + e.getMessage());
   }
   return success;
 }
 /**
  * Goes through SynapsePath argument list, evaluating each by calling stringValueOf and returns a
  * HashMap String, String array where each item will contain a hash map with key "evaluated
  * expression" and value "SynapsePath type".
  *
  * @param synCtx
  * @return
  */
 private HashMap<String, String>[] getArgValues(MessageContext synCtx) {
   HashMap<String, String>[] argValues = new HashMap[pathArgumentList.size()];
   HashMap<String, String> valueMap;
   String value = "";
   for (int i = 0; i < pathArgumentList.size(); ++i) {
       /*ToDo use foreach*/
     Argument arg = pathArgumentList.get(i);
     if (arg.getValue() != null) {
       value = arg.getValue();
       if (!isWellFormedXML(value)) {
         value = StringEscapeUtils.escapeXml(value);
       }
       value = Matcher.quoteReplacement(value);
     } else if (arg.getExpression() != null) {
       value = arg.getExpression().stringValueOf(synCtx);
       if (value != null) {
         // XML escape the result of an expression that produces a literal, if the target format
         // of the payload is XML.
         if (!isWellFormedXML(value)
             && !arg.getExpression().getPathType().equals(SynapsePath.JSON_PATH)
             && XML_TYPE.equals(getType())) {
           value = StringEscapeUtils.escapeXml(value);
         }
         value = Matcher.quoteReplacement(value);
       } else {
         value = "";
       }
     } else {
       handleException("Unexpected arg type detected", synCtx);
     }
     // value = value.replace(String.valueOf((char) 160), " ").trim();
     valueMap = new HashMap<String, String>();
     if (null != arg.getExpression()) {
       valueMap.put(value, arg.getExpression().getPathType());
     } else {
       valueMap.put(value, SynapsePath.X_PATH);
     }
     argValues[i] = valueMap;
   }
   return argValues;
 }
  public boolean visit(MethodDeclaration method) throws Exception {

    methodGlobalVars.add(new HashSet<String>());

    ASTNode parentDeclaration = null;
    if (!declarations.empty()) {
      parentDeclaration = declarations.peek();
    }

    // In case we are entering a nested element - just add to the deferred
    // list
    // and get out of the nested element visiting process
    if (parentDeclaration instanceof MethodDeclaration) {
      if (fLastNamespace == null) {
        deferredDeclarations.add(method);
      } else {
        deferredNamespacedDeclarations.add(method);
      }
      return false;
    }

    if (parentDeclaration instanceof InterfaceDeclaration) {
      method.setModifier(Modifiers.AccAbstract);
    }

    method.setModifiers(markAsDeprecated(method.getModifiers(), method));

    declarations.push(method);

    for (PHPSourceElementRequestorExtension visitor : extensions) {
      visitor.visit(method);
    }

    boolean visit = visitMethodDeclaration(method);

    if (visit) {
      // Process method argument (local variable) declarations:
      List<Argument> arguments = method.getArguments();
      for (Argument arg : arguments) {
        ISourceElementRequestor.FieldInfo info = new ISourceElementRequestor.FieldInfo();
        info.name = arg.getName();
        info.modifiers = Modifiers.AccPublic;
        info.nameSourceStart = arg.getNameStart();
        info.nameSourceEnd = arg.getNameEnd() - 1;
        info.declarationStart = arg.sourceStart();
        fRequestor.enterField(info);
        fRequestor.exitField(arg.sourceEnd() - 1);
      }
    }
    return visit;
  }
Beispiel #17
0
  /** Iterates over fields and their annotations, and creates argument handlers. */
  @Override
  protected void registered(API_VERSION version) {
    try {
      ArrayList<Class> classes = new ArrayList<Class>();
      {
        Class c = getClass();
        while (c != null) {
          classes.add(c);
          c = c.getSuperclass();
        }
      }
      // Fields from parent classes first
      Collections.reverse(classes);
      ArrayList<Field> fields = new ArrayList<Field>();
      for (Class c : classes)
        for (Field field : c.getDeclaredFields())
          if (!Modifier.isStatic(field.getModifiers())) fields.add(field);

      // TODO remove map, response field already processed specifically
      HashMap<String, FrameClassVec> classVecs = new HashMap<String, FrameClassVec>();
      for (Field f : fields) {
        Annotation[] as = f.getAnnotations();
        API api = find(as, API.class);

        if (api != null && Helper.isInput(api)) {
          f.setAccessible(true);
          Object defaultValue = f.get(this);

          // Create an Argument instance to reuse existing Web framework for now
          Argument arg = null;

          // Simplest case, filter is an Argument
          if (Argument.class.isAssignableFrom(api.filter())) {
            arg = (Argument) newInstance(api);
          }

          //
          else if (ColumnSelect.class.isAssignableFrom(api.filter())) {
            ColumnSelect name = (ColumnSelect) newInstance(api);
            H2OHexKey key = null;
            for (Argument a : _arguments)
              if (a instanceof H2OHexKey && name._ref.equals(((H2OHexKey) a)._name))
                key = (H2OHexKey) a;
            arg = new HexAllColumnSelect(f.getName(), key);
          }

          //
          else if (Dependent.class.isAssignableFrom(api.filter())) {
            Dependent d = (Dependent) newInstance(api);
            Argument ref = find(d._ref);
            if (d instanceof VecSelect) arg = new FrameKeyVec(f.getName(), (TypeaheadKey) ref);
            else if (d instanceof VecClassSelect) {
              arg = new FrameClassVec(f.getName(), (TypeaheadKey) ref);
              classVecs.put(d._ref, (FrameClassVec) arg);
            } else if (d instanceof MultiVecSelect) {
              FrameClassVec response = classVecs.get(d._ref);
              boolean names = ((MultiVecSelect) d)._namesOnly;
              arg =
                  new FrameKeyMultiVec(
                      f.getName(), (TypeaheadKey) ref, response, api.help(), names);
            } else if (d instanceof DoClassBoolean) {
              FrameClassVec response = classVecs.get(d._ref);
              arg = new ClassifyBool(f.getName(), response);
            }
          }

          // String
          else if (f.getType() == String.class) arg = new Str(f.getName(), (String) defaultValue);

          // Real
          else if (f.getType() == float.class || f.getType() == double.class) {
            double val = ((Number) defaultValue).doubleValue();
            arg = new Real(f.getName(), api.required(), val, api.dmin(), api.dmax(), api.help());
          }

          // LongInt
          else if (f.getType() == int.class || f.getType() == long.class) {
            long val = ((Number) defaultValue).longValue();
            arg = new LongInt(f.getName(), api.required(), val, api.lmin(), api.lmax(), api.help());
          }

          // RSeq
          else if (f.getType() == int[].class) {
            int[] val = (int[]) defaultValue;
            double[] ds = null;
            if (val != null) {
              ds = new double[val.length];
              for (int i = 0; i < ds.length; i++) ds[i] = val[i];
            }
            arg =
                new RSeq(
                    f.getName(),
                    api.required(),
                    new NumberSequence(ds, null, true),
                    false,
                    api.help());
          }

          // RSeq
          else if (f.getType() == double[].class) {
            double[] val = (double[]) defaultValue;
            arg =
                new RSeq(
                    f.getName(),
                    api.required(),
                    new NumberSequence(val, null, false),
                    false,
                    api.help());
          }

          // Bool
          else if (f.getType() == boolean.class && api.filter() == Default.class) {
            boolean val = (Boolean) defaultValue;
            arg = new Bool(f.getName(), val, api.help());
          }

          // Enum
          else if (Enum.class.isAssignableFrom(f.getType())) {
            Enum val = (Enum) defaultValue;
            arg = new EnumArgument(f.getName(), val);
          }

          // Key
          else if (f.getType() == Key.class) {
            TypeaheadKey t = new TypeaheadKey();
            t._defaultValue = (Key) defaultValue;
            arg = t;
          }

          // Generic Freezable field
          else if (Freezable.class.isAssignableFrom(f.getType()))
            arg = new TypeaheadKey(f.getType(), api.required());

          if (arg != null) {
            arg._name = f.getName();
            arg._displayName = api.displayName().length() > 0 ? api.displayName() : null;
            arg._required = api.required();
            arg._field = f;
            arg._hideInQuery = api.hide();
            arg._gridable = api.gridable();
            arg._mustExist = api.mustExist();
            arg._validator = newValidator(api);
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public boolean authenticate(
      String[] mechs, final String realm, final String authzid, final String u, final String p)
      throws ProtocolException {

    synchronized (pr) { // authenticate method should be synchronized
      List<Response> v = new ArrayList<Response>();
      String tag = null;
      Response r = null;
      boolean done = false;
      if (logger.isLoggable(Level.FINE)) {
        logger.fine("SASL Mechanisms:");
        for (int i = 0; i < mechs.length; i++) logger.fine(" " + mechs[i]);
        logger.fine("");
      }

      SaslClient sc;
      CallbackHandler cbh =
          new CallbackHandler() {
            public void handle(Callback[] callbacks) {
              if (logger.isLoggable(Level.FINE))
                logger.fine("SASL callback length: " + callbacks.length);
              for (int i = 0; i < callbacks.length; i++) {
                if (logger.isLoggable(Level.FINE))
                  logger.fine("SASL callback " + i + ": " + callbacks[i]);
                if (callbacks[i] instanceof NameCallback) {
                  NameCallback ncb = (NameCallback) callbacks[i];
                  ncb.setName(u);
                } else if (callbacks[i] instanceof PasswordCallback) {
                  PasswordCallback pcb = (PasswordCallback) callbacks[i];
                  pcb.setPassword(p.toCharArray());
                } else if (callbacks[i] instanceof RealmCallback) {
                  RealmCallback rcb = (RealmCallback) callbacks[i];
                  rcb.setText(realm != null ? realm : rcb.getDefaultText());
                } else if (callbacks[i] instanceof RealmChoiceCallback) {
                  RealmChoiceCallback rcb = (RealmChoiceCallback) callbacks[i];
                  if (realm == null) rcb.setSelectedIndex(rcb.getDefaultChoice());
                  else {
                    // need to find specified realm in list
                    String[] choices = rcb.getChoices();
                    for (int k = 0; k < choices.length; k++) {
                      if (choices[k].equals(realm)) {
                        rcb.setSelectedIndex(k);
                        break;
                      }
                    }
                  }
                }
              }
            }
          };

      try {
        sc = Sasl.createSaslClient(mechs, authzid, name, host, (Map) props, cbh);
      } catch (SaslException sex) {
        logger.log(Level.FINE, "Failed to create SASL client", sex);
        throw new UnsupportedOperationException(sex.getMessage(), sex);
      }
      if (sc == null) {
        logger.fine("No SASL support");
        throw new UnsupportedOperationException("No SASL support");
      }
      if (logger.isLoggable(Level.FINE)) logger.fine("SASL client " + sc.getMechanismName());

      try {
        Argument args = new Argument();
        args.writeAtom(sc.getMechanismName());
        if (pr.hasCapability("SASL-IR") && sc.hasInitialResponse()) {
          String irs;
          byte[] ba = sc.evaluateChallenge(new byte[0]);
          if (ba.length > 0) {
            ba = BASE64EncoderStream.encode(ba);
            irs = ASCIIUtility.toString(ba, 0, ba.length);
          } else irs = "=";
          args.writeAtom(irs);
        }
        tag = pr.writeCommand("AUTHENTICATE", args);
      } catch (Exception ex) {
        logger.log(Level.FINE, "SASL AUTHENTICATE Exception", ex);
        return false;
      }

      OutputStream os = pr.getIMAPOutputStream(); // stream to IMAP server

      /*
       * Wrap a BASE64Encoder around a ByteArrayOutputstream
       * to craft b64 encoded username and password strings
       *
       * Note that the encoded bytes should be sent "as-is" to the
       * server, *not* as literals or quoted-strings.
       *
       * Also note that unlike the B64 definition in MIME, CRLFs
       * should *not* be inserted during the encoding process. So, I
       * use Integer.MAX_VALUE (0x7fffffff (> 1G)) as the bytesPerLine,
       * which should be sufficiently large !
       */

      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] CRLF = {(byte) '\r', (byte) '\n'};

      // Hack for Novell GroupWise XGWTRUSTEDAPP authentication mechanism
      // http://www.novell.com/developer/documentation/gwimap/?
      //   page=/developer/documentation/gwimap/gwimpenu/data/al7te9j.html
      boolean isXGWTRUSTEDAPP =
          sc.getMechanismName().equals("XGWTRUSTEDAPP")
              && PropUtil.getBooleanProperty(
                  props, "mail." + name + ".sasl.xgwtrustedapphack.enable", true);
      while (!done) { // loop till we are done
        try {
          r = pr.readResponse();
          if (r.isContinuation()) {
            byte[] ba = null;
            if (!sc.isComplete()) {
              ba = r.readByteArray().getNewBytes();
              if (ba.length > 0) ba = BASE64DecoderStream.decode(ba);
              if (logger.isLoggable(Level.FINE))
                logger.fine("SASL challenge: " + ASCIIUtility.toString(ba, 0, ba.length) + " :");
              ba = sc.evaluateChallenge(ba);
            }
            if (ba == null) {
              logger.fine("SASL no response");
              os.write(CRLF); // write out empty line
              os.flush(); // flush the stream
              bos.reset(); // reset buffer
            } else {
              if (logger.isLoggable(Level.FINE))
                logger.fine("SASL response: " + ASCIIUtility.toString(ba, 0, ba.length) + " :");
              ba = BASE64EncoderStream.encode(ba);
              if (isXGWTRUSTEDAPP) bos.write(ASCIIUtility.getBytes("XGWTRUSTEDAPP "));
              bos.write(ba);

              bos.write(CRLF); // CRLF termination
              os.write(bos.toByteArray()); // write out line
              os.flush(); // flush the stream
              bos.reset(); // reset buffer
            }
          } else if (r.isTagged() && r.getTag().equals(tag))
            // Ah, our tagged response
            done = true;
          else if (r.isBYE()) // outta here
          done = true;
          else // hmm .. unsolicited response here ?!
          v.add(r);
        } catch (Exception ioex) {
          logger.log(Level.FINE, "SASL Exception", ioex);
          // convert this into a BYE response
          r = Response.byeResponse(ioex);
          done = true;
          // XXX - ultimately return true???
        }
      }

      if (sc.isComplete() /*&& res.status == SUCCESS*/) {
        String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
        if (qop != null
            && (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf"))) {
          // XXX - NOT SUPPORTED!!!
          logger.fine("SASL Mechanism requires integrity or confidentiality");
          return false;
        }
      }

      /* Dispatch untagged responses.
       * NOTE: in our current upper level IMAP classes, we add the
       * responseHandler to the Protocol object only *after* the
       * connection has been authenticated. So, for now, the below
       * code really ends up being just a no-op.
       */
      Response[] responses = v.toArray(new Response[v.size()]);
      pr.notifyResponseHandlers(responses);

      // Handle the final OK, NO, BAD or BYE response
      pr.handleResult(r);
      pr.setCapabilities(r);

      /*
       * If we're using the Novell Groupwise XGWTRUSTEDAPP mechanism
       * to run as a specified authorization ID, we have to issue a
       * LOGIN command to select the user we want to operate as.
       */
      if (isXGWTRUSTEDAPP && authzid != null) {
        Argument args = new Argument();
        args.writeString(authzid);

        responses = pr.command("LOGIN", args);

        // dispatch untagged responses
        pr.notifyResponseHandlers(responses);

        // Handle result of this command
        pr.handleResult(responses[responses.length - 1]);
        // If the response includes a CAPABILITY response code, process it
        pr.setCapabilities(responses[responses.length - 1]);
      }
      return true;
    }
  }
Beispiel #19
0
  @SuppressWarnings("unchecked")
  public boolean visit(MethodDeclaration method) throws Exception {
    fNodes.push(method);
    methodGlobalVars.add(new HashSet<String>());
    int modifiers = method.getModifiers();
    PHPDocBlock doc = null;
    if (method instanceof IPHPDocAwareDeclaration) {
      IPHPDocAwareDeclaration declaration = (IPHPDocAwareDeclaration) method;
      doc = declaration.getPHPDoc();
    }
    Declaration parentDeclaration = null;
    if (!declarations.empty()) {
      parentDeclaration = declarations.peek();
    }
    declarations.push(method);

    // In case we are entering a nested element - just add to the deferred
    // list
    // and get out of the nested element visiting process
    if (parentDeclaration instanceof MethodDeclaration) {
      if (fCurrentNamespace == null) {
        deferredDeclarations.add(method);
      } else {
        deferredNamespacedDeclarations.add(method);
      }
      return visitGeneral(method);
    }

    if (parentDeclaration instanceof InterfaceDeclaration) {
      method.setModifier(Modifiers.AccAbstract);
    }

    String methodName = method.getName();

    // Determine whether this method represents constructor:
    if (methodName.equalsIgnoreCase(CONSTRUCTOR_NAME)
        || (parentDeclaration instanceof ClassDeclaration
            && methodName.equalsIgnoreCase(((ClassDeclaration) parentDeclaration).getName()))) {
      modifiers |= IPHPModifiers.Constructor;
    }

    if (parentDeclaration == null
        || (parentDeclaration instanceof TypeDeclaration
            && parentDeclaration == fCurrentNamespace)) {
      modifiers |= Modifiers.AccGlobal;
    }
    if (!Flags.isPrivate(modifiers)
        && !Flags.isProtected(modifiers)
        && !Flags.isPublic(modifiers)) {
      modifiers |= Modifiers.AccPublic;
    }

    modifiers = markAsDeprecated(modifiers, method);

    StringBuilder metadata = new StringBuilder();
    if (fCurrentQualifier != null) {
      metadata.append(fCurrentQualifierCounts.get(fCurrentQualifier));
      metadata.append(";"); // $NON-NLS-1$
    }
    List<Argument> arguments = method.getArguments();
    if (arguments != null) {
      Iterator<Argument> i = arguments.iterator();
      while (i.hasNext()) {
        Argument arg = (Argument) i.next();

        String type = NULL_VALUE;
        if (arg instanceof FormalParameter) {
          FormalParameter fp = (FormalParameter) arg;
          if (fp.getParameterType() != null) {
            if (fp.getParameterType().getName() != null) {
              type = fp.getParameterType().getName();
            }
          }
        }
        if (type == NULL_VALUE && doc != null) {
          type = getParamType(doc, arg.getName(), type);
        }

        metadata.append(type);
        metadata.append(PARAMETER_SEPERATOR);
        metadata.append(arg.getName());
        metadata.append(PARAMETER_SEPERATOR);
        String defaultValue = NULL_VALUE;
        if (arg.getInitialization() != null) {
          if (arg.getInitialization() instanceof Literal) {
            Literal scalar = (Literal) arg.getInitialization();
            defaultValue = scalar.getValue();
          } else {
            defaultValue = DEFAULT_VALUE;
          }
        }
        metadata.append(defaultValue);
        if (i.hasNext()) {
          metadata.append(","); // $NON-NLS-1$
        }
      }
    }

    // Add method declaration:
    modifyDeclaration(
        method,
        new DeclarationInfo(
            IModelElement.METHOD,
            modifiers,
            method.sourceStart(),
            method.sourceEnd() - method.sourceStart(),
            method.getNameStart(),
            method.getNameEnd() - method.getNameStart(),
            methodName,
            metadata.length() == 0 ? null : metadata.toString(),
            encodeDocInfo(method),
            fCurrentQualifier,
            fCurrentParent));

    for (PhpIndexingVisitorExtension visitor : extensions) {
      visitor.visit(method);
    }

    return visitGeneral(method);
  }
 /** {@inheritDoc} */
 public int compare(GroupItem<?> group1, GroupItem<?> group2) {
   return nullSafeCompare(
       argument.evaluate(group1.getGroupKey()), argument.evaluate(group2.getGroupKey()));
 }
  public boolean visit(LambdaFunctionDeclaration lambdaMethod) throws Exception {

    fNodes.push(lambdaMethod);
    methodGlobalVars.add(new HashSet<String>());

    // Declaration parentDeclaration = null;
    // if (!declarations.empty()
    // && declarations.peek() instanceof MethodDeclaration) {
    // parentDeclaration = declarations.peek();
    // // In case we are entering a nested element - just add to the
    // // deferred list and get out of the nested element visiting process
    // deferredDeclarations.add(lambdaMethod);
    // return visitGeneral(lambdaMethod);
    // }

    Collection<FormalParameter> arguments = lambdaMethod.getArguments();
    StringBuilder metadata = new StringBuilder();
    String[] parameters;
    if (arguments != null) {
      parameters = new String[arguments.size()];
      Iterator<FormalParameter> i = arguments.iterator();
      int indx = 0;
      while (i.hasNext()) {
        Argument arg = (Argument) i.next();
        metadata.append(arg.getName());
        parameters[indx] = arg.getName();
        indx++;
        if (i.hasNext()) {
          metadata.append(","); // $NON-NLS-1$
        }
      }
    } else {
      parameters = new String[0];
    }

    // Add method declaration:
    for (PHPSourceElementRequestorExtension visitor : extensions) {
      visitor.visit(lambdaMethod);
    }

    ISourceElementRequestor.MethodInfo mi = new ISourceElementRequestor.MethodInfo();
    mi.parameterNames = parameters;
    mi.name = PHPCoreConstants.ANONYMOUS;
    mi.modifiers = Modifiers.AccPublic;
    if (lambdaMethod.isStatic()) {
      mi.modifiers |= Modifiers.AccStatic;
    }
    mi.nameSourceStart = lambdaMethod.sourceStart();
    mi.nameSourceEnd = lambdaMethod.sourceEnd();
    mi.declarationStart = mi.nameSourceStart;
    mi.isConstructor = false;

    fInfoStack.push(mi);
    this.fRequestor.enterMethod(mi);
    this.fInMethod = true;

    for (Argument arg : arguments) {
      ISourceElementRequestor.FieldInfo info = new ISourceElementRequestor.FieldInfo();
      info.name = arg.getName();
      info.modifiers = Modifiers.AccPublic;
      info.nameSourceStart = arg.getNameStart();
      info.nameSourceEnd = arg.getNameEnd() - 1;
      info.declarationStart = arg.sourceStart();
      fRequestor.enterField(info);
      fRequestor.exitField(arg.sourceEnd() - 1);
    }

    return true;
  }
 /*
 Register a new Argument handler for a desired parameter
  */
 public void registerArgument(Argument argument) {
   parameters.put(argument.getName().toLowerCase(), argument);
 }
Beispiel #23
0
 protected static final void help(Argument arg, String help) {
   arg._requestHelp = help;
 }