List of usage examples for java.lang Class getEnumConstants
public T[] getEnumConstants()
From source file:com.oembedler.moon.graphql.engine.dfs.GraphQLSchemaDfsTraversal.java
public GraphQLEnumType buildGraphQLEnumType(DfsContext dfsContext, ResolvableTypeAccessor resolvableTypeAccessor) { Class<?> implClass = resolvableTypeAccessor.getImplClass(); Enum[] enumList = (Enum[]) implClass.getEnumConstants(); String valueProviderMethod = resolvableTypeAccessor.getGraphQLEnumValueProviderMethodName(); String valueSpel = resolvableTypeAccessor.getGraphQLEnumDefaultValueSpel(); GraphQLEnumTypeExt.Builder enumTypeBuilder = new GraphQLEnumTypeExt.Builder() .name(resolvableTypeAccessor.getName()).description(resolvableTypeAccessor.getDescription()); if (enumList != null) { for (Enum en : enumList) { ResolvableTypeAccessor rta = ResolvableTypeAccessor.forEnumField(en); String description = rta.getDescription(); String enumName = rta.getName(); Object value = enumName; if (StringUtils.hasText(valueProviderMethod)) value = invokeMethodByName(dfsContext, implClass, valueProviderMethod, en); value = evaluateSpElExpression(dfsContext, implClass, en, valueSpel, value); enumTypeBuilder.value(enumName, value, description); }/*w w w.j av a 2 s. co m*/ } GraphQLEnumType enumType = enumTypeBuilder.build(); return enumType; }
From source file:org.jsonschema2pojo.integration.EnumIT.java
@Test @SuppressWarnings({ "unchecked" }) public void enumWithCustomJavaNames() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/enumWithCustomJavaNames.json", "com.example"); Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.EnumWithCustomJavaNames"); Class<Enum> enumClass = (Class<Enum>) resultsClassLoader .loadClass("com.example.EnumWithCustomJavaNames$EnumProperty"); Object valueWithEnumProperty = typeWithEnumProperty.newInstance(); Method enumSetter = typeWithEnumProperty.getMethod("setEnumProperty", enumClass); enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[2]); assertThat(enumClass.getEnumConstants()[0].name(), is("ONE")); assertThat(enumClass.getEnumConstants()[1].name(), is("TWO")); assertThat(enumClass.getEnumConstants()[2].name(), is("THREE")); assertThat(enumClass.getEnumConstants()[3].name(), is("FOUR")); ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty); JsonNode jsonTree = objectMapper.readTree(jsonString); assertThat(jsonTree.size(), is(1));/*from w w w . j av a2s . c om*/ assertThat(jsonTree.has("enum_Property"), is(true)); assertThat(jsonTree.get("enum_Property").isTextual(), is(true)); assertThat(jsonTree.get("enum_Property").asText(), is("3")); }
From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractController.java
@ExceptionHandler(ConversionNotSupportedException.class) @ResponseBody//from w w w. j ava 2s. co m public UnspecifiedCts2Exception handleException(HttpServletResponse response, HttpServletRequest request, ConversionNotSupportedException ex) { int status = HttpServletResponse.SC_BAD_REQUEST; response.setStatus(status); Class<?> requiredType = ex.getRequiredType(); String typeName = requiredType.getSimpleName(); String value = ex.getValue().toString(); String possibleValues = ""; if (requiredType.isEnum()) { StringBuilder sb = new StringBuilder(); sb.append(" Possible values include: "); Object[] values = requiredType.getEnumConstants(); sb.append(StringUtils.join(values, ", ")); possibleValues = sb.toString(); } return ExceptionFactory.createUnknownException( "Cannot convert value " + value + " to the type " + typeName + "." + possibleValues, getUrlString(request), getParameterString(request)); }
From source file:nz.co.senanque.validationengine.metadata.AnnotationsMetadataFactory.java
public EngineMetadata getObject() throws Exception { final Map<Class<? extends Annotation>, Class<? extends FieldValidator<Annotation>>> validatorMap = getValidatorMap(); final Map<Class<?>, ClassMetadata> classMap = new HashMap<Class<?>, ClassMetadata>(); for (Class<?> clazz : m_classes) { log.debug("class name {}", clazz); boolean classNeeded = true; final ClassMetadata classMetadata = new ClassMetadata(); @SuppressWarnings("unchecked") Map<String, Property> propertyMap = ValidationUtils .getProperties((Class<? extends ValidationObject>) clazz); for (Property property : propertyMap.values()) { Method method = property.getGetter(); log.debug("method.getName() {}", method.getName()); String mname = method.getName(); final String fieldName = property.getFieldName(); final PropertyMetadataImpl fieldMetadata = new PropertyMetadataImpl(property, getMessageSource()); boolean fieldNeeded = false; boolean foundDigits = false; boolean foundLength = false; int digitsLength = -1; for (Annotation fieldAnnotation : method.getAnnotations()) { log.debug("field annotation {}", fieldAnnotation); if (fieldAnnotation instanceof Label) { fieldMetadata.setLabelName(((Label) fieldAnnotation).labelName()); fieldNeeded = true;//from ww w. j a v a 2s. c o m } if (fieldAnnotation instanceof Inactive) { fieldMetadata.setInactive(true); fieldNeeded = true; } if (fieldAnnotation instanceof ReadOnly) { fieldMetadata.setReadOnly(true); fieldNeeded = true; } if (fieldAnnotation instanceof Secret) { fieldMetadata.setSecret(true); fieldNeeded = true; } if (fieldAnnotation instanceof Unknown) { fieldMetadata.setUnknown(true); fieldNeeded = true; } if (fieldAnnotation instanceof Required) { fieldMetadata.setRequired(true); fieldNeeded = true; } if (fieldAnnotation instanceof Digits) { fieldMetadata.setFractionalDigits(((Digits) fieldAnnotation).fractionalDigits()); fieldNeeded = true; foundDigits = true; digitsLength = Integer.parseInt(((Digits) fieldAnnotation).integerDigits()); foundLength = true; } if (fieldAnnotation instanceof Range) { fieldMetadata.setMinValue(((Range) fieldAnnotation).minInclusive()); fieldMetadata.setMaxValue(((Range) fieldAnnotation).maxInclusive()); fieldNeeded = true; } if (fieldAnnotation instanceof Description) { fieldMetadata.setDescription(((Description) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof History) { fieldMetadata.setHistory(((History) fieldAnnotation).expire(), ((History) fieldAnnotation).entries()); fieldNeeded = true; } if (fieldAnnotation instanceof Id) { fieldMetadata.setIdentifier(true); } if (fieldAnnotation instanceof Regex) { fieldMetadata.setRegex(((Regex) fieldAnnotation).pattern()); fieldNeeded = true; } // if (fieldAnnotation instanceof BeanValidator) // { // fieldMetadata.setBean(((BeanValidator)fieldAnnotation).bean()); // fieldMetadata.setParam(((BeanValidator)fieldAnnotation).param()); // fieldNeeded = true; // } if (fieldAnnotation instanceof MapField) { fieldMetadata.setMapField(((MapField) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof WritePermission) { fieldMetadata.setPermission(((WritePermission) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof ReadPermission) { fieldMetadata.setReadPermission(((ReadPermission) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof ChoiceList) { final List<ChoiceBase> choiceList = m_choicesMap.get(((ChoiceList) fieldAnnotation).name()); fieldMetadata.setChoiceList(choiceList); fieldNeeded = true; } if (fieldAnnotation instanceof Length) { fieldMetadata.setMaxLength(((Length) fieldAnnotation).maxLength()); fieldNeeded = true; foundLength = true; } Class<? extends FieldValidator<Annotation>> fvClass = validatorMap .get(fieldAnnotation.annotationType()); if (fvClass != null) { final FieldValidator<Annotation> fv = fvClass.newInstance(); fv.init(fieldAnnotation, fieldMetadata); fieldMetadata.addConstraintValidator(fv); fieldNeeded = true; } } Column column = method.getAnnotation(Column.class); if (column != null) { int precision = column.precision(); int fractional = column.scale(); int length = column.length(); if (!foundDigits) { if (fractional > 0) { fieldMetadata.setFractionalDigits(String.valueOf(fractional)); } } if (!foundLength) { if (precision > 0 && length == 255) { length = column.precision() + ((fractional > 0) ? 1 : 0); fieldMetadata.setMaxLength(String.valueOf(length)); } else { length = column.length(); fieldMetadata.setMaxLength(String.valueOf(length)); } } } Field field; try { field = clazz.getField(mname); for (Annotation fieldAnnotation : field.getAnnotations()) { if (fieldAnnotation instanceof XmlElement) { if (((XmlElement) fieldAnnotation).required()) { fieldMetadata.setRequired(true); fieldNeeded = true; } } } } catch (NoSuchFieldException e) { // ignore } Class<?> returnClass = method.getReturnType(); Object[] t = returnClass.getEnumConstants(); if (t != null) { fieldNeeded = true; fieldMetadata.setChoiceList(t); } if (!fieldNeeded) { if (m_classes.contains(returnClass) || returnClass.isAssignableFrom(List.class)) { fieldNeeded = true; } } if (fieldNeeded) { log.debug("fieldName added to metadata {}.{}", clazz.getName(), fieldName); classMetadata.addField(fieldName, fieldMetadata); classNeeded = true; } else { log.debug("fieldName not needed {}.{}", clazz.getName(), fieldName); } } if (classNeeded) { log.debug("Class added to metadata {}", clazz.getName()); classMap.put(clazz, classMetadata); } } return new EngineMetadata(classMap, m_choicesDoc); }
From source file:de.iteratec.iteraplan.businesslogic.exchange.xmi.importer.XmiImportServiceImpl.java
/** * Method to get an Enumeration Value//from ww w . j ava 2s .c om * * @param object the EEnumLiteral value * @param writeMethod the writeMethod for the corresponding enumeration-attribute * @return the enum-value for the given EEnumLiteral value */ private Object enumObjectForEEnum(Object object, Method writeMethod) { EEnumLiteral eEnumLiteral = (EEnumLiteral) object; try { String name = writeMethod.getParameterTypes()[0].getName(); Class<?> enumClass = Class.forName(name); return enumClass.getEnumConstants()[eEnumLiteral.getValue()]; } catch (ClassNotFoundException e) { LOGGER.error(e); return null; } }
From source file:us.ihmc.idl.serializers.extra.JacksonInterchangeSerializer.java
/** * Enum/*from w w w . j a va 2 s. c om*/ */ public Enum<?> read_type_c(String name, Class<? extends Enum<?>> enumType) { String val = node.path(name).asText(); return str2enum(enumType.getEnumConstants(), val); }
From source file:com.vmware.photon.controller.deployer.helpers.TestHelper.java
public static Object[][] getValidStageTransitions(@Nullable Class<? extends Enum> subStages) { if (subStages == null) { ///*from www . j a va 2s . com*/ // N.B. Tasks without defined sub-stages must allow these default stage transitions. // return new Object[][] { { TaskState.TaskStage.CREATED, TaskState.TaskStage.STARTED }, { TaskState.TaskStage.CREATED, TaskState.TaskStage.FINISHED }, { TaskState.TaskStage.CREATED, TaskState.TaskStage.FAILED }, { TaskState.TaskStage.CREATED, TaskState.TaskStage.CANCELLED }, { TaskState.TaskStage.STARTED, TaskState.TaskStage.STARTED }, { TaskState.TaskStage.STARTED, TaskState.TaskStage.FINISHED }, { TaskState.TaskStage.STARTED, TaskState.TaskStage.FAILED }, { TaskState.TaskStage.STARTED, TaskState.TaskStage.CANCELLED }, }; } if (!subStages.isEnum() || subStages.getEnumConstants().length == 0) { throw new IllegalStateException("Class " + subStages.getName() + " is not a valid enum"); } // // Add the normal task stage progression transitions. // Enum[] enumConstants = subStages.getEnumConstants(); List<Object[]> validStageTransitions = new ArrayList<>(); validStageTransitions.add( new Object[] { TaskState.TaskStage.CREATED, null, TaskState.TaskStage.STARTED, enumConstants[0] }); for (int i = 0; i < enumConstants.length - 1; i++) { validStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i], TaskState.TaskStage.STARTED, enumConstants[i + 1] }); } // // N.B. The transition to the final FINISHED stage is handled below. // // Add transitions to the terminal task stages. // validStageTransitions .add(new Object[] { TaskState.TaskStage.CREATED, null, TaskState.TaskStage.FINISHED, null }); validStageTransitions .add(new Object[] { TaskState.TaskStage.CREATED, null, TaskState.TaskStage.FAILED, null }); validStageTransitions .add(new Object[] { TaskState.TaskStage.CREATED, null, TaskState.TaskStage.CANCELLED, null }); for (int i = 0; i < enumConstants.length; i++) { validStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i], TaskState.TaskStage.FINISHED, null }); validStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i], TaskState.TaskStage.FAILED, null }); validStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i], TaskState.TaskStage.CANCELLED, null }); } Object[][] returnValue = new Object[validStageTransitions.size()][4]; for (int i = 0; i < validStageTransitions.size(); i++) { returnValue[i][0] = validStageTransitions.get(i)[0]; returnValue[i][1] = validStageTransitions.get(i)[1]; returnValue[i][2] = validStageTransitions.get(i)[2]; returnValue[i][3] = validStageTransitions.get(i)[3]; } return returnValue; }
From source file:org.mule.module.extension.internal.capability.xml.schema.SchemaBuilder.java
private LocalSimpleType createEnumSimpleType(DataType enumType) { LocalSimpleType enumValues = new LocalSimpleType(); Restriction restriction = new Restriction(); enumValues.setRestriction(restriction); restriction.setBase(SchemaConstants.STRING); Class<? extends Enum> enumClass = (Class<? extends Enum>) enumType.getRawType(); for (Enum value : enumClass.getEnumConstants()) { NoFixedFacet noFixedFacet = objectFactory.createNoFixedFacet(); noFixedFacet.setValue(value.name()); JAXBElement<NoFixedFacet> enumeration = objectFactory.createEnumeration(noFixedFacet); enumValues.getRestriction().getFacets().add(enumeration); }/*www .java 2s. c om*/ return enumValues; }
From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java
/** * Parses the./*from w w w . jav a 2s.com*/ * * @param <T> the generic type * @param cls the cls * @param value the value * @return the t * @throws java.text.ParseException the parse exception */ @SuppressWarnings("unchecked") public static <T> T parse(Class<T> cls, String value) throws ParseException { if (cls.isEnum()) { final Map<Class<?>, Map<String, String>> member = SCHEMA_TO_ENUM_DICTIONARIES.getMember(); String val = value; final Map<String, String> stringToEnumDict = member.get(cls); if (stringToEnumDict != null) { final String strEnumName = stringToEnumDict.get(value); if (strEnumName != null) { val = strEnumName; } } for (T o : cls.getEnumConstants()) { if (o.toString().equals(val)) { return o; } } return null; } else if (Number.class.isAssignableFrom(cls)) { if (Double.class.isAssignableFrom(cls)) { return (T) ((Double) Double.parseDouble(value)); } else if (Integer.class.isAssignableFrom(cls)) { return (T) ((Integer) Integer.parseInt(value)); } else if (Long.class.isAssignableFrom(cls)) { return (T) ((Long) Long.parseLong(value)); } else if (Float.class.isAssignableFrom(cls)) { return (T) ((Float) Float.parseFloat(value)); } else if (Byte.class.isAssignableFrom(cls)) { return (T) ((Byte) Byte.parseByte(value)); } else if (Short.class.isAssignableFrom(cls)) { return (T) ((Short) Short.parseShort(value)); } else if (BigInteger.class.isAssignableFrom(cls)) { return (T) (new BigInteger(value)); } else if (BigDecimal.class.isAssignableFrom(cls)) { return (T) (new BigDecimal(value)); } } else if (Date.class.isAssignableFrom(cls)) { DateFormat df = createDateFormat(XML_SCHEMA_DATE_TIME_FORMAT); return (T) df.parse(value); } else if (Boolean.class.isAssignableFrom(cls)) { return (T) ((Boolean) Boolean.parseBoolean(value)); } else if (String.class.isAssignableFrom(cls)) { return (T) value; } return null; }
From source file:org.jsonschema2pojo.integration.EnumIT.java
@Test @SuppressWarnings("unchecked") public void intEnumIsSerializedCorrectly() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, JsonParseException, JsonMappingException, IOException, InstantiationException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/integerEnumToSerialize.json", "com.example"); // the schema for a valid instance Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize"); Class<Enum> enumClass = (Class<Enum>) resultsClassLoader .loadClass("com.example.enums.IntegerEnumToSerialize$TestEnum"); // create an instance Object valueWithEnumProperty = typeWithEnumProperty.newInstance(); Method enumSetter = typeWithEnumProperty.getMethod("setTestEnum", enumClass); // call setTestEnum(TestEnum.ONE) enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[0]); ObjectMapper objectMapper = new ObjectMapper(); // write our instance out to json String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty); JsonNode jsonTree = objectMapper.readTree(jsonString); assertThat(jsonTree.size(), is(1));/* w w w.j a v a2 s . c o m*/ assertThat(jsonTree.has("testEnum"), is(true)); assertThat(jsonTree.get("testEnum").isIntegralNumber(), is(true)); assertThat(jsonTree.get("testEnum").asInt(), is(1)); }