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:org.nuxeo.ecm.directory.sql.SQLDirectoryDescriptor.java
@XNode("substringMatchType") public void setSubstringMatchType(String substringMatchType) { if (substringMatchType != null) { try {/*ww w . j av a 2 s .c o m*/ this.substringMatchType = Enum.valueOf(SubstringMatchType.class, substringMatchType); } catch (IllegalArgumentException iae) { log.error("Invalid substring match type: " + substringMatchType + ". Valid options: subinitial, subfinal, subany"); this.substringMatchType = SubstringMatchType.subinitial; } } }
From source file:org.chililog.server.workbench.workers.UsersWorker.java
/** * Read. Anyone is allowed to get a list of users. This helps the client side link usernames with display names and * gravatars. However, unless you are the system administrator, you don't get roles and email addresses. * //from ww w . j a va 2s .co m * @throws Exception */ @Override public ApiResult processGet() throws Exception { try { DB db = MongoConnection.getInstance().getConnection(); Object responseContent = null; boolean isSysAdmin = this.getAuthenticatedUser().isSystemAdministrator(); if (this.getUriPathParameters() == null || this.getUriPathParameters().length == 0) { UserListCriteria criteria = new UserListCriteria(); this.loadBaseListCriteriaParameters(criteria); criteria.setUsernamePattern( this.getUriQueryStringParameter(USERNAME_URI_QUERYSTRING_PARAMETER_NAME, true)); criteria.setEmailAddressPattern( this.getUriQueryStringParameter(EMAIL_ADDRESS_URI_QUERYSTRING_PARAMETER_NAME, true)); criteria.setRole(this.getUriQueryStringParameter(ROLE_URI_QUERYSTRING_PARAMETER_NAME, true)); String status = this.getUriQueryStringParameter(STATUS_URI_QUERYSTRING_PARAMETER_NAME, true); if (!StringUtils.isBlank(status)) { criteria.setStatus(Enum.valueOf(Status.class, status)); } ArrayList<UserBO> boList = UserController.getInstance().getList(db, criteria); if (!boList.isEmpty()) { ArrayList<UserAO> aoList = new ArrayList<UserAO>(); for (UserBO userBO : boList) { aoList.add(new UserAO(userBO, isSysAdmin)); } responseContent = aoList.toArray(new UserAO[] {}); ApiResult result = new ApiResult(this.getAuthenticationToken(), JSON_CONTENT_TYPE, responseContent); if (criteria.getDoPageCount()) { result.getHeaders().put(PAGE_COUNT_HEADER, new Integer(criteria.getPageCount()).toString()); } return result; } } else { // Get specific user String id = this.getUriPathParameters()[ID_URI_PATH_PARAMETER_INDEX]; responseContent = new UserAO(UserController.getInstance().get(db, new ObjectId(id)), isSysAdmin); } return new ApiResult(this.getAuthenticationToken(), JSON_CONTENT_TYPE, responseContent); } catch (Exception ex) { return new ApiResult(HttpResponseStatus.BAD_REQUEST, ex); } }
From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java
/** * Disable sessionId in URL (Servlet 3.0 containers) by setting the session tracking mode to SessionTrackingMode.COOKIE * For Servlet container < 3.0 we use different method (for tomcat 6 we use custom context.xml and for jetty * there is a custom jetty.xml file).//w w w.ja v a2 s . co m */ @SuppressWarnings("unchecked") private void setSessionTrackingMode(ServletContext servletContext) { // Only for Servlet container version 3.0 and above if (servletContext.getMajorVersion() < 3) { return; } // We cannot use ConstantValue.enableURLSessionId.getBoolean() since ArtifactoryHome is not binded yet. ArtifactoryHome artifactoryHome = (ArtifactoryHome) servletContext .getAttribute(ArtifactoryHome.SERVLET_CTX_ATTR); if (artifactoryHome == null) { throw new IllegalStateException("Artifactory home not initialized."); } if (artifactoryHome.getArtifactoryProperties() .getBooleanProperty(ConstantValues.supportUrlSessionTracking)) { getLogger().debug("Skipping setting session tracking mode to COOKIE, enableURLSessionId flag it on."); return; } try { // load enum with reflection ClassLoader cl = ClassUtils.getDefaultClassLoader(); Class<Enum> trackingModeEnum = (Class<Enum>) cl.loadClass("javax.servlet.SessionTrackingMode"); Enum cookieTrackingMode = Enum.valueOf(trackingModeEnum, "COOKIE"); // reflective call servletContext.setSessionTrackingModes(trackingModes) Method method = servletContext.getClass().getMethod("setSessionTrackingModes", Set.class); method.setAccessible(true); ReflectionUtils.invokeMethod(method, servletContext, Sets.newHashSet(cookieTrackingMode)); getLogger().debug("Successfully set session tracking mode to COOKIE"); } catch (Exception e) { getLogger().warn("Failed to set session tracking mode: " + e.getMessage()); } }
From source file:nl.strohalm.cyclos.utils.access.PermissionHelper.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static Permission getPermission(final String qualifiedPermissionName) { final String[] valueParts = StringUtils.split(qualifiedPermissionName, "."); final Class permissionClass = permissionsBySimpleName.get(valueParts[0]); if (permissionClass == null) { throw new IllegalArgumentException("Invalid permission class simple name: " + valueParts[0]); }/*from w ww . j a v a 2s .c o m*/ return (Permission) Enum.valueOf(permissionClass, valueParts[1]); }
From source file:io.liveoak.security.policy.uri.BasicURIPolicyRootResourceTest.java
private void assertAuthzDecision(RequestContext reqCtxToCheck, ResourceState reqResourceState, AuthzDecision expectedDecision) throws Exception { RequestAttributes attribs = new DefaultRequestAttributes(); attribs.setAttribute(AuthzConstants.ATTR_REQUEST_CONTEXT, reqCtxToCheck); attribs.setAttribute(AuthzConstants.ATTR_REQUEST_RESOURCE_STATE, reqResourceState); RequestContext reqCtx = new RequestContext.Builder().requestAttributes(attribs).build(); ResourceState state = client.read(reqCtx, "/testApp/uri-policy/authzCheck"); String decision = (String) state.getProperty(AuthzConstants.ATTR_AUTHZ_POLICY_RESULT); Assert.assertNotNull(decision);/* w ww .ja va 2 s . c o m*/ Assert.assertEquals(expectedDecision, Enum.valueOf(AuthzDecision.class, decision)); }
From source file:org.apache.lens.server.util.UtilityMethods.java
public static <T extends Enum<T>> T checkAndGetOperation(final String operation, Class<T> enumType, T... supportedOperations) throws UnSupportedOpException { try {/*w w w .j a va 2 s . c om*/ T op = Enum.valueOf(enumType, operation.toUpperCase()); for (T supportedOperation : supportedOperations) { if (op.equals(supportedOperation)) { return op; } } throw new UnSupportedOpException(supportedOperations); } catch (IllegalArgumentException e) { throw new UnSupportedOpException(e, supportedOperations); } }
From source file:com.bstek.dorado.config.definition.Definition.java
/** * ?// w w w . j a va 2 s .c o m * * @param object * ? * @param property * ?? * @param value * @see {@link #getProperties()} * @param context * * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected void setObjectProperty(Object object, String property, Object value, CreationContext context) throws Exception { if (object instanceof Map) { value = DefinitionUtils.getRealValue(value, context); if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { ((Map) object).put(property, value); } } else { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(object, property); if (propertyDescriptor != null) { Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); Class<?> propertyType = propertyDescriptor.getPropertyType(); if (writeMethod != null) { Class<?> oldImpl = context.getDefaultImpl(); try { context.setDefaultImpl(propertyType); value = DefinitionUtils.getRealValue(value, context); } finally { context.setDefaultImpl(oldImpl); } if (!propertyType.equals(String.class) && value instanceof String) { if (propertyType.isEnum()) { value = Enum.valueOf((Class) propertyType, (String) value); } else if (StringUtils.isBlank((String) value)) { value = null; } } else if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { writeMethod.invoke(object, new Object[] { ConvertUtils.convert(value, propertyType) }); } } else if (readMethod != null && Collection.class.isAssignableFrom(propertyType)) { Collection collection = (Collection) readMethod.invoke(object, EMPTY_ARGS); if (collection != null) { if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } } else { collection.addAll((Collection) value); } } } else { throw new NoSuchMethodException( "Property [" + property + "] of [" + object + "] is not writable."); } } else { throw new NoSuchMethodException("Property [" + property + "] not found in [" + object + "]."); } } }
From source file:edu.harvard.med.screensaver.io.CommandLineApplication.java
public <T extends Enum<T>> T getCommandLineOptionEnumValue(String optionName, Class<T> ofEnum) { verifyOptionsProcessed();/* w ww . j a va2s. c om*/ _lastAccessOption = _options.getOption(optionName); if (!_cmdLine.hasOption(optionName) && _option2DefaultValue.containsKey(optionName)) { return (T) _option2DefaultValue.get(optionName); } if (_cmdLine.hasOption(optionName)) { Object value = getCommandLineOptionValue(optionName); try { Enum<T> valueOf = Enum.valueOf(ofEnum, value.toString().toUpperCase()); return (T) valueOf; } catch (Exception e) { showHelpAndExit("could not parse option " + optionName + " with arg " + value + " as enum " + ofEnum.getClass().getSimpleName()); } } return null; }
From source file:nl.strohalm.cyclos.utils.conversion.CoercionHelper.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Object convert(Class toType, Object value) { if ("".equals(value)) { value = null;// ww w. j av a2 s . co m } // If we do not want a collection, but the value is one, use the first value if (value != null && !(Collection.class.isAssignableFrom(toType) || toType.isArray()) && (value.getClass().isArray() || value instanceof Collection)) { final Iterator it = IteratorUtils.getIterator(value); if (!it.hasNext()) { value = null; } else { value = it.next(); } } // Check for null values if (value == null) { if (toType.isPrimitive()) { // On primitives, use the default value if (toType == Boolean.TYPE) { value = Boolean.FALSE; } else if (toType == Character.TYPE) { value = '\0'; } else { value = 0; } } else { // For objects, return null return null; } } // Check if the value is already of the expected type if (toType.isInstance(value)) { return value; } // If the class is primitive, use the wrapper, so we have an easier work of testing instances if (toType.isPrimitive()) { toType = ClassUtils.primitiveToWrapper(toType); } // Convert to well-known types if (String.class.isAssignableFrom(toType)) { if (value instanceof Entity) { final Long entityId = ((Entity) value).getId(); return entityId == null ? null : entityId.toString(); } return value.toString(); } else if (Number.class.isAssignableFrom(toType)) { if (!(value instanceof Number)) { if (value instanceof String) { value = new BigDecimal((String) value); } else if (value instanceof Date) { value = ((Date) value).getTime(); } else if (value instanceof Calendar) { value = ((Calendar) value).getTimeInMillis(); } else if (value instanceof Entity) { value = ((Entity) value).getId(); if (value == null) { return null; } } else { throw new ConversionException("Invalid number: " + value); } } final Number number = (Number) value; if (Byte.class.isAssignableFrom(toType)) { return number.byteValue(); } else if (Short.class.isAssignableFrom(toType)) { return number.shortValue(); } else if (Integer.class.isAssignableFrom(toType)) { return number.intValue(); } else if (Long.class.isAssignableFrom(toType)) { return number.longValue(); } else if (Float.class.isAssignableFrom(toType)) { return number.floatValue(); } else if (Double.class.isAssignableFrom(toType)) { return number.doubleValue(); } else if (BigInteger.class.isAssignableFrom(toType)) { return new BigInteger(number.toString()); } else if (BigDecimal.class.isAssignableFrom(toType)) { return new BigDecimal(number.toString()); } } else if (Boolean.class.isAssignableFrom(toType)) { if (value instanceof Number) { return ((Number) value).intValue() != 0; } else if ("on".equalsIgnoreCase(value.toString())) { return true; } else { return Boolean.parseBoolean(value.toString()); } } else if (Character.class.isAssignableFrom(toType)) { final String str = value.toString(); return (str.length() == 0) ? null : str.charAt(0); } else if (Calendar.class.isAssignableFrom(toType)) { if (value instanceof Date) { final Calendar cal = new GregorianCalendar(); cal.setTime((Date) value); return cal; } } else if (Date.class.isAssignableFrom(toType)) { if (value instanceof Calendar) { final long millis = ((Calendar) value).getTimeInMillis(); try { return ConstructorUtils.invokeConstructor(toType, millis); } catch (final Exception e) { throw new IllegalStateException(e); } } } else if (Enum.class.isAssignableFrom(toType)) { Object ret; try { ret = Enum.valueOf(toType, value.toString()); } catch (final Exception e) { ret = null; } if (ret == null) { Object[] possible; try { possible = (Object[]) toType.getMethod("values").invoke(null); } catch (final Exception e) { throw new IllegalStateException( "Couldn't invoke the 'values' method for enum " + toType.getName()); } if (StringValuedEnum.class.isAssignableFrom(toType)) { final String test = coerce(String.class, value); for (final Object item : possible) { if (((StringValuedEnum) item).getValue().equals(test)) { ret = item; break; } } } else if (IntValuedEnum.class.isAssignableFrom(toType)) { final int test = coerce(Integer.TYPE, value); for (final Object item : possible) { if (((IntValuedEnum) item).getValue() == test) { ret = item; break; } } } else { throw new ConversionException("Invalid enum: " + value); } } return ret; } else if (Entity.class.isAssignableFrom(toType)) { final Long id = coerce(Long.class, value); return EntityHelper.reference(toType, id); } else if (Locale.class.isAssignableFrom(toType)) { return LocaleConverter.instance().valueOf(value.toString()); } else if (Collection.class.isAssignableFrom(toType)) { final Collection collection = (Collection) ClassHelper.instantiate(toType); final Iterator iterator = IteratorUtils.getIterator(value); while (iterator.hasNext()) { collection.add(iterator.next()); } return collection; } else if (toType.isArray()) { final Collection collection = coerceCollection(toType.getComponentType(), value); final Object[] array = (Object[]) Array.newInstance(toType.getComponentType(), collection.size()); return collection.toArray(array); } // We don't know how to convert the value throw new ConversionException("Cannot coerce value to: " + toType.getName()); }
From source file:com.thinkbiganalytics.metadata.modeshape.common.JcrObject.java
public <T> T getPropertyFromNode(Node node, String name, Class<T> type, boolean allowNotFound) { Object o = JcrPropertyUtil.getProperty(node, name, allowNotFound); if (allowNotFound && o == null) { return null; }/*from w ww. j av a 2 s. c om*/ if (type.isEnum()) { String savedType = o.toString(); if (StringUtils.isNotBlank(savedType)) { Class<? extends Enum> x = (Class<? extends Enum>) type; return (T) Enum.valueOf(x, savedType); } } if (!o.getClass().isAssignableFrom(type)) { //if it cant be matched and it is a Node > JcrObject, do the conversion if (o instanceof Node && JcrObject.class.isAssignableFrom(type)) { return JcrUtil.constructNodeObject((Node) o, type, null); } else { throw new MetadataRepositoryException("Unable to convert Property " + name + " to type " + type); } } else { return (T) o; } }