static List<ListenerMethod> getListenerMethods(ListenerClass listener) { if (listener.method().length == 1) { return Arrays.asList(listener.method()); } try { List<ListenerMethod> methods = new ArrayList<ListenerMethod>(); Class<? extends Enum<?>> callbacks = listener.callbacks(); for (Enum<?> callbackMethod : callbacks.getEnumConstants()) { Field callbackField = callbacks.getField(callbackMethod.name()); ListenerMethod method = callbackField.getAnnotation(ListenerMethod.class); if (method == null) { throw new IllegalStateException( String.format( "@%s's %s.%s missing @%s annotation.", callbacks.getEnclosingClass().getSimpleName(), callbacks.getSimpleName(), callbackMethod.name(), ListenerMethod.class.getSimpleName())); } methods.add(method); } return methods; } catch (NoSuchFieldException e) { throw new AssertionError(e); } }
protected TaskModel( LocalTask inputTask, ComboBox<UserActionOutputResponse> userActionOutputResponseComboBox, Enum<? extends Enum<?>>[] enumValues) { this(inputTask, userActionOutputResponseComboBox); for (Enum<?> en : enumValues) { addOutputVariable(en.name()); initializeOutputVariableInputNode(en.name()); } }
@Override protected void setup() throws Throwable { // The enum used for titles titleEnumClass = getTitleEnumClass(); // Get the title enum values. for (Object o : titleEnumClass.getEnumConstants()) { Enum<?> e = (Enum<?>) o; if (e.name().equalsIgnoreCase("TITLE")) titleMainEnum = e; else if (e.name().equalsIgnoreCase("SUBTITLE")) titleSubEnum = e; else if (e.name().equalsIgnoreCase("TIMES")) titleTimesEnum = e; } // Get chatserializer and chat component. iChatBaseComponent = PackageType.MINECRAFT_SERVER.getClass("IChatBaseComponent"); chatSerializer = getChatSerializer(); // Get title packet and it's constructor Class<?> titlePacketClass = PackageType.MINECRAFT_SERVER.getClass("PacketPlayOutTitle"); titlePacketConstructor = ReflectionUtils.getConstructor(titlePacketClass, titleEnumClass, iChatBaseComponent); titlePacketConstructorTimes = ReflectionUtils.getConstructor( titlePacketClass, titleEnumClass, iChatBaseComponent, Integer.class, Integer.class, Integer.class); // Get Chat packet and it's constructor Class<?> chatPacketClass = PackageType.MINECRAFT_SERVER.getClass("PacketPlayOutChat"); chatPacketConstructor = ReflectionUtils.getConstructor(chatPacketClass, iChatBaseComponent); chatPacketActionbarConstructor = ReflectionUtils.getConstructor(chatPacketClass, iChatBaseComponent, Byte.TYPE); // Player connection getHandle = ReflectionUtils.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); playerConnection = ReflectionUtils.getField( "EntityPlayer", PackageType.MINECRAFT_SERVER, false, "playerConnection"); sendPacket = ReflectionUtils.getMethod( playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet")); // Set accessible setAllAccessible(); }
/** * Notifies all the observers with the eventtype selected from the class that fires the event. * * @param eventType * @param data */ @Override public void notifyObservers(Enum event, Dto data) { Logger.getLogger(ApplicationConfig.class.getName()) .log(Level.INFO, "Notifying observers " + event.name()); synchronized (syncedList) { for (int i = 0; i < syncedList.size(); i++) { try { syncedList.get(i).update(new NegodEvent(event, data)); } catch (Exception e) { Logger.getLogger(ApplicationConfig.class.getName()) .log(Level.WARNING, "Failed to notify: " + event.name()); } } } }
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; }
/** * Instrospect an Enum and serialize it as a name/value pair or as a bean including all its own * properties */ private void enumeration(Enum enumeration) throws JSONException { if (enumAsBean) { this.bean(enumeration); } else { this.string(enumeration.name()); } }
@Override Enum<?> handle(String s) throws ValidationException { for (Enum<?> o : cz.getEnumConstants()) { if (o.name().equals(s)) return o; } throw new ValidationException(s + " not member of enumeration " + cz.getSimpleName()); }
/** * 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; }
/** * 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); }
@Override public ObjectMapper get() { final ObjectMapper mapper = new ObjectMapper(jsonFactory); // Set the features for (Map.Entry<Enum<?>, Boolean> entry : featureMap.entrySet()) { final Enum<?> key = entry.getKey(); if (key instanceof JsonGenerator.Feature) { mapper.configure(((JsonGenerator.Feature) key), entry.getValue()); } else if (key instanceof JsonParser.Feature) { mapper.configure(((JsonParser.Feature) key), entry.getValue()); } else if (key instanceof SerializationConfig.Feature) { mapper.configure(((SerializationConfig.Feature) key), entry.getValue()); } else if (key instanceof DeserializationConfig.Feature) { mapper.configure(((DeserializationConfig.Feature) key), entry.getValue()); } else { throw new IllegalArgumentException("Can not configure ObjectMapper with " + key.name()); } } for (Module module : modules) { mapper.registerModule(module); } // by default, don't serialize null values. mapper.setSerializationInclusion(Inclusion.NON_NULL); return mapper; }
private String getMessageKey(Enum<?> enumInstance) { StringBuffer result = new StringBuffer(); result.append(enumInstance.getClass().getSimpleName()); result.append("."); result.append(enumInstance.name()); return result.toString(); }
private void fire(Enum<?> e, Enum<?> serverCallId, Object... params) { if (params == null) { JavaScriptExpressionEvaluator.getInstance().eval(e, serverCallId.name()); } else { String[] xmlParams = new String[params.length + 1]; xmlParams[0] = serverCallId.name(); for (int i = 0; i < params.length; i++) { xmlParams[i + 1] = Utils.escape(Utils.toString(params[i])); LOG.log(Level.FINE, "Param {0}", i); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, Utils.toString(params[i])); } } JavaScriptExpressionEvaluator.getInstance().eval(e, xmlParams); } }
@Override public void setValue(Enum<?> value) { this.value = value; if (null != value) { holder.setText(value.name()); } }
/** * Get the values from the annotation. We use reflection to turn the annotation into a simple * HashMap of values. * * @return */ Map<String, Object> doGetValues(Annotation annotation) { /* Holds the value map. */ Map<String, Object> values = new HashMap<String, Object>(); /* Get the declared methodMap from the actual annotation. */ Method[] methods = annotation.annotationType().getDeclaredMethods(); final Object[] noargs = (Object[]) null; /* Iterate through declared methodMap and extract values * by invoking decalared methodMap if they are no arg methodMap. */ for (Method method : methods) { /* If it is a no arg method assume it is an annoation value. */ if (method.getParameterTypes().length == 0) { try { /* Get the value. */ Object value = method.invoke(annotation, noargs); if (value instanceof Enum) { Enum enumVal = (Enum) value; value = enumVal.name(); } values.put(method.getName(), value); } catch (Exception ex) { throw new RuntimeException(ex); } } } return values; }
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(); } }
@Override public List<Resource> resources(Enum resourceType) { if ("EBS_VOLUME".equals(resourceType.name())) { return getVolumeResources(); } return Collections.emptyList(); }
private void removeRelationshipPropertyFromAllIndices(final Relationship rel, final String key) { for (Enum indexName : (RelationshipIndex[]) arguments.get("relationshipIndices")) { indices.get(indexName.name()).remove(rel, key); } }
/** * Store an enum value to the user preferences. * * @param key the key * @param value the value to store, or null to remove the value */ public final void putEnum(String key, Enum<?> value) { if (value == null) { putString(key, null); } else { putString(key, value.name()); } }
public static void writeEnum(ObjectOutput out, Enum<?> value) throws IOException { if (value == null) { out.writeObject(null); } else { out.writeUTF(value.name()); } }
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); } }
@Override public JsonElement fetch(Enum<?> entityType, Map<String, String> params) throws IOException { // On the first call, read all the files if (object == null) { object = RemoteJsonHelper.mergeJsonFiles(null, filenames); } return object.get(entityType.name()); }
static String matchStringOrThrow(Pattern p, ToDateParser params, Enum<?> aEnum) { String s = params.getInputStr(); Matcher matcher = p.matcher(s); if (!matcher.find()) { throwException(params, format("Issue happened when parsing token '%s'", aEnum.name())); } return matcher.group(1); }
@SuppressWarnings("rawtypes") public static JsonElement get(JsonObject source, Enum sourceProperty, Converter sourceConverter) { JsonElement value = source.get(maybeFixPropertyName(sourceProperty.name())); if (sourceConverter != null) { value = sourceConverter.convert(value); } return value; }
void addEnum(String parameter, Enum<?> value) { appendExceptFirst(", "); if (!StringUtils.isNullOrEmpty(parameter)) { append(parameter); append('='); } append(value.getClass().getSimpleName() + "." + value.name()); }
private Enum<?> enumForString(String theEnumString) { for (Enum<?> myEnumConstant : value().getDeclaringClass().getEnumConstants()) { if (myEnumConstant.name().equals(theEnumString)) { return myEnumConstant; } } return null; }
/** * A nice human-readable representation of this flag object. * * @return String */ public String toString() { Enum[] enums = setValues(); String out = ""; for (Enum f : enums) { if (out.length() > 0) out += ","; out += f.name(); } return out; }
public static JsonArray getAsArray(JsonObject source, Enum<?> sourceProperty) { if (source == null) { return null; } JsonElement el = source.get(sourceProperty.name()); if (el == null || !el.isJsonArray()) { return null; } return el.getAsJsonArray(); }
protected Object convertToType(Class type, Object value) throws Throwable { Class<Enum> forEnum = type; String strValue = value.toString(); // for (Enum<?> item : forEnum.getEnumConstants()) { String enumValue = item.name().toLowerCase(); if (enumValue.equals(strValue.toLowerCase()) == true) return item; } return null; }
@Override public void data(CCDataObject theData) { String myName = theData.getString("value"); for (Enum<?> myEnumConstant : enumConstants()) { if (myEnumConstant.name().equals(myName)) { value(myEnumConstant, true); return; } } }
private String getEnumValues(Enum<?>[] e) { StringBuilder sb = new StringBuilder(); String sep = ""; for (Enum<?> v : e) { sb.append(sep); sb.append(v.name()); sep = "|"; } return sb.toString(); }