/** * 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; }
/** * 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; }
private void removeRelationshipPropertyFromAllIndices(final Relationship rel, final String key) { for (Enum indexName : (RelationshipIndex[]) arguments.get("relationshipIndices")) { indices.get(indexName.name()).remove(rel, key); } }
private static Collection<Integer> toOrdinals(Collection<? extends Enum> enums) { Collection<Integer> ordinals = new ArrayList<Integer>(enums.size()); for (Enum e : enums) { ordinals.add(e.ordinal()); } return ordinals; }
/** * @param filterName 比较属性字符串,含待比较的比较类型、属性值类型及属性列表. eg. LIKES_NAME_OR_LOGIN_NAME * @param value 待比较的值. */ public PropertyFilter(final String filterName, final Object value) { String firstPart = StringUtils.upperCase(StringUtils.substringBefore(filterName, "_")); String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1); String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length()); try { matchType = Enum.valueOf(MatchType.class, matchTypeCode); } catch (RuntimeException e) { throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性比较类型.", e); } try { propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue(); } catch (RuntimeException e) { throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性值类型.", e); } String propertyNameStr = StringUtils.substringAfter(filterName, "_"); // AssertUtils.isTrue(StringUtils.isNotBlank(propertyNameStr), "filter名称" + filterName + // "没有按规则编写,无法得到属性名称."); propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR); this.matchValue = value; if (null == value || !String.class.equals(value.getClass())) { return; } if (!String.class.equals(propertyClass)) { this.matchValue = ConvertUtils.convert((String) value, propertyClass); } }
protected Component buildReportSelection() { FormLayout content = new FormLayout(); content.setSpacing(true); // Create reporting selection reportSelection = ModelBasedFieldFactory.getInstance(entityModel, getMessageService()) .createEnumCombo(reportDefinition.getClass(), ComboBox.class); reportSelection.setCaption( getMessageService() .getMessage( entityModel.getReference() + "." + reportDefinition.getClass().getSimpleName())); reportSelection.setNullSelectionAllowed(false); reportSelection.setRequired(true); reportSelection.select(reportSelection.getItemIds().iterator().next()); reportSelection.setSizeFull(); reportSelection.addValueChangeListener( new Property.ValueChangeListener() { private static final long serialVersionUID = -3358229370015557129L; @Override public void valueChange(Property.ValueChangeEvent event) { if (exportPDF != null) { exportPDF.setEnabled(false); } } }); // Add combo content.addComponent(reportSelection); return content; }
private Object enumsToString(Object value) { if (value instanceof Enum) { final Enum<?> e = (Enum<?>) value; value = e.toString(); } return value; }
private String getMessageKey(Enum<?> enumInstance) { StringBuffer result = new StringBuffer(); result.append(enumInstance.getClass().getSimpleName()); result.append("."); result.append(enumInstance.name()); return result.toString(); }
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; }
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); } }
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(); } }
public void test7SimpleRpcEncPortEchoMultipleFaults4() throws Exception { SimpleRpcEncPortType binding; try { binding = new SimpleRpcEncServiceLocator().getSimpleRpcEncPort(url); } catch (javax.xml.rpc.ServiceException jre) { if (jre.getLinkedCause() != null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertTrue("binding is null", binding != null); //////////////////////////////////////////////////////////////////////// // echoMultipleFaults4 int intParam = 66; Enum enumParam = new Enum(1); for (int i = 1; i < 3; i++) { try { binding.echoMultipleFaults4(i, intParam, enumParam); } catch (IntFault e1) { assertEquals("Wrong fault thrown: " + e1.getClass(), 1, i); assertEquals(intParam, e1.getPart3()); continue; } catch (EnumFault e2) { assertEquals("Wrong fault thrown: " + e2.getClass(), 2, i); assertEquals(enumParam.getValue(), e2.getPart9().getValue()); continue; } fail("Did NOT catch any exception"); } }
/** * 将bean装换为一个map(能将枚举转换为int) * * @param bean * @return */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Map buildMap(Object bean) { if (bean == null) { return null; } try { Map map = describe(bean); PropertyDescriptor[] pds = BEANUTILSBEAN.getPropertyUtils().getPropertyDescriptors(bean); for (PropertyDescriptor pd : pds) { Class type = pd.getPropertyType(); if (type.isEnum()) { Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName()); Enum enums = EnumUtils.valueOf(type, String.valueOf(value)); map.put(pd.getName(), enums == null ? -1 : enums.ordinal()); } else if (type == java.util.Date.class) { // 防止是Timestamp Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName()); if (value != null) { Calendar cal = Calendar.getInstance(); cal.setTime((java.util.Date) value); map.put(pd.getName(), cal.getTime()); } } } return map; } catch (Throwable e) { LOGGER.error("BeanUtil 创建Map失败:", e); throw new RuntimeException(e); } }
public void testValueOfType() { assertEquals(Embed.Type.link, Embed.Type.valueOf("link")); assertEquals(Embed.Type.undefined, Embed.Type.valueOf("undefined")); assertEquals(Embed.Type.link, Enum.valueOf(Embed.Type.class, "link")); assertEquals(Embed.Type.undefined, Enum.valueOf(Embed.Type.class, "undefined")); }
public void next(Knoop knoop) { @SuppressWarnings("unchecked") Enum<? extends Diagnose> diagnose = (Enum<? extends Diagnose>) knoop.getDiagnose(); Enum<? extends Diagnose>[] diagnoses = possibleDiagnoses().getEnumConstants(); knoop.setDiagnose((Diagnose) diagnoses[(diagnose.ordinal() + 1) % diagnoses.length]); }
/** * 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 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; }
public static boolean containsConstant( Enum<?>[] enumValues, String constant, boolean caseSensitive) { Enum[] arr$ = enumValues; int len$ = enumValues.length; int i$ = 0; while (true) { if (i$ >= len$) { return false; } Enum candidate = arr$[i$]; if (caseSensitive) { if (candidate.toString().equals(constant)) { break; } } else if (candidate.toString().equalsIgnoreCase(constant)) { break; } ++i$; } return true; }
private void applySampler(final Element sampler, final Texture texture) { if (sampler.getChild("minfilter") != null) { final String minfilter = sampler.getChild("minfilter").getText(); texture.setMinificationFilter( Enum.valueOf(SamplerTypes.MinFilterType.class, minfilter).getArdor3dFilter()); } if (sampler.getChild("magfilter") != null) { final String magfilter = sampler.getChild("magfilter").getText(); texture.setMagnificationFilter( Enum.valueOf(SamplerTypes.MagFilterType.class, magfilter).getArdor3dFilter()); } if (sampler.getChild("wrap_s") != null) { final String wrapS = sampler.getChild("wrap_s").getText(); texture.setWrap( Texture.WrapAxis.S, Enum.valueOf(SamplerTypes.WrapModeType.class, wrapS).getArdor3dWrapMode()); } if (sampler.getChild("wrap_t") != null) { final String wrapT = sampler.getChild("wrap_t").getText(); texture.setWrap( Texture.WrapAxis.T, Enum.valueOf(SamplerTypes.WrapModeType.class, wrapT).getArdor3dWrapMode()); } if (sampler.getChild("border_color") != null) { texture.setBorderColor(_colladaDOMUtil.getColor(sampler.getChild("border_color").getText())); } }
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('-', '_')); } }
@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()); }
/* 148: */ /* 149: */ private static AnnotationValue enumValue(String name, DotName typeName, Enum value) /* 150: */ { /* 151:182 */ if ((value != null) && (StringHelper.isNotEmpty(value.toString()))) { /* 152:183 */ return AnnotationValue.createEnumValue(name, typeName, value.toString()); /* 153: */ } /* 154:185 */ return null; /* 155: */ }
/** * Converts a primitive type value, this implementation only converts an EEnum to an Enum value. * * @param value the value to convert * @param eDataType its EDataType * @return the converted value */ @SuppressWarnings({"unchecked", "rawtypes"}) protected Object convertEAttributeValue(final Object value, final EDataType eDataType) { if (value instanceof Enum<?>) { final EDataType enumDataType = getDataTypeOrBaseType(eDataType); Check.isInstanceOf(enumDataType, EEnum.class); final ModelPackage modelPackage = ModelResolver.getInstance().getModelPackage(enumDataType.getEPackage().getNsURI()); final Class<? extends Enum> enumClass = (Class<? extends Enum>) modelPackage.getEClassifierClass(enumDataType); return Enum.valueOf(enumClass, ((Enum<?>) value).name().toUpperCase(Locale.ENGLISH)); } else if (value instanceof EEnumLiteral) { final EDataType enumDataType = getDataTypeOrBaseType(eDataType); Check.isInstanceOf(enumDataType, EEnum.class); final EEnumLiteral eeNumLiteral = (EEnumLiteral) value; final ModelPackage modelPackage = ModelResolver.getInstance().getModelPackage(enumDataType.getEPackage().getNsURI()); if (modelPackage == null) { // dynamic model return eeNumLiteral; } final Class<? extends Enum> enumClass = (Class<? extends Enum>) modelPackage.getEClassifierClass(enumDataType); return Enum.valueOf(enumClass, eeNumLiteral.getName().toUpperCase(Locale.ENGLISH)); } // convert these to a Date always if (value instanceof XMLGregorianCalendar) { final XMLGregorianCalendar xmlCalendar = (XMLGregorianCalendar) value; final Date date = xmlCalendar.toGregorianCalendar().getTime(); return date; } return value; }
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { switch (typeName) { case BOOLEAN: writer.keyword(value == null ? "UNKNOWN" : (Boolean) value ? "TRUE" : "FALSE"); break; case NULL: writer.keyword("NULL"); break; case CHAR: case DECIMAL: case DOUBLE: case BINARY: // should be handled in subtype throw Util.unexpected(typeName); case SYMBOL: if (value instanceof Enum) { Enum enumVal = (Enum) value; writer.keyword(enumVal.toString()); } else { writer.keyword(String.valueOf(value)); } break; default: writer.literal(value.toString()); } }
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 String getLabel(Enum enumValue) { if (enumValue != null) { return getLabel(enumValue.getClass().getName() + "." + enumValue.toString()); } else { return ""; } }
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; }
@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; }