Example #1
1
  protected static <T extends Enum<T>> T parseEnum(
      Class<T> enumClass, String name, T defaultValue, Pair<String, T>... additionalPairs) {
    if (name == null) {
      return defaultValue;
    }

    name = name.toLowerCase();
    for (T enumConstant : enumClass.getEnumConstants()) {
      if (enumConstant.name().equalsIgnoreCase(name)) {
        return enumConstant;
      }
    }
    for (T enumConstant : enumClass.getEnumConstants()) {
      if (enumConstant.name().toLowerCase().startsWith(name)) {
        return enumConstant;
      }
    }

    for (Pair<String, T> additional : additionalPairs) {
      if (additional.first().equalsIgnoreCase(name)) {
        return additional.other();
      }
    }
    for (Pair<String, T> additional : additionalPairs) {
      if (additional.first().toLowerCase().startsWith(name)) {
        return additional.other();
      }
    }

    throw new IllegalArgumentException("No '" + name + "' or '" + name + ".*' in " + enumClass);
  }
Example #2
1
 public void addMaterials(Class<?> c) {
   if (!c.isEnum()) return;
   if (!(c.getEnumConstants() instanceof Material[])) return;
   Material[] ms = (Material[]) c.getEnumConstants();
   for (Material m : ms) {
     materials.put(m.getSymbol(), m);
   }
 }
 public JSSPopupPropertyDescriptor(
     Object id, String displayName, Class<? extends JREnum> jrEnum, NullEnum type) {
   super(id, displayName, EnumHelper.getEnumNames(jrEnum.getEnumConstants(), type));
   this.type = type;
   jrEnums = jrEnum.getEnumConstants();
   this.start = jrEnums[0].getValue();
   setItemsToDefault();
 }
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static void enterA2Mode() {
    System.err.println("APV::enterA2Mode");
    try {
      Class epdControllerClass = Class.forName("android.hardware.EpdController");
      Class epdControllerRegionClass = Class.forName("android.hardware.EpdController$Region");
      Class epdControllerRegionParamsClass =
          Class.forName("android.hardware.EpdController$RegionParams");
      Class epdControllerWaveClass = Class.forName("android.hardware.EpdController$Wave");

      Object[] waveEnums = null;
      if (epdControllerWaveClass.isEnum()) {
        System.err.println("EpdController Wave Enum successfully retrived.");
        waveEnums = epdControllerWaveClass.getEnumConstants();
      }

      Object[] regionEnums = null;
      if (epdControllerRegionClass.isEnum()) {
        System.err.println("EpdController Region Enum successfully retrived.");
        regionEnums = epdControllerRegionClass.getEnumConstants();
      }

      Constructor RegionParamsConstructor =
          epdControllerRegionParamsClass.getConstructor(
              new Class[] {
                Integer.TYPE,
                Integer.TYPE,
                Integer.TYPE,
                Integer.TYPE,
                epdControllerWaveClass,
                Integer.TYPE
              });

      Object localRegionParams =
          RegionParamsConstructor.newInstance(
              new Object[] {0, 0, 600, 800, waveEnums[2], 16}); // Wave = DU

      Method epdControllerSetRegionMethod =
          epdControllerClass.getMethod(
              "setRegion",
              new Class[] {String.class, epdControllerRegionClass, epdControllerRegionParamsClass});
      epdControllerSetRegionMethod.invoke(
          null, new Object[] {"APV-ReadingView", regionEnums[2], localRegionParams});

      Thread.sleep(100L);
      localRegionParams =
          RegionParamsConstructor.newInstance(
              new Object[] {0, 0, 600, 800, waveEnums[3], 14}); // Wave = A2
      epdControllerSetRegionMethod.invoke(
          null, new Object[] {"APV-ReadingView", regionEnums[2], localRegionParams});

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public JSSPopupPropertyDescriptor(
     Object id,
     String displayName,
     Class<? extends JREnum> jrEnum,
     NullEnum type,
     List<ComboItem> items) {
   super(id, displayName, EnumHelper.getEnumNames(jrEnum.getEnumConstants(), type));
   jrEnums = jrEnum.getEnumConstants();
   this.start = jrEnums[0].getValue();
   this.items = items;
 }
Example #6
1
  /**
   * Get the enum value with the passed ID
   *
   * @param <ENUMTYPE> The enum type
   * @param aClass The enum class
   * @param nID The ID to search
   * @param aDefault The default value to be returned, if the ID was not found.
   * @return The default parameter if no enum item with the given ID is present.
   */
  @Nullable
  public static <ENUMTYPE extends Enum<ENUMTYPE> & IHasSimpleIntID> ENUMTYPE getFromIDOrDefault(
      @Nonnull final Class<ENUMTYPE> aClass, final int nID, @Nullable final ENUMTYPE aDefault) {
    ValueEnforcer.notNull(aClass, "Class");

    final String sCacheKey = aClass.getName();
    Object[] aCachedData;
    s_aRWLockInt.readLock().lock();
    try {
      aCachedData = s_aIntCache.get(sCacheKey);
    } finally {
      s_aRWLockInt.readLock().unlock();
    }
    if (aCachedData == null) {
      s_aRWLockInt.writeLock().lock();
      try {
        // Try again in write lock
        aCachedData = s_aIntCache.get(sCacheKey);
        if (aCachedData == null) {
          // Create new cache entry
          int nMinID = Integer.MAX_VALUE;
          int nMaxID = Integer.MIN_VALUE;
          for (final ENUMTYPE aElement : aClass.getEnumConstants()) {
            final int nElementID = aElement.getID();
            if (nElementID < nMinID) nMinID = nElementID;
            if (nElementID > nMaxID) nMaxID = nElementID;
          }
          if (nMinID >= 0 && nMaxID <= CGlobal.MAX_BYTE_VALUE) {
            // Cachable!
            aCachedData = new Object[nMaxID + 1];
            for (final ENUMTYPE aElement : aClass.getEnumConstants())
              aCachedData[aElement.getID()] = aElement;
          } else {
            // Enum not cachable
            aCachedData = NOT_CACHABLE;
          }
          s_aIntCache.put(sCacheKey, aCachedData);
        }
      } finally {
        s_aRWLockInt.writeLock().unlock();
      }
    }

    if (aCachedData != NOT_CACHABLE) {
      if (nID < 0 || nID >= aCachedData.length) return aDefault;
      return GenericReflection.<Object, ENUMTYPE>uncheckedCast(aCachedData[nID]);
    }

    // Object is not cachable - traverse as ususal
    for (final ENUMTYPE aElement : aClass.getEnumConstants())
      if (aElement.getID() == nID) return aElement;
    return aDefault;
  }
Example #7
0
  @SuppressWarnings("rawtypes")
  @Override
  public Map<Integer, String> convertAlias(final Alias alias, final FrameworkWorkspace workspace) {
    final Map<Integer, String> map = new HashMap<>();

    // Get enumeration
    final Class<? extends Enum> enumeration =
        FrameworkServiceImpl.getEntityService().requestEnum(alias.target().get());

    for (int i = 0; i < enumeration.getEnumConstants().length; ++i)
      map.put(i, enumeration.getEnumConstants()[i].name());

    return map;
  }
Example #8
0
  public static <T extends Enum> T toEnum(Class<T> cls, String value, Enum defaultEnum) {

    T[] enumConstants = cls.getEnumConstants();
    for (T e : enumConstants) {
      if (e.name().equals(value)) {
        return e;
      }
    }

    value = value.toUpperCase().replace('-', '_');
    for (T e : enumConstants) {
      if (e.name().equals(value)) {
        return e;
      }
    }

    value = Str.underBarCase(value);
    for (T e : enumConstants) {
      if (e.name().equals(value)) {
        return e;
      }
    }

    return (T) defaultEnum;
  }
  private static int putEnumTypeInHash(Class<?> type, Hashtable<String, Class<?>> enums) {
    Class<?> flagsType = QFlags.class.isAssignableFrom(type) ? type : null;
    Class<?> enumType = type.isEnum() ? type : null;
    if (enumType == null && flagsType != null) {
      enumType = getEnumForQFlags(flagsType);
    }

    if (enumType == null) return 0;

    // Since Qt supports enums that are not part of the meta object
    // we need to check whether the enum can actually be used in
    // a property.
    Class<?> enclosingClass = enumType.getEnclosingClass();
    if (enclosingClass != null
        && ((!QObject.class.isAssignableFrom(enclosingClass) && !Qt.class.equals(enclosingClass))
            || enumType.isAnnotationPresent(QtBlockedEnum.class))) {
      return -1;
    }

    int enumConstantCount = 0;
    if (!enums.contains(enumType.getName())) {
      enums.put(enumType.getName(), enumType);

      enumConstantCount = enumType.getEnumConstants().length;
    }

    if (flagsType != null && !enums.contains(flagsType.getName()))
      enums.put(flagsType.getName(), flagsType);

    return enumConstantCount;
  }
Example #10
0
  public static <E extends Enum<E>> E valueOf(Class<E> c, String name, boolean ignorecase) {
    // trim any leading or trailing spaces from the name
    name = name.trim();

    if (!ignorecase) {
      {
        return Enum.<E>valueOf(c, name);
      }
    }

    E[] universe = c.getEnumConstants();
    if (universe == null) {
      throw new IllegalArgumentException(name + " is not an enum type");
    }

    Map<String, E> map = cacheEnumValuesInCapitalLetters.get(c);

    if (map == null) {
      // populate the map with enum values and add it to cache
      map = new HashMap<String, E>(2 * universe.length);

      for (E e : universe) {
        map.put(e.name().toUpperCase(), e);
      }
      cacheEnumValuesInCapitalLetters.put(c, map);
    }

    E result = map.get(name.toUpperCase());
    if (result == null) {
      throw new IllegalArgumentException("No enum const " + c.getName() + "." + name);
    }
    return result;
  }
  @SuppressWarnings("rawtypes")
  public static FieldMapper getMapperForClass(final Class clazz) {
    FieldMapper fieldMapper = register.get(clazz);

    if (fieldMapper == null) {

      // check if there is a global field mapper defined in the value transformer register:
      final ValueTransformer<?, ?> valueTransformer =
          GlobalValueTransformerRegistry.getValueTransformerForClass(clazz);
      if (valueTransformer != null) {
        fieldMapper = new ValueTransformerFieldMapper(valueTransformer);
        register.put(clazz, fieldMapper);
      }
    }

    if (fieldMapper == null) {
      if (clazz.getEnumConstants() != null) {
        fieldMapper = register.get(Enum.class);
      }
    }

    if (fieldMapper == null) {
      fieldMapper = NULL_FIELD_MAPPER;
    }

    return fieldMapper;
  }
 /**
  * 获取枚举的所有属性
  *
  * @param clazz
  * @return
  */
 public static IEnum[] getEnums(Class<?> clazz) {
   if (IEnum.class.isAssignableFrom(clazz)) {
     Object[] enumConstants = clazz.getEnumConstants();
     return (IEnum[]) enumConstants;
   }
   return null;
 }
Example #13
0
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

      @SuppressWarnings("unchecked")
      Class<T> rawType = (Class<T>) type.getRawType();
      if (!rawType.isEnum()) {
        return null;
      }

      final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
      for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
      }

      return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
          if (value == null) {
            out.nullValue();
          } else {
            out.value(toLowercase(value));
          }
        }

        public T read(JsonReader reader) throws IOException {
          if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
          } else {
            return lowercaseToConstant.get(reader.nextString());
          }
        }
      };
    }
Example #14
0
  private Map<String, List<Object>> loadContextDatabase() {
    // context DB 생
    Map<String, List<Object>> contextMap = new HashMap<String, List<Object>>();

    log.d("pakage is " + pakagename);
    List<Class<?>> classlist = getFilterClasses(pakagename, ContextSchemable.class);

    try {
      ContextSchemable schemable;

      for (Class<?> clazz : classlist) {
        if (clazz.isEnum()) {
          // enum 타입
          schemable = (ContextSchemable) clazz.getEnumConstants()[0];
          //					log.d("Type of enum: "+clazz.getSimpleName());
        } else {
          // 그외 interface 타입
          schemable = (ContextSchemable) clazz.newInstance();
          //					log.d("Type of class: "+clazz.getSimpleName());
        }

        List<Object> list = schemable.getContextSchemaData();
        if (list != null) {
          contextMap.put(schemable.getClass().getSimpleName(), list);
        }
      }
    } catch (InstantiationException e) {
      log.e(e.getMessage());
    } catch (IllegalAccessException e) {
      log.e(e.getMessage());
    }
    return contextMap;
  }
 private Object sample(Class<?> type) {
   if (type.isPrimitive()) {
     if (type == long.class) {
       return random.nextLong();
     }
     if (type == boolean.class) {
       return random.nextBoolean();
     }
   } else if (type.isEnum()) {
     Object[] candidates = type.getEnumConstants();
     return candidates[random.nextInt(candidates.length)];
   } else if (!type.isArray()) {
     if (type == String.class) {
       StringBuilder result = new StringBuilder();
       for (int len = 5 + random.nextInt(10); len > 0; len--) {
         result.append('a' + random.nextInt('z' - 'a'));
       }
       return result.toString();
     }
     if (type == Long.class) {
       return random.nextLong();
     }
     return mock(type);
   }
   throw new UnsupportedOperationException(
       "doesn't support " + type + " please add support for it.");
 }
 public a(Class cls) {
   this.a = new HashMap();
   this.b = new HashMap();
   try {
     Enum[] enumArr = (Enum[]) cls.getEnumConstants();
     int length = enumArr.length;
     int i = 0;
     while (i < length) {
       Object a;
       Enum enumR = enumArr[i];
       String name = enumR.name();
       com.google.ads.interactivemedia.v3.a.a.b bVar =
           (com.google.ads.interactivemedia.v3.a.a.b)
               cls.getField(name).getAnnotation(com.google.ads.interactivemedia.v3.a.a.b.class);
       if (bVar != null) {
         a = bVar.a();
       } else {
         String str = name;
       }
       this.a.put(a, enumR);
       this.b.put(enumR, a);
       i++;
     }
   } catch (NoSuchFieldException e) {
     throw new AssertionError();
   }
 }
Example #17
0
 /**
  * Tries to convert a string value to a data type given as a parameter. There are few cases, that
  * can occure.
  *
  * <ol>
  *   <li>Given value is null or an empty string. In such case the null is also returned.
  *   <li>Defined class is a java primitive like int, double etc. For these instances the object
  *       representation is returned. It means that for int it returns Integer, for double Double
  *       etc.
  *   <li>Value is well-known object primitive, like Integer, Date etc. In these cases the string
  *       is parsed into given object and returned.
  *   <li>Defined class is complex. In such cases the original string value is returned because
  *       there is not known converter.
  * </ol>
  *
  * <p>Note: When the given class is inherited from some java primitive then the returned object is
  * that primitive type. For example this can occure for {@link java.sql.Date} which inherits from
  * {@link java.util.Date}
  *
  * @param <T> desired type to be converted to
  * @param value string representation of converted value
  * @param type target class of the value
  * @return converted value if the conversion is defined
  * @throws ParseException this occures when the date is in bad format. The format can be redefined
  *     in {@link #dateFormat}.
  * @throws NumberFormatException conversion of string to number has failed. It occures when the
  *     input string is not a number but the target class is.
  */
 public static <T> Object tryToConvertTo(final String value, final Class<T> type)
     throws ParseException, NumberFormatException {
   if (value == null || "".equals(value)) {
     return null;
   }
   if (java.util.Date.class.isAssignableFrom(type)) {
     return (java.util.Date)
         (new java.text.SimpleDateFormat(dateFormat, java.util.Locale.getDefault()).parse(value));
   } else if (String.class.isAssignableFrom(type)) {
     return type.cast(value);
   } else if (Integer.class.isAssignableFrom(type) || Integer.TYPE.equals(type)) {
     return Integer.valueOf(value);
   } else if (Double.class.isAssignableFrom(type) || Double.TYPE.equals(type)) {
     return Double.valueOf(value);
   } else if (Long.class.isAssignableFrom(type) || Long.TYPE.equals(type)) {
     return Long.valueOf(value);
   } else if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE.equals(type)) {
     return (BooleanHelper.isTrue(value) ? Boolean.TRUE : (Boolean.valueOf(value)));
   } else if (Byte.class.isAssignableFrom(type) || Byte.TYPE.equals(type)) {
     return Byte.valueOf(value);
   } else if (type.isEnum()) {
     for (T enumValue : type.getEnumConstants()) {
       if (enumValue.toString().equals(value)) {
         return enumValue;
       }
     }
     return null;
   } else {
     return value;
   }
 }
 @Override
 public void execute(OperationContext context, ModelNode operation)
     throws OperationFailedException {
   PathAddress address =
       context.getCurrentAddress().append(BinaryTableResourceDefinition.PATH);
   ModelNode table = Operations.getAttributeValue(operation);
   for (Class<? extends org.jboss.as.clustering.controller.Attribute> attributeClass :
       Arrays.asList(
           BinaryTableResourceDefinition.Attribute.class,
           TableResourceDefinition.Attribute.class)) {
     for (org.jboss.as.clustering.controller.Attribute attribute :
         attributeClass.getEnumConstants()) {
       ModelNode writeAttributeOperation =
           Operations.createWriteAttributeOperation(
               address, attribute, table.get(attribute.getDefinition().getName()));
       context.addStep(
           writeAttributeOperation,
           context
               .getResourceRegistration()
               .getAttributeAccess(
                   PathAddress.pathAddress(BinaryTableResourceDefinition.PATH),
                   attribute.getDefinition().getName())
               .getWriteHandler(),
           context.getCurrentStage());
     }
   }
 }
Example #19
0
  TitleUtil()
      throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
          InstantiationException, NoSuchFieldException {
    String name = Bukkit.getServer().getClass().getPackage().getName();
    String version = name.substring(name.lastIndexOf('.') + 1) + ".";

    // Common classpaths
    NMS = "net.minecraft.server." + version;
    CB = "org.bukkit.craftbukkit." + version;

    // Classes being used
    CB_CRAFTPLAYER = (Class<? extends Player>) Class.forName(CB + "entity.CraftPlayer");
    NMS_ENTITY_PLAYER = Class.forName(NMS + "EntityPlayer");
    NMS_PLAYER_CONN = Class.forName(NMS + "PlayerConnection");
    NMS_ICHAT_BASE = Class.forName(NMS + "IChatBaseComponent");
    NMS_PACKET = Class.forName(NMS + "Packet");
    NMS_PACKET_PLAY_TITLE = Class.forName(NMS + "PacketPlayOutTitle");
    NMS_TITLE_ACTION =
        (Class<? extends Enum>) Class.forName(NMS + "PacketPlayOutTitle$EnumTitleAction");
    NMS_CHAT_SERIALIZER = Class.forName(NMS + "IChatBaseComponent$ChatSerializer");

    // Methods being used
    GET_HANDLE = CB_CRAFTPLAYER.getMethod("getHandle");
    SEND_PACKET = NMS_PLAYER_CONN.getMethod("sendPacket", NMS_PACKET);
    ICHAT_A = NMS_CHAT_SERIALIZER.getMethod("a", String.class);

    // Fields being used
    PLAYER_CONN = NMS_ENTITY_PLAYER.getDeclaredField("playerConnection");

    // Title action array
    ACTION_ARRAY = NMS_TITLE_ACTION.getEnumConstants();
  }
 static void init() {
   try {
     awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
     translucencyClass = Class.forName("com.sun.awt.AWTUtilities$Translucency");
     if (translucencyClass.isEnum()) {
       Object[] kinds = translucencyClass.getEnumConstants();
       if (kinds != null) {
         PERPIXEL_TRANSPARENT = kinds[0];
         TRANSLUCENT = kinds[1];
         PERPIXEL_TRANSLUCENT = kinds[2];
       }
     }
     mIsTranslucencySupported =
         awtUtilitiesClass.getMethod("isTranslucencySupported", translucencyClass);
     mIsTranslucencyCapable =
         awtUtilitiesClass.getMethod("isTranslucencyCapable", GraphicsConfiguration.class);
     mSetWindowShape = awtUtilitiesClass.getMethod("setWindowShape", Window.class, Shape.class);
     mSetWindowOpacity =
         awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
     mSetWindowOpaque =
         awtUtilitiesClass.getMethod("setWindowOpaque", Window.class, boolean.class);
   } catch (NoSuchMethodException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   } catch (SecurityException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   } catch (ClassNotFoundException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
Example #21
0
 private static List<String> getEnumValues(Class<?> type) {
   List<String> result = new ArrayList<String>();
   for (Object constant : type.getEnumConstants()) {
     result.add(constant.toString());
   }
   return result;
 }
  public void init(Model model) {
    javaAnnotationClass = ReflectionUtil.loadClass(type);
    if (javaAnnotationClass == null) {
      logger.warn("Cannot load annotation class: {}", type);
      return;
    }

    AnnotationsManager annotationsManager = AnnotationsManager.getManager();

    Class annotationImplClass =
        annotationsManager.getAnnotationImplementationClass(javaAnnotationClass);
    if (annotationImplClass == null) {
      logger.warn("Cannot find implementation for annotation class: {}", javaAnnotationClass);
      return;
    }

    Constructor[] constructors = annotationImplClass.getConstructors();
    for (Constructor candidateConstructor : constructors) {
      Class[] parameterTypes = candidateConstructor.getParameterTypes();
      if (parameterTypes.length != values.size()) {
        continue;
      }

      try {
        Object castValues[] = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
          Class parameterType = parameterTypes[i];
          String stringValue = values.get(i);
          Object value;
          if (parameterType.isArray()) {
            value = Util.matchStringArray(stringValue);
          } else if (parameterType.isEnum()) {
            Object[] enumValues = parameterType.getEnumConstants();
            value = stringValue;
            for (Object current : enumValues) {
              Enum enumValue = (Enum) current;
              if (enumValue.name().equals(stringValue)) {
                value = enumValue;
                break;
              }
            }
          } else {
            value = stringValue;
          }
          castValues[i] = OgnlUtils.convertValue(value, parameterType);
        }

        javaAnnotation =
            (java.lang.annotation.Annotation)
                ReflectionUtil.newInstance(candidateConstructor, castValues);
      } catch (Throwable e) {
        logger.debug("Failed to use constructor: " + candidateConstructor, e);
      }
    }

    if (javaAnnotation == null) {
      logger.warn("Cannot instanciate annotation: {}", javaAnnotationClass);
    }
  }
 public void apply()
     throws IllegalAccessException, InvocationTargetException, InstantiationException {
   if (type.isEnum()) {
     for (T instance : type.getEnumConstants()) {
       assertThat(
           instance.toString(),
           is(
               type.getCanonicalName().substring(type.getPackage().getName().length() + 1)
                   + "."
                   + ((Enum<?>) instance).name()));
     }
     return;
   }
   for (Constructor<?> constructor : type.getDeclaredConstructors()) {
     if (constructor.isSynthetic() && skipSynthetic) {
       continue;
     }
     constructor.setAccessible(true);
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     Object[] actualArguments = new Object[parameterTypes.length];
     Object[] otherArguments = new Object[parameterTypes.length];
     int index = 0;
     for (Class<?> parameterType : parameterTypes) {
       putInstance(parameterType, actualArguments, otherArguments, index++);
     }
     int testIndex = 0;
     @SuppressWarnings("unchecked")
     T instance = (T) constructor.newInstance(actualArguments);
     assertThat(instance, is(instance));
     assertThat(instance, not(is((Object) null)));
     assertThat(instance, not(is(new Object())));
     Object similarInstance = constructor.newInstance(actualArguments);
     assertThat(instance.hashCode(), is(similarInstance.hashCode()));
     assertThat(instance, is(similarInstance));
     if (skipToString) {
       assertThat(instance.toString(), notNullValue());
     } else if (optionalToStringRegex == null) {
       checkString(instance);
     } else {
       assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex));
     }
     for (Object otherArgument : otherArguments) {
       Object[] compareArguments = new Object[actualArguments.length];
       int argumentIndex = 0;
       for (Object actualArgument : actualArguments) {
         if (argumentIndex == testIndex) {
           compareArguments[argumentIndex] = otherArgument;
         } else {
           compareArguments[argumentIndex] = actualArgument;
         }
         argumentIndex++;
       }
       Object unlikeInstance = constructor.newInstance(compareArguments);
       assertThat(instance.hashCode(), not(is(unlikeInstance)));
       assertThat(instance, not(is(unlikeInstance)));
       testIndex++;
     }
   }
 }
Example #24
0
  public NamedPattern(String pattern, Class<E> groupEnum) {
    if (pattern == null) {
      throw new IllegalArgumentException("pattern cannot be null");
    }
    if (groupEnum == null) {
      throw new IllegalArgumentException("groupEnum cannot be null");
    }

    _patternAsString = pattern;

    pattern = pattern.replaceAll("\\(", "\\\\(");
    pattern = pattern.replaceAll("\\)", "\\\\)");
    pattern = pattern.replaceAll("\\[", "\\\\[");
    pattern = pattern.replaceAll("\\]", "\\\\]");

    this.groupEnum = groupEnum;

    groupIndexes = new EnumMap<E, Integer>(groupEnum);

    E[] availableGroupNames = groupEnum.getEnumConstants();

    List<E> usedGroupNames = new ArrayList<E>();
    List<Integer> groupNameStringIndexOfs = new ArrayList<Integer>();

    for (int i = 0; i < availableGroupNames.length; i++) {
      E group = availableGroupNames[i];
      String groupToken = getGroupToken(group);

      int indexOf = pattern.indexOf(groupToken);
      if (indexOf != -1) {
        usedGroupNames.add(group);
        groupNameStringIndexOfs.add(indexOf);
      }
    }

    if (usedGroupNames.isEmpty()) {
      throw new IllegalArgumentException(
          "None of the groups defined in "
              + groupEnum.getSimpleName()
              + " where found in the pattern: "
              + pattern);
    }

    Integer groupIndex = getIndexOfHighest(groupNameStringIndexOfs);
    while (groupIndex != null) {

      E group = usedGroupNames.remove(groupIndex.intValue());
      groupNameStringIndexOfs.remove(groupIndex.intValue());

      groupIndexes.put(group, usedGroupNames.size() + 1);

      pattern = pattern.replace(getGroupToken(group), getGroupLiteral(group));

      groupIndex = getIndexOfHighest(groupNameStringIndexOfs);
    }

    logger.info("compiling pattern: {}", pattern);
    this.pattern = Pattern.compile(pattern);
  }
Example #25
0
  public static void main(String[] args) throws NoSuchFieldException, SecurityException {
    Class clazz = UserType.class;

    Object[] objs = clazz.getEnumConstants();
    for (Object obj : objs) {
      System.out.println(obj.getClass().getDeclaredField("code"));
    }
  }
 public static void addEnumValues(Class<?> theClass, Builder builder) {
   if (theClass.isEnum()) {
     Object[] enumConstants = theClass.getEnumConstants();
     for (Object object : enumConstants) {
       builder.option(object.toString(), object.toString());
     }
   }
 }
Example #27
0
 /**
  * Determines if the passed name is a valid enum collector name for the passed enum collector
  * class. The name will be trimmed and matched ignoring case.
  *
  * @param clazz The enum collector class
  * @param name The name to test
  * @return true for match, false otherwise
  */
 public boolean isMemberName(Class<T> clazz, CharSequence name) {
   if (name == null || name.toString().trim().isEmpty()) return false;
   String _name = name.toString().trim();
   for (T t : clazz.getEnumConstants()) {
     if (_name.equalsIgnoreCase(t.name())) return true;
   }
   return false;
 }
Example #28
0
 /**
  * Returns the member for the passed enum collector class that has a name match with the passed
  * name
  *
  * @param clazz The enum collector class
  * @param name The name of the member to get
  * @return the matching member or null if no match was made
  */
 public T getMember(Class<T> clazz, CharSequence name) {
   if (name == null || name.toString().trim().isEmpty()) return null;
   String _name = name.toString().trim();
   for (T t : clazz.getEnumConstants()) {
     if (_name.equalsIgnoreCase(t.name())) return t;
   }
   return null;
 }
Example #29
0
  /**
   * @param num
   * @param enumType
   * @return
   */
  public static Enum toEnum(Number num, Class<? extends Enum> enumType) {
    try {
      return enumType.getEnumConstants()[num.intValue()];

    } catch (Exception e) {
      return null;
    }
  }
Example #30
0
 public static void main(String[] args) {
   Class<Integer> intClass = Integer.class;
   try {
     for (Object en : intClass.getEnumConstants()) System.out.println(en);
   } catch (Exception e) {
     System.out.println(e);
   }
 }