コード例 #1
1
  public List<String> onTabComplete(
      CommandSender commandSender, Command command, String s, String[] strings) {

    for (TabCompleter completer : delegateCompleters) {
      List<String> list = completer.onTabComplete(commandSender, command, s, strings);
      if (list != null) return list;
    }

    String expression = strings[strings.length - 1];
    TreeSet<String> result = new TreeSet<String>();
    Caller caller = plugin.getCallerService().getCaller(commandSender);
    WorkspaceService service = plugin.getWorkspaceService();
    String workspaceName = service.getWorkspaceName(commandSender);
    Workspace workspace = service.getWorkspace(workspaceName);
    LinkedList<String> tokens = new LinkedList<String>();
    boolean needHelp = expression.endsWith("?");
    if (needHelp) expression = expression.substring(0, expression.length() - 1);
    Collections.addAll(tokens, expression.split("\\."));
    if (expression.endsWith(".")) tokens.add("");

    if (needHelp) {
      getHelp(caller, workspace, tokens);
      return Collections.singletonList(expression);
    }

    String firstToken = tokens.pollFirst();
    if (firstToken == null) firstToken = "";
    MetaClass callerScriptMetaClass = InvokerHelper.getMetaClass(CallerScript.class);
    MetaClass workspaceMetaClass = InvokerHelper.getMetaClass(Workspace.class);
    Map workspaceVars = null;
    if (workspace != null) workspaceVars = workspace.getBinding().getVariables();
    Map globalVars = service.getBinding().getVariables();
    PreparedScriptProperties properties = new PreparedScriptProperties();
    properties.setCaller(caller);
    properties.setServer(plugin.getServer());
    properties.setWorkspace(workspace);

    if (tokens.isEmpty()) { // get current method or class
      for (MetaProperty metaProperty : callerScriptMetaClass.getProperties()) {
        String name = metaProperty.getName();
        if (name.contains(firstToken)) result.add(name);
      }
      for (String name : service.getImportTabCompleteClasses().keySet()) {
        if (name.contains(firstToken)) result.add(name);
      }
      for (MetaMethod metaMethod : callerScriptMetaClass.getMetaMethods()) {
        if (metaMethod.getDeclaringClass().getTheClass().equals(Object.class)) continue;
        String name = metaMethod.getName();
        if (name.contains(firstToken)) {
          String methodEnd = "(";
          if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{";
          else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()";
          result.add(name + methodEnd);
        }
        int args = metaMethod.getParameterTypes().length;
        if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
            && name.length() > 3) {
          String propertyName = getPropertyName(name);
          if (propertyName != null && propertyName.contains(firstToken)) result.add(propertyName);
        }
      }
      for (MetaMethod metaMethod : workspaceMetaClass.getMetaMethods()) {
        if (metaMethod.getDeclaringClass().getTheClass().equals(Object.class)) continue;
        String name = metaMethod.getName();
        if (name.contains(firstToken)) {
          String methodEnd = "(";
          if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{";
          else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()";
          result.add(name + methodEnd);
        }
      }
      for (Method method : CallerScript.class.getMethods()) {
        if (method.getDeclaringClass().equals(Object.class)) continue;
        String name = method.getName();
        if (name.contains(firstToken)) {
          String methodEnd = "(";
          Class<?>[] types = method.getParameterTypes();
          if (types.length == 1 && Closure.class.isAssignableFrom(types[0])) methodEnd = "{";
          else if (types.length == 0) methodEnd = "()";
          result.add(name + methodEnd);
          int args = method.getParameterTypes().length;
          if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
              && name.length() > 3) {
            String propertyName = getPropertyName(name);
            if (propertyName != null && propertyName.contains(firstToken)) result.add(propertyName);
          }
        }
      }
      for (Method method : Workspace.class.getMethods()) {
        if (method.getDeclaringClass().equals(Object.class)) continue;
        String name = method.getName();
        if (name.contains(firstToken)) {
          String methodEnd = "(";
          Class<?>[] types = method.getParameterTypes();
          if (types.length == 1 && Closure.class.isAssignableFrom(types[0])) methodEnd = "{";
          else if (types.length == 0) methodEnd = "()";
          result.add(name + methodEnd);
        }
      }
      if (workspaceVars != null)
        for (Object key : workspaceVars.keySet()) {
          String name = key.toString();
          if (name.contains(firstToken)) result.add(name);
        }
      if (globalVars != null)
        for (Object key : globalVars.keySet()) {
          String name = key.toString();
          if (name.contains(firstToken)) result.add(name);
        }
      for (GroovyObject modifier : CallerScript.getDynamicModifiers()) {
        Object[] params = {properties};
        try {
          Map<?, ?> map =
              (Map) modifier.getMetaClass().invokeMethod(modifier, "getPropertyMapFor", params);
          for (Object key : map.keySet()) {
            String name = key.toString();
            if (name.contains(firstToken)) result.add(name);
          }
        } catch (Exception ignored) {
        }
        try {
          Map<?, ?> map =
              (Map) modifier.getMetaClass().invokeMethod(modifier, "getMethodMapFor", params);
          for (Object key : map.keySet()) {
            String name = key.toString();
            if (name.contains(firstToken)) result.add(name + "(");
          }
        } catch (Exception ignored) {
        }
      }
      if (globalVars != null)
        for (Object key : globalVars.keySet()) {
          String name = key.toString();
          if (name.contains(firstToken)) result.add(name);
        }
      return new ArrayList<String>(result);
    }

    // get metaclass of first token
    MetaClass metaClass =
        getFirstTokenMeta(
            caller,
            firstToken,
            commandSender,
            service,
            callerScriptMetaClass,
            workspaceMetaClass,
            workspace,
            workspaceVars,
            globalVars,
            properties);
    boolean classHook =
        tokens.size() <= 1 && service.getImportTabCompleteClasses().containsKey(firstToken);

    if (metaClass == null) return null;
    metaClass = skipTokens(tokens, metaClass);
    if (metaClass == null) return null;

    // select property or method of last metaclass
    String token = tokens.pollFirst();
    Class theClass = metaClass.getTheClass();
    String inputPrefix = expression.substring(0, expression.lastIndexOf('.')) + ".";
    for (MetaProperty metaProperty : metaClass.getProperties()) {
      String name = metaProperty.getName();
      if (name.startsWith(token)) result.add(inputPrefix + name);
    }
    for (MetaMethod metaMethod : metaClass.getMetaMethods()) {
      if (metaMethod.getDeclaringClass().getTheClass().equals(Object.class)) continue;
      String name = metaMethod.getName();
      if (name.startsWith(token)) {
        String methodEnd = "(";
        if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{";
        else if (metaMethod.getNativeParameterTypes().length == 0) methodEnd = "()";
        result.add(inputPrefix + name + methodEnd);
      }
      int args = metaMethod.getParameterTypes().length;
      if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
          && name.length() > 3) {
        String propertyName = getPropertyName(name);
        if (propertyName != null && propertyName.startsWith(token))
          result.add(inputPrefix + propertyName);
      }
    }
    for (Method method : theClass.getMethods()) {
      if (method.getDeclaringClass().equals(Object.class)) continue;
      String name = method.getName();
      if (name.startsWith(token)) {
        String methodEnd = "(";
        Class<?>[] types = method.getParameterTypes();
        if (types.length == 1 && Closure.class.isAssignableFrom(types[0])) methodEnd = "{";
        if (types.length == 0) methodEnd = "()";
        result.add(inputPrefix + name + methodEnd);
      }
      int args = method.getParameterTypes().length;
      if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
          && name.length() > 3) {
        String propertyName = getPropertyName(name);
        if (propertyName != null && propertyName.startsWith(token))
          result.add(inputPrefix + propertyName);
      }
    }
    if (Enum.class.isAssignableFrom(theClass)) {
      Enum[] enumValues = getEnumValues(theClass);
      if (enumValues != null)
        for (Enum anEnum : enumValues) {
          String name = anEnum.name();
          if (name.startsWith(token)) result.add(inputPrefix + name);
        }
    }
    if (classHook) {
      for (MetaProperty metaProperty : InvokerHelper.getMetaClass(Class.class).getProperties()) {
        String name = metaProperty.getName();
        if (name.startsWith(token)) result.add(inputPrefix + name);
      }
      for (Method method : Class.class.getMethods()) {
        if (method.getDeclaringClass().equals(Object.class)) continue;
        String name = method.getName();
        if (name.startsWith(token)) {
          String methodEnd = "(";
          Class<?>[] types = method.getParameterTypes();
          if (types.length == 1 && Closure.class.isAssignableFrom(types[0])) methodEnd = "{";
          if (types.length == 0) methodEnd = "()";
          result.add(inputPrefix + name + methodEnd);
        }
        int args = method.getParameterTypes().length;
        if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
            && name.length() > 3) {
          String propertyName = getPropertyName(name);
          if (propertyName != null && propertyName.startsWith(token))
            result.add(inputPrefix + propertyName);
        }
      }
    }
    return new ArrayList<String>(result);
  }
コード例 #2
0
  private boolean addClassMemberStaticImports(String packageName) {
    try {
      Class c = Class.forName(packageName);
      initImports();
      if (c.isEnum()) {

        //noinspection unchecked
        for (Enum e : (EnumSet<?>) EnumSet.allOf(c)) {
          imports.put(e.name(), e);
        }
        return true;
      } else {
        for (Field f : c.getDeclaredFields()) {
          if ((f.getModifiers() & (Modifier.STATIC | Modifier.PUBLIC)) != 0) {
            imports.put(f.getName(), f.get(null));
          }
        }
      }
    } catch (ClassNotFoundException e) {
      // do nothing.
    } catch (IllegalAccessException e) {
      throw new RuntimeException("error adding static imports for: " + packageName, e);
    }
    return false;
  }
コード例 #3
0
 public List<Feature> kindTagging(List<String> words) {
   List<Feature> features = new ArrayList<Feature>();
   for (String word : words) {
     Feature feature = new Feature();
     feature.setText(word);
     if (isPrivativeWord(word)) {
       // System.out.println("bubnububub");
       feature.setKind(Enum.valueOf(WordType.class, "PRIVATIVE"));
       feature.setMultiple(-1.0);
     } else if (isDecoVeryWord(word)) {
       feature.setKind(Enum.valueOf(WordType.class, "DECORATEVERY"));
       feature.setMultiple(2.0);
     } else if (isDecoLittleWord(word)) {
       feature.setKind(Enum.valueOf(WordType.class, "DECORATELITTLE"));
       feature.setMultiple(0.5);
     } else if (isPositiveWord(word)) {
       feature.setKind(Enum.valueOf(WordType.class, "POSITIVE"));
       feature.setMultiple(1.0);
       feature.setScore(posiLexicon.get(word));
     } else if (isNegativeWord(word)) {
       feature.setKind(Enum.valueOf(WordType.class, "NEGATIVE"));
       feature.setMultiple(-1.0);
       feature.setScore(negaLexicon.get(word));
     }
     features.add(feature);
   }
   return features;
 }
コード例 #4
0
ファイル: Conversions.java プロジェクト: ThrawnCA/boon
 public static <T extends Enum> T toEnumOld(Class<T> cls, String value) {
   try {
     return (T) Enum.valueOf(cls, value);
   } catch (Exception ex) {
     return (T) Enum.valueOf(cls, value.toUpperCase().replace('-', '_'));
   }
 }
コード例 #5
0
ファイル: StringParser.java プロジェクト: phspaelti/basex
  /**
   * Returns the found command or throws an exception.
   *
   * @param cmp possible completions
   * @param par parent command
   * @param <E> token type
   * @return index
   * @throws QueryException query exception
   */
  private <E extends Enum<E>> E consume(final Class<E> cmp, final Cmd par) throws QueryException {

    final String token = command(null);
    if (!suggest || token == null || !token.isEmpty()) {
      try {
        // return command reference; allow empty strings as input ("NULL")
        return Enum.valueOf(cmp, token == null ? "NULL" : token.toUpperCase(Locale.ENGLISH));
      } catch (final IllegalArgumentException ignore) {
      }
    }

    final Enum<?>[] alt = startWith(cmp, token);
    // handle empty input
    if (token == null) {
      if (par != null) throw help(alt, par);
      if (suggest) throw error(alt, EXPECTING_CMD);
      return null;
    }

    // output error for similar commands
    final byte[] name = uc(token(token));
    final Levenshtein ls = new Levenshtein();
    for (final Enum<?> s : startWith(cmp, null)) {
      final byte[] sm = uc(token(s.name()));
      if (ls.similar(name, sm) && Cmd.class.isInstance(s)) {
        throw error(alt, UNKNOWN_SIMILAR_X, name, sm);
      }
    }

    // show unknown command error or available command extensions
    throw par == null ? error(alt, UNKNOWN_TRY_X, token) : help(alt, par);
  }
コード例 #6
0
ファイル: StringParser.java プロジェクト: phspaelti/basex
 /**
  * Converts the specified commands into a string list.
  *
  * @param comp input completions
  * @return string list
  */
 private static StringList list(final Enum<?>[] comp) {
   final StringList list = new StringList();
   if (comp != null) {
     for (final Enum<?> c : comp) list.add(c.name().toLowerCase(Locale.ENGLISH));
   }
   return list;
 }
コード例 #7
0
 @Override
 protected String getEnumName(Enum e) {
   String name = enumClassToNameMap.get(e.getClass());
   if (name == null) {
     throw new IllegalArgumentException("Enum class not known to factory:" + e.getClass());
   }
   return name;
 }
コード例 #8
0
ファイル: StringParser.java プロジェクト: phspaelti/basex
 /**
  * Returns all commands that start with the specified user input.
  *
  * @param <T> token type
  * @param en available commands
  * @param prefix user input
  * @return completions
  */
 private static <T extends Enum<T>> Enum<?>[] startWith(final Class<T> en, final String prefix) {
   Enum<?>[] list = new Enum<?>[0];
   final String t = prefix == null ? "" : prefix.toUpperCase(Locale.ENGLISH);
   for (final Enum<?> e : en.getEnumConstants()) {
     if (e.name().startsWith(t)) {
       final int s = list.length;
       list = Array.copy(list, new Enum<?>[s + 1]);
       list[s] = e;
     }
   }
   return list;
 }
コード例 #9
0
ファイル: DefaultQueryConf.java プロジェクト: tivv/esorm
 @Override
 public <T> T get(Enum key, Class<T> resultClass, T defaultValue) {
   if (defaultValue == null) {
     try {
       String def =
           key.getDeclaringClass().getField(key.name()).getAnnotation(Default.class).value();
       if (resultClass == String.class) return (T) def;
       return resultClass.getConstructor(String.class).newInstance(def);
     } catch (Exception e) {
       throw new RegisteredExceptionWrapper(e);
     }
   }
   return defaultValue;
 }
コード例 #10
0
  public static void main(String args[]) {

    int width = IN.nextInt();
    int height = IN.nextInt();
    IN.nextLine();
    System.err.println(width + " " + height);

    Grid tunnelMap = new Grid(width, height);

    fillTunelMap(tunnelMap);

    int exit =
        IN
            .nextInt(); // the coordinate along the X axis of the exit (not useful for this first
                        // mission, but must be read).
    System.err.println(exit);
    tunnelMap.setEndPosition(new Position(exit, height - 1));

    // game loop
    while (true) {
      Position IndiActPosition = new Position(IN.nextInt(), IN.nextInt());

      Direction entranceDirection = Enum.valueOf(Direction.class, IN.next());

      tunnelMap.getRoom(IndiActPosition).setEntrance(entranceDirection);
      tunnelMap.initializeGrid();
      tunnelMap.findPathFromStartToEnd(IndiActPosition);

      int numberOfRocks = IN.nextInt(); // the number of rocks currently in the grid.

      for (int i = 0; i < numberOfRocks; i++) {
        System.err.println();
        int XR = IN.nextInt();
        int YR = IN.nextInt();
        Position rockPosition = new Position(XR, YR);
        Direction entranceOfRock = Enum.valueOf(Direction.class, IN.next());
        tunnelMap.getRoom(rockPosition).setEntrance(entranceOfRock);
        tunnelMap.compareRockPathWithIndisPath(rockPosition);

        System.err.println("ROCK " + rockPosition + " " + entranceOfRock);
      }

      String command = tunnelMap.nextCommand();

      // One line containing the X Y coordinates of the room in which you believe Indy will be on
      // the next turn.
      System.out.println(command);
    }
  }
コード例 #11
0
ファイル: JSONWriter.java プロジェクト: freiby/nirvana
 /**
  * Instrospect an Enum and serialize it as a name/value pair or as a bean including all its own
  * properties
  */
 protected void enumeration(Enum enumeration) throws JSONException {
   if (enumAsBean) {
     this.bean(enumeration);
   } else {
     this.string(enumeration.name());
   }
 }
コード例 #12
0
 protected IDatabaseManager.DatabaseType getType(DataSource dataSource) throws ApsSystemException {
   String typeString = null;
   try {
     String driverClassName = this.invokeGetMethod("getDriverClassName", dataSource);
     Iterator<Object> typesIter = this.getDatabaseTypeDrivers().keySet().iterator();
     while (typesIter.hasNext()) {
       String typeCode = (String) typesIter.next();
       List<String> driverClassNames = (List<String>) this.getDatabaseTypeDrivers().get(typeCode);
       if (null != driverClassNames && driverClassNames.contains(driverClassName)) {
         typeString = typeCode;
         break;
       }
     }
     if (null == typeString) {
       ApsSystemUtils.getLogger()
           .severe(
               "Type not recognized for Driver '"
                   + driverClassName
                   + "' - "
                   + "Recognized types '"
                   + IDatabaseManager.DatabaseType.values()
                   + "'");
       return IDatabaseManager.DatabaseType.UNKNOWN;
     }
     return Enum.valueOf(IDatabaseManager.DatabaseType.class, typeString.toUpperCase());
   } catch (Throwable t) {
     ApsSystemUtils.getLogger()
         .severe("Invalid type for db - '" + typeString + "' - " + t.getMessage());
     throw new ApsSystemException("Invalid type for db - '" + typeString + "'", t);
   }
 }
コード例 #13
0
 public static <T extends Enum<T>> T convertEnum(Class<T> clazz, String value) {
   try {
     return Enum.valueOf(clazz, value);
   } catch (IllegalArgumentException e) {
     throw new ConstrettoConversionException(value, clazz, e);
   }
 }
コード例 #14
0
ファイル: Command.java プロジェクト: plutext/basex
 /**
  * Returns the specified command option.
  *
  * @param s string to be found
  * @param typ options enumeration
  * @param <E> token type
  * @return option
  */
 protected static <E extends Enum<E>> E getOption(final String s, final Class<E> typ) {
   try {
     return Enum.valueOf(typ, s.toUpperCase(Locale.ENGLISH));
   } catch (final Exception ex) {
     return null;
   }
 }
コード例 #15
0
ファイル: HiveCatalogStore.java プロジェクト: javaoracle/tajo
 private TajoDataTypes.Type getDataType(final String typeStr) {
   try {
     return Enum.valueOf(TajoDataTypes.Type.class, typeStr);
   } catch (IllegalArgumentException iae) {
     LOG.error("Cannot find a matched type against from '" + typeStr + "'");
     return null;
   }
 }
コード例 #16
0
ファイル: CoreDictionary.java プロジェクト: aunjgr/HanLP
 /**
  * 获取词性的词频
  *
  * @param nature 字符串词性
  * @return 词频
  * @deprecated 推荐使用Nature参数!
  */
 public int getNatureFrequency(String nature) {
   try {
     Nature pos = Enum.valueOf(Nature.class, nature);
     return getNatureFrequency(pos);
   } catch (IllegalArgumentException e) {
     return 0;
   }
 }
コード例 #17
0
ファイル: BaseMod.java プロジェクト: nevercast/SGCraft
 public void registerEntity(
     Class<? extends Entity> cls,
     String name,
     Enum id,
     int updateFrequency,
     boolean sendVelocityUpdates) {
   registerEntity(cls, name, id.ordinal(), updateFrequency, sendVelocityUpdates);
 }
コード例 #18
0
 @SuppressWarnings("unchecked")
 @Override
 protected Enum createEnum(String name, String value) {
   Class enumClass = nameToEnumClassMap.get(name);
   if (enumClass == null) {
     throw new IllegalArgumentException("Enum name not known to factory:" + name);
   }
   Set<Enum> enums = valueToEnumMap.get(value);
   if (enums == null) {
     return Enum.valueOf(enumClass, value);
   }
   for (Enum e : enums) {
     if (e.getClass() == enumClass) {
       return e;
     }
   }
   throw new IllegalArgumentException("Enum value not known to factory:" + value);
 }
コード例 #19
0
 /**
  * Helper method that can be used to dynamically figure out formal enumeration type (class) for
  * given enumeration. This is either class of enum instance (for "simple" enumerations), or its
  * superclass (for enums with instance fields or methods)
  */
 @SuppressWarnings("unchecked")
 public static Class<? extends Enum<?>> findEnumType(Enum<?> en) {
   // enums with "body" are sub-classes of the formal type
   Class<?> ec = en.getClass();
   if (ec.getSuperclass() != Enum.class) {
     ec = ec.getSuperclass();
   }
   return (Class<? extends Enum<?>>) ec;
 }
コード例 #20
0
  /** Return the value of an enum of the given type. Prefix allows a shortened form of the enum */
  @SuppressWarnings("unchecked")
  public <T extends Enum<T>> T getEnum(String prop, String prefix, T dflt) {
    Enum<?> v = dflt;
    String s = getProperty(prop);
    if (s == null || s.length() == 0) return dflt;
    if (prefix != null && !s.startsWith(prefix)) s = prefix + s;
    Object[] vals = dflt.getClass().getEnumConstants();
    if (vals == null) return dflt;
    for (int i = 0; i < vals.length; ++i) {
      Enum<?> e = (Enum<?>) vals[i];
      if (e.name().equalsIgnoreCase(s)) {
        v = e;
        break;
      }
    }

    return (T) v;
  }
コード例 #21
0
 public JSONObject describeClass(Class<?> clazz) throws Exception {
   JSONObject desc = new JSONObject();
   desc.put("name", clazz.getName());
   if (clazz.isEnum()) {
     @SuppressWarnings("unchecked")
     Class<Enum<?>> enumClass = (Class<Enum<?>>) clazz;
     ArrayList<String> enumNames = Lists.newArrayList();
     for (Enum<?> e : enumClass.getEnumConstants()) {
       enumNames.add(e.name());
     }
     desc.put("enum", enumNames);
   }
   UI_TYPE ui_type = UI_TYPE.getEnumFor(clazz);
   if (ui_type != null) {
     desc.put("uiType", ui_type.getName());
   }
   desc.put("properties", getClassProperties(clazz, 0));
   return desc;
 }
コード例 #22
0
  public static Enum<?> setUpEnumAttribute(Scanner scan, Attributes.AttributeEnum attribute) {
    int num;
    Attributes.printEnumNValuesOfEnumAttribute(attribute);
    num =
        makeSureValInRange(
                scan,
                1,
                Attributes.getEnumAttrValues(attribute).length,
                attribute.toString(),
                ValType.INTEGER,
                true,
                true)
            .intValue();

    Enum<?> attr = Attributes.getEnumAttrByVal(num, attribute);
    System.out.println(
        inputString(attr.getClass().getSimpleName(), attr.toString(), StringOption.SELECTED, true));
    return attr;
  }
コード例 #23
0
  @NotNull
  private static Optional<TypeConversion> findEnumConversion(@NotNull Type target) {
    if (isEnum(target)) {
      @SuppressWarnings("rawtypes")
      Class<? extends Enum> cl = rawType(target).asSubclass(Enum.class);

      return Optional.ofNullable(
          TypeConversion.fromNonNullFunction(value -> Enum.valueOf(cl, value.toString())));
    }

    return Optional.empty();
  }
 @Override
 public void loadState(Element element) {
   List children = element.getChildren(SETTING_TAG);
   for (final Object aChildren : children) {
     final Element child = (Element) aChildren;
     final String url = child.getAttributeValue(FILE_ATT);
     if (url == null) continue;
     final VirtualFile fileByUrl = VirtualFileManager.getInstance().findFileByUrl(url);
     if (fileByUrl != null) {
       final List<FileHighlightingSetting> settings = new ArrayList<FileHighlightingSetting>();
       int index = 0;
       while (child.getAttributeValue(ROOT_ATT_PREFIX + index) != null) {
         final String attributeValue = child.getAttributeValue(ROOT_ATT_PREFIX + index++);
         settings.add(Enum.valueOf(FileHighlightingSetting.class, attributeValue));
       }
       myHighlightSettings.put(
           fileByUrl, settings.toArray(new FileHighlightingSetting[settings.size()]));
     }
   }
 }
コード例 #25
0
  @Before
  public void setup() throws Exception {
    user = new User();
    user.setUserId(1L);
    user.setUserName(USERNAME);
    user.setHashedPassword(HASHED_PASSWORD);

    canvas = new Canvas("testCanvas1");

    List<String> listensFor = new ArrayList<String>();
    listensFor.add("Area");
    listensFor.add("Shift");
    listensFor.add("Picker");

    List<Integer> anchorList = new ArrayList<Integer>();
    anchorList.add(2);
    anchorList.add(3);

    List<Map<String, String>> options = new ArrayList<Map<String, String>>();
    Map<String, String> optionsMap1 = new HashMap<String, String>();
    optionsMap1.put("legend", "horizontal");
    optionsMap1.put("value", "h");
    Map<String, String> optionsMap2 = new HashMap<String, String>();
    optionsMap2.put("legend", "vertical");
    optionsMap2.put("value", "v");
    options.add(optionsMap1);
    options.add(optionsMap2);

    widgetOrientation = new WidgetOrientation(options, "h");

    defaultViewConfig = new DefaultViewConfig(anchorList, 2L, 2L, 2L, widgetOrientation);
    actualViewConfig = new ActualViewConfig(anchorList, 2L, 2L, 2L, listensFor);
    p1 = new Permission("create-assignment");
    p2 = new Permission("view-report-productivity");
    p3 = new Permission("configure-location");
    p4 = new Permission("create-canvas");
    p5 = new Permission("delete-canvas");
    p6 = new Permission("authenticated-user");
    p7 = new Permission("pickingwidget2-widget-access");
    Map<String, Map<Permission, Boolean>> mappedActionConfigurableMap =
        new HashMap<String, Map<Permission, Boolean>>();
    mappedActionConfig = new PermissionMappedActionConfig(mappedActionConfigurableMap);

    mappedActionConfigurableMap.put(
        "widget-access",
        new HashMap<Permission, Boolean>() {
          {
            put(p7, Boolean.FALSE);
          }
        });

    mappedActionConfigurableMap.put(
        "widget-actions",
        new HashMap<Permission, Boolean>() {
          {
            put(p1, Boolean.FALSE);
            put(p2, Boolean.FALSE);
            put(p3, Boolean.FALSE);
            put(p4, Boolean.FALSE);
            put(p5, Boolean.FALSE);
            put(p6, Boolean.FALSE);
          }
        });

    ObjectMapper objectMapper = new ObjectMapper();

    widget =
        new UserCreationFormWidget(
            "Picking Widget2",
            "pick2",
            Enum.valueOf(WidgetType.class, "GRID"),
            objectMapper.writeValueAsString(defaultViewConfig));
    widget.setActionConfig(mappedActionConfig);
    widget.setActive(true);
    widget.setCategory("Administration");
    ;
    widgetInstance =
        new DefaultWidgetInstance(
            objectMapper.writeValueAsString(actualViewConfig), canvas, widget);
    widgetInstanceList = new ArrayList<DefaultWidgetInstance>();
    widgetInstanceList.add(widgetInstance);

    canvas.setWidgetInstanceList(widgetInstanceList);
    auth =
        new UsernamePasswordAuthenticationToken(user, null, Arrays.asList(grantedAuthoritiesArr));
  }
コード例 #26
0
  private static Room mapStringToRoom(String roomValue, Position position, Grid tunnelMap) {
    RoomType type = Enum.valueOf(RoomType.class, "TYPE_" + roomValue.replace("-", ""));
    boolean rotatable = isNegativeType(roomValue) ? false : true;

    return new Room(type, position, rotatable, tunnelMap);
  }
コード例 #27
0
  public void getHelp(Caller caller, Workspace workspace, LinkedList<String> tokens) {

    WorkspaceService service = plugin.getWorkspaceService();
    String source = service.getWorkspaceName(caller.getSender());
    String firstToken = tokens.pollFirst();
    if (firstToken == null) firstToken = "";
    MetaClass callerScriptMetaClass = InvokerHelper.getMetaClass(CallerScript.class);
    MetaClass workspaceMetaClass = InvokerHelper.getMetaClass(Workspace.class);
    Map workspaceVars = null;
    if (workspace != null) workspaceVars = workspace.getBinding().getVariables();
    Map globalVars = service.getBinding().getVariables();
    PreparedScriptProperties properties = new PreparedScriptProperties();
    properties.setCaller(caller);
    properties.setServer(plugin.getServer());
    properties.setWorkspace(workspace);

    if (tokens.isEmpty()) { // get current method or class
      if (firstToken.equals("_")) {
        Object result = caller.getLastResult();
        String type = "null";
        if (result != null) type = result.getClass().getName();
        caller.sendPrintMessage("Last result: " + AQUA + type + RESET, source);
        return;
      }
      MetaProperty prop = callerScriptMetaClass.getMetaProperty(firstToken);
      if (prop != null) {
        caller.sendPrintMessage(
            String.format(
                "Script property %s: %s",
                YELLOW + prop.getName() + RESET, AQUA + prop.getType().getName() + RESET),
            source);
        return;
      }
      Class compClass = service.getImportTabCompleteClasses().get(firstToken);
      if (compClass != null) {
        String type = "Class";
        if (compClass.isInterface()) type = "Interface";
        else if (compClass.isEnum()) type = "Enum class";
        StringBuilder buf = new StringBuilder();
        Class superClass = compClass.getSuperclass();
        buf.append(type).append(" ").append(YELLOW).append(compClass.getName()).append(RESET);
        if (superClass != null) {
          buf.append(" extends ").append(AQUA).append(superClass.getName()).append(RESET);
        }
        caller.sendPrintMessage(buf, source);
        return;
      }
      for (MetaMethod metaMethod : callerScriptMetaClass.getMetaMethods()) {
        String name = metaMethod.getName();
        String methodEnd = "(";
        if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{";
        else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Script meta method ")
              .append(YELLOW)
              .append(metaMethod.getName())
              .append(RESET);
          buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = metaMethod.getNativeParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append('\n').append(RESET);
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
        int args = metaMethod.getParameterTypes().length;
        if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
            && name.length() > 3) {
          String propertyName = getPropertyName(name);
          if (propertyName != null && propertyName.equals(firstToken)) {
            caller.sendPrintMessage(
                String.format(
                    "Script meta getter %s returns %s",
                    YELLOW + name + "()" + RESET,
                    AQUA + metaMethod.getReturnType().getName() + RESET),
                source);
          }
        }
      }
      for (MetaMethod metaMethod : workspaceMetaClass.getMetaMethods()) {
        String name = metaMethod.getName();
        String methodEnd = "(";
        if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{";
        else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Workspace meta method ")
              .append(YELLOW)
              .append(metaMethod.getName())
              .append(RESET);
          buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = metaMethod.getNativeParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
      for (Method method : CallerScript.class.getMethods()) {
        String name = method.getName();
        String methodEnd = "(";
        Class<?>[] params = method.getParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Script method ").append(YELLOW).append(method.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
          buf.append(RESET).append('\n');
          buf.append("arguments: ").append(YELLOW).append(params.length).append(RESET).append('\n');
          for (Class<?> type : params)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
        int args = params.length;
        if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
            && name.length() > 3) {
          String propertyName = getPropertyName(name);
          if (propertyName != null && propertyName.equals(firstToken)) {
            caller.sendPrintMessage(
                String.format(
                    "Script getter %s returns %s",
                    YELLOW + name + "()" + RESET, AQUA + method.getReturnType().getName() + RESET),
                source);
          }
        }
      }
      for (Method method : Workspace.class.getMethods()) {
        String name = method.getName();
        String methodEnd = "(";
        Class<?>[] params = method.getParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Workspace method ").append(YELLOW).append(method.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
          buf.append(RESET).append('\n');
          buf.append("arguments: ").append(YELLOW).append(params.length).append(RESET).append('\n');
          for (Class<?> type : params)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
      if (workspaceVars != null) {
        Object result = workspaceVars.get(firstToken);
        if (result != null || workspaceVars.containsKey(firstToken)) {
          caller.sendPrintMessage(
              String.format(
                  "Workspace variable %s: %s",
                  YELLOW + firstToken + RESET,
                  AQUA + (result == null ? "null" : result.getClass().getName()) + RESET),
              source);
          return;
        }
      }
      if (globalVars != null) {
        Object result = globalVars.get(firstToken);
        if (result != null || globalVars.containsKey(firstToken)) {
          caller.sendPrintMessage(
              String.format(
                  "Workspace variable %s: %s",
                  YELLOW + firstToken + RESET,
                  AQUA + (result == null ? "null" : result.getClass().getName()) + RESET),
              source);
          return;
        }
      }
      for (GroovyObject modifier : CallerScript.getDynamicModifiers()) {
        Object[] params = {properties};
        try {
          Map<?, ?> map =
              (Map) modifier.getMetaClass().invokeMethod(modifier, "getPropertyMapFor", params);
          Object result = map.get(firstToken);
          if (result != null || map.containsKey(firstToken)) {
            Class resultClass = result instanceof Class ? (Class) result : null;
            caller.sendPrintMessage(
                String.format(
                    "Dynamic variable %s: %s",
                    YELLOW + firstToken + RESET,
                    AQUA + (resultClass == null ? "unknown type" : resultClass.getName()) + RESET),
                source);
          }
        } catch (Exception ignored) {
        }
        try {
          Map<?, ?> map =
              (Map) modifier.getMetaClass().invokeMethod(modifier, "getMethodMapFor", params);
          String funToken = firstToken;
          if (funToken.endsWith("(")) funToken = firstToken.substring(0, funToken.length() - 1);
          Object result = map.get(funToken);
          if (result != null || map.containsKey(funToken)) {
            Class resultClass = result instanceof Class ? (Class) result : null;
            caller.sendPrintMessage(
                String.format(
                    "Dynamic function %s: %s",
                    YELLOW + firstToken + RESET,
                    AQUA + (resultClass == null ? "unknown type" : resultClass.getName()) + RESET),
                source);
          }
        } catch (Exception ignored) {
        }
      }
      return;
    }

    MetaClass metaClass =
        getFirstTokenMeta(
            caller,
            firstToken,
            caller.getSender(),
            service,
            callerScriptMetaClass,
            workspaceMetaClass,
            workspace,
            workspaceVars,
            globalVars,
            properties);
    boolean classHook =
        tokens.size() <= 1 && service.getImportTabCompleteClasses().containsKey(firstToken);

    metaClass = skipTokens(tokens, metaClass);
    if (metaClass == null) return;

    // select property or method of last metaclass
    String token = tokens.pollFirst();
    Class theClass = metaClass.getTheClass();
    MetaProperty metaProperty = metaClass.getMetaProperty(token);
    if (metaProperty != null) {
      caller.sendPrintMessage(
          String.format(
              "Meta property %s: %s",
              YELLOW + token + RESET, AQUA + metaProperty.getType().getName() + RESET),
          source);
    }
    for (MetaMethod metaMethod : metaClass.getMetaMethods()) {
      String name = metaMethod.getName();
      String methodEnd = "(";
      Class<?>[] params = metaMethod.getNativeParameterTypes();
      if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
      else if (params.length == 0) methodEnd = "()";
      if (token.equals(name) || token.equals(name + methodEnd)) {
        StringBuilder buf = new StringBuilder();
        buf.append("Meta method ").append(YELLOW).append(metaMethod.getName()).append(RESET);
        buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
        buf.append(RESET).append('\n');
        Class[] types = metaMethod.getNativeParameterTypes();
        buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
        for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
        buf.deleteCharAt(buf.length() - 1);
        caller.sendPrintMessage(buf, source);
      }
      int args = params.length;
      if (name.startsWith("get") && args == 0 && name.length() > 3) {
        String propertyName = getPropertyName(name);
        if (propertyName != null && propertyName.equals(token)) {
          caller.sendPrintMessage(
              String.format(
                  "Meta getter %s returns %s",
                  YELLOW + name + "()" + RESET,
                  AQUA + metaMethod.getReturnType().getName() + RESET),
              source);
        }
      }
    }
    for (Method method : theClass.getMethods()) {
      String name = method.getName();
      String methodEnd = "(";
      Class<?>[] params = method.getParameterTypes();
      if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
      else if (params.length == 0) methodEnd = "()";
      if (token.equals(name) || token.equals(name + methodEnd)) {
        StringBuilder buf = new StringBuilder();
        buf.append("Method ").append(YELLOW).append(method.getName()).append(RESET);
        buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
        buf.append(RESET).append('\n');
        Class[] types = method.getParameterTypes();
        buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
        for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
        buf.deleteCharAt(buf.length() - 1);
        caller.sendPrintMessage(buf, source);
      }
      int args = params.length;
      if (name.startsWith("get") && args == 0 && name.length() > 3) {
        String propertyName = getPropertyName(name);
        if (propertyName != null && propertyName.equals(token)) {
          caller.sendPrintMessage(
              String.format(
                  "Getter %s returns %s",
                  YELLOW + name + "()" + RESET, AQUA + method.getReturnType().getName() + RESET),
              source);
        }
      }
    }
    if (Enum.class.isAssignableFrom(theClass)) {
      Enum[] enumValues = getEnumValues(theClass);
      if (enumValues != null)
        for (Enum anEnum : enumValues) {
          String name = anEnum.name();
          if (name.equals(token)) {
            caller.sendPrintMessage(
                String.format(
                    "Enum value %s: %s", YELLOW + name + RESET, AQUA + theClass.getName() + RESET),
                source);
          }
        }
    }
    if (classHook) {
      MetaProperty property = InvokerHelper.getMetaClass(Class.class).getMetaProperty(token);
      if (property != null) {
        caller.sendPrintMessage(
            String.format(
                "Meta property %s: %s",
                YELLOW + token + RESET, AQUA + property.getType().getName() + RESET),
            source);
      }
      for (MetaMethod metaMethod : InvokerHelper.getMetaClass(Class.class).getMetaMethods()) {
        String name = metaMethod.getName();
        String methodEnd = "(";
        Class<?>[] params = metaMethod.getNativeParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Method ").append(YELLOW).append(metaMethod.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = metaMethod.getNativeParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
      for (Method method : Class.class.getMethods()) {
        String name = method.getName();
        String methodEnd = "(";
        Class<?>[] params = method.getParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Method ").append(YELLOW).append(method.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = method.getParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
    }
  }
コード例 #28
0
ファイル: DefaultQueryConf.java プロジェクト: tivv/esorm
 public <T extends Enum<T>> T getSelected(Class<T> clazz) {
   Default d = clazz.getAnnotation(Default.class);
   return d != null
       ? Enum.<T>valueOf(clazz, d.value())
       : clazz.getAnnotation(FirstIsDefault.class) != null ? clazz.getEnumConstants()[0] : null;
 }
コード例 #29
0
  /** Reads the attributes from the specified DOMInput and assigns them to the figure. */
  public static void readAttributes(Figure f, DOMInput in) throws IOException {
    // FIXME - This method is not working, when "style" and individual attributes
    // are both used in an SVG document.
    List<Map<String, String>> styles = new ArrayList<Map<String, String>>();
    List<String> values = in.getInheritedAttribute("style");
    for (String v : values) {
      styles.add(getStyles(v));
    }
    String value;

    // Fill color
    value = getInheritedAttribute("fill", in, styles);
    if (value != null) {
      Color color = getColor(value);
      if (color != INHERIT_COLOR && color != CURRENT_COLOR) {
        FILL_COLOR.set(f, color);
      }
    }
    value = getInheritedAttribute("fill-rule", in, styles);
    if (value != null) {
      WINDING_RULE.set(
          f, value.toUpperCase().equals("NONZERO") ? WindingRule.NON_ZERO : WindingRule.EVEN_ODD);
    } else {
      WINDING_RULE.set(f, WindingRule.NON_ZERO);
    }

    // Stroke color
    value = getInheritedAttribute("stroke", in, styles);
    if (value != null) {
      Color color = getColor(value);
      if (color != INHERIT_COLOR && color != CURRENT_COLOR) {
        STROKE_COLOR.set(f, color);
      }
    }

    value = getInheritedAttribute("stroke-width", in, styles);
    if (value != null) {
      STROKE_WIDTH.set(f, Double.valueOf(value));
    }
    value = getInheritedAttribute("stroke-miterlimit", in, styles);
    if (value != null) {
      STROKE_MITER_LIMIT_FACTOR.set(f, Double.valueOf(value));
    }
    value = getInheritedAttribute("stroke-dasharray", in, styles);
    if (value != null) {
      StringTokenizer tt = new StringTokenizer(value, " ,");
      double[] dashes = new double[tt.countTokens()];
      for (int i = 0, n = dashes.length; i < n; i++) {
        dashes[i] = Double.valueOf(tt.nextToken());
      }
      STROKE_DASHES.set(f, dashes);
    }
    value = getInheritedAttribute("stroke-dashoffset", in, styles);
    if (value != null) {
      STROKE_DASH_PHASE.set(f, Math.abs(Double.valueOf(value)));
    }
    value = getInheritedAttribute("font-size", in, styles);
    if (value != null) {
      FONT_SIZE.set(f, getDimensionValue(in, value));
    }
    value = getInheritedAttribute("text-anchor", in, styles);
    if (value != null) {
      SVGText.TEXT_ANCHOR.set(f, Enum.valueOf(SVGText.TextAnchor.class, value.toUpperCase()));
    }
  }
コード例 #30
0
 /** {@inheritDoc} */
 @Override
 public synchronized Counter findCounter(Enum<?> key) {
   return findCounter(key.getDeclaringClass().getName(), key.name(), true);
 }