List of usage examples for java.lang Enum valueOf
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
From source file:springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl.java
protected List<Scheme> stringSetToSchemeList(Set<String> set) { if (set == null) { return null; }//from w w w.j av a 2 s. c o m List<Scheme> list = new ArrayList<Scheme>(); for (String string : set) { list.add(Enum.valueOf(Scheme.class, string)); } return list; }
From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java
/** * Sole constructor. This is the injection point for stored config, via the * connectorInstance.xml.// w w w . j a v a2s.co m * * @param config A Map<String, String> The config keys for this map come from * the {@link ConfigName} enumeration, plus the pseudo-keys for schema. * The values are interpreted depending on the types of the * corresponding * configuration points, which are accessed through public getters. * There * can be at most {@code MAX_SCHEMA_ELEMENTS} pseudo-keys to define the * schema: these are of the form {@code ConfigName.SCHEMA.toString() + * "_" + i}, that is, {@code SCHEMA_0, SCHEMA_1,} etc. */ public LdapConnectorConfig(Map<String, String> config) { String hostname = getTrimmedValueFromConfig(config, ConfigName.HOSTNAME); String portString = getTrimmedValueFromConfig(config, ConfigName.PORT); String authtypeString = getTrimmedValueFromConfig(config, ConfigName.AUTHTYPE); String username = getTrimmedValueFromConfig(config, ConfigName.USERNAME); if (username == null) { username = ""; } String password = getTrimmedValueFromConfig(config, ConfigName.PASSWORD); if (password == null) { password = ""; } String methodString = getTrimmedValueFromConfig(config, ConfigName.METHOD); String basedn = getTrimmedValueFromConfig(config, ConfigName.BASEDN); String filter = getTrimmedValueFromConfig(config, ConfigName.FILTER); String schemaKey = getTrimmedValueFromConfig(config, ConfigName.SCHEMA_KEY); //Since we removed this attribute from UI in 2.6.4 we need to add //a default value here. if (schemaKey == null) { schemaKey = LdapHandler.DN_ATTRIBUTE; } Set<String> tempSchema = new TreeSet<String>(); addSchemaFromConfig(config, tempSchema); /** * Note: if the schema is not empty (at least one schema_xx keys was * specified in the config) * then the schemaKey will be added to the schema. Otherwise the schema will * remain empty, to signify that this config is not complete. */ if (tempSchema.size() > 0 && !tempSchema.contains(schemaKey)) { tempSchema.add(schemaKey); } ImmutableSet<String> schema = ImmutableSet.copyOf(tempSchema); this.hostname = hostname; Integer p; try { p = Integer.valueOf(portString); } catch (NumberFormatException e) { LOG.warning("Found illegal port value: " + portString + " defaulting to 389"); p = 389; } this.port = p; AuthType authtype = AuthType.ANONYMOUS; if (authtypeString != null) { try { authtype = Enum.valueOf(AuthType.class, authtypeString); } catch (IllegalArgumentException e) { LOG.warning("Found illegal authtype value: " + authtypeString + " defaulting to " + AuthType.ANONYMOUS.toString()); } } this.authtype = authtype; this.username = username; this.password = password; Method method = Method.STANDARD; if (methodString != null) { try { method = Enum.valueOf(Method.class, methodString); } catch (IllegalArgumentException e) { LOG.warning("Found illegal method value: " + methodString + " defaulting to " + Method.STANDARD.toString()); } } this.method = method; this.basedn = basedn; this.schemaKey = schemaKey; this.filter = filter; this.schema = schema; this.settings = new LdapConnectionSettings(this.method, this.hostname, this.port, this.basedn, this.authtype, this.username, this.password); LOG.fine("this.settings: " + this.settings); // only create an LdapRule if one was supplied this.rule = (this.filter == null) ? null : new LdapRule(Scope.SUBTREE, this.filter); }
From source file:com.amazonaws.hal.client.ConversionUtil.java
private static Object convertFromNumber(Class<?> clazz, Number value) { if (String.class.isAssignableFrom(clazz)) { return value.toString(); } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) { return value.intValue(); } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) { return value.longValue(); } else if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) { return value.shortValue(); } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) { return value.doubleValue(); } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) { return value.floatValue(); } else if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) { return Boolean.valueOf(value.toString()); } else if (char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) { if (value.longValue() <= 255) { return (char) value.longValue(); } else {// w w w . j a v a2 s . c o m throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName()); } } else if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)) { return value.byteValue(); } else if (BigDecimal.class.isAssignableFrom(clazz)) { return new BigDecimal(value.toString()); } else if (BigInteger.class.isAssignableFrom(clazz)) { // Necessary because BigInteger(long) is a private method and we need to convert the Number to a long to // prevent the constructor from throwing a NumberFormatException Example: BigInteger(1.2) return new BigInteger(String.valueOf(value.longValue())); } else if (Date.class.isAssignableFrom(clazz)) { return new Date(value.longValue()); } else if (clazz.isEnum()) { try { //noinspection unchecked return Enum.valueOf((Class<Enum>) clazz, value.toString()); } catch (IllegalArgumentException e) { log.error(String.format( "'%s' is not a recognized enum value for %s. Returning default of %s instead.", value, clazz.getName(), clazz.getEnumConstants()[0])); return clazz.getEnumConstants()[0]; } } else { throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName()); } }
From source file:jef.tools.Assert.java
/** * //from w w w .ja v a 2 s. c om * @param string * @param name */ public static <T extends Enum<T>> void isEnumOf(Object string, Class<T> name) { Enum.valueOf(name, string.toString()); }
From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.MappingHelper.java
/** * Bildet ein Objekt mithilfe von Dozer auf einen gewnschten Zieltyp ab. Im Gegensatz zu * {@link Mapper#map(Object, Class)} knnen als Zieltyp auch generische Collections, String und primitive * Typen bergeben werden./*w w w . j a v a2s .com*/ * * @param mapper * der Dozer-Mapper * @param source * das zu mappende Objekt * @param destinationType * der Zieltyp * @return das gemappte Objekt */ @SuppressWarnings("unchecked") public static Object map(Mapper mapper, Object source, Type destinationType) { if (source == null) { return null; } if (destinationType instanceof ParameterizedType) { ParameterizedType parDestinationType = (ParameterizedType) destinationType; Class<?> rawClass = (Class<?>) parDestinationType.getRawType(); if (List.class.isAssignableFrom(rawClass)) { return mapCollection(mapper, source, parDestinationType, new ArrayList<Object>()); } else if (SortedSet.class.isAssignableFrom(rawClass)) { return mapCollection(mapper, source, parDestinationType, new TreeSet<Object>()); } else if (Set.class.isAssignableFrom(rawClass)) { return mapCollection(mapper, source, parDestinationType, new HashSet<Object>()); } else if (SortedMap.class.isAssignableFrom(rawClass)) { return mapMap(mapper, source, parDestinationType, new TreeMap<Object, Object>()); } else if (Map.class.isAssignableFrom(rawClass)) { return mapMap(mapper, source, parDestinationType, new HashMap<Object, Object>()); } destinationType = parDestinationType.getRawType(); } if (destinationType instanceof GenericArrayType) { if (!source.getClass().isArray()) { throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: " + source.getClass()); } // wir werden im Array Element pro Element mappen Type elementType = ((GenericArrayType) destinationType).getGenericComponentType(); Object[] sourceArray = (Object[]) source; Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length); for (int i = 0; i < sourceArray.length; i++) { destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType); } return destinationArray; } else if ((destinationType instanceof Class<?>) && ((Class<?>) destinationType).isArray()) { if (!source.getClass().isArray()) { throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: " + source.getClass()); } Class<?> destinationTypeClass = (Class<?>) destinationType; // wir werden im Array Element pro Element mappen Type elementType = destinationTypeClass.getComponentType(); Object[] sourceArray = (Object[]) source; Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length); for (int i = 0; i < sourceArray.length; i++) { destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType); } return destinationArray; } if (!(destinationType instanceof Class<?>)) { throw new IllegalArgumentException( "Ein Mapping auf Typ " + destinationType + " wird nicht untersttzt"); } Class<?> destinationClass = (Class<?>) destinationType; if (ClassUtils.isPrimitiveOrWrapper(destinationClass) || MAPPING_BLACKLIST.contains(destinationClass)) { return source; } else if (destinationClass.isEnum()) { // wir mssen auf dieser Ebene Enums leider manuell mappen if (!(source instanceof Enum)) { throw new IllegalArgumentException("Ein Mapping auf ein Enum " + destinationClass + " wird nicht untersttzt, da das Quellobjekt kein Enumobjekt ist (Quellobjektstyp: " + source.getClass().toString() + ")."); } return Enum.valueOf((Class<Enum>) destinationClass, ((Enum<?>) source).name()); } else { return mapper.map(source, destinationClass); } }
From source file:com.joyent.manta.util.MantaUtils.java
/** * Parses an arbitrary object for an enum represented as a String. If the * string is empty or null we return null. If the String doesn't match any * valid enum values, then we return null * * @param value object to parse string value from * @param enumClass enum class to parse/*from w w w.j a v a 2 s.c o m*/ * @param <T> enum type to parse * @return value of enum or null on invalid input */ public static <T extends Enum<T>> T parseEnumOrNull(final Object value, final Class<T> enumClass) { if (value == null) { return null; } if (value.getClass() == enumClass) { @SuppressWarnings("unchecked") T cast = (T) value; return cast; } String string = toStringEmptyToNull(value); if (string == null) { return null; } T parsed; try { parsed = Enum.valueOf(enumClass, string); } catch (RuntimeException e) { String msg = "Error parsing value as enum. Value: %s"; LOGGER.warn(String.format(msg, value), e); parsed = null; } return parsed; }
From source file:net.iaeste.iws.core.transformers.CSVTransformer.java
static <T extends Enum<T>> void transformEnum(final Map<String, String> errors, final Verifiable obj, final OfferFields field, final CSVRecord record, final Class<T> enumType) { final String value = record.get(field.getField()); if ((value != null) && !value.isEmpty()) { try {/* w w w.j a v a 2 s .com*/ final T theEnum = Enum.valueOf(enumType, value.toUpperCase(DEFAULT_LOCALE)); invokeMethodOnObject(errors, obj, field, theEnum); } catch (IllegalArgumentException e) { LOG.debug(e.getMessage(), e); errors.put(field.getField(), e.getMessage()); } } }
From source file:org.mule.module.wsdlproc.WSDLProcModule.java
public Object createArgumentObject(Map<String, Object> inputParams) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchMethodException { Object inputObject = type.newInstance(); BeanUtilsBean beanUtilsBean = new BeanUtilsBean(new ConvertUtilsBean() {//This is to make BeanUtils handle Enums @Override/* w w w .j ava 2s. co m*/ public Object convert(String value, Class clazz) { if (clazz.isEnum()) { return Enum.valueOf(clazz, camelCaseToEnumFormat(value)); } else { return super.convert(value, clazz); } } }); beanUtilsBean.populate(inputObject, inputParams); //BeanUtils.populateWithoutFail(inputObject, inputParams, false); return inputObject; }
From source file:freedots.web.MusicXML2BrailleServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Score score = null;//from w w w.j a va 2 s .co m BrailleEncoding brailleEncoding = BrailleEncoding.UnicodeBraille; int width = 40, height = 25; InputStream stream = null; ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { final FileItemStream item = iterator.next(); if (item.getFieldName().compareTo("file.xml") == 0) { String extension = "xml"; if (item.getName().endsWith(".mxl")) extension = "mxl"; score = parseMusicXML(item.openStream(), extension); } else if (item.getFieldName().compareTo("encoding") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null) { try { brailleEncoding = Enum.valueOf(BrailleEncoding.class, line); } catch (IllegalArgumentException e) { LOG.info("Unknown encoding " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("width") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_COLUMNS_PER_LINE && value <= MAX_COLUMNS_PER_LINE) width = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("height") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_LINES_PER_PAGE && value <= MAX_LINES_PER_PAGE) height = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } } } catch (org.apache.commons.fileupload.FileUploadException e) { LOG.info("FileUploadException error"); resp.sendError(500); } if (score != null) { writeResult(score, width, height, Method.SectionBySection, brailleEncoding, resp); } else { resp.sendRedirect("/"); } }
From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java
/** {@inheritDoc} */ @SuppressWarnings("unchecked") // We're checking after the fact. @Override/*from w w w. j a v a 2s . c om*/ public <T> T convertToInstance(final Class<T> type, final String stringValue, final String format) throws ConverterException { Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL); T result = null; if (type.isEnum()) { DelegatingEnumConverterTool.LOGGER.debug("Converting to instance type {} with format {} and value: {}", type, stringValue); @SuppressWarnings("rawtypes") // No other way? final Class<? extends Enum> enumType = (Class<? extends Enum>) type; if (!StringUtil.isEmptyString(stringValue)) { result = (T) Enum.valueOf(enumType, stringValue); } } else { result = this.converterTool.convertToInstance(type, stringValue, format); } return result; }