Example usage for java.lang Class isEnum

List of usage examples for java.lang Class isEnum

Introduction

In this page you can find the example usage for java.lang Class isEnum.

Prototype

public boolean isEnum() 

Source Link

Document

Returns true if and only if this class was declared as an enum in the source code.

Usage

From source file:ch.algotrader.esper.EngineImpl.java

private void initVariables(final Configuration configuration, final ConfigParams configParams) {

    Map<String, ConfigurationVariable> variables = configuration.getVariables();
    for (Map.Entry<String, ConfigurationVariable> entry : variables.entrySet()) {
        String variableName = entry.getKey().replace("_", ".");
        String value = configParams.getString(variableName);
        if (value != null) {
            String type = entry.getValue().getType();
            try {
                Class clazz = Class.forName(type);
                Object typedObj;//from  ww w . j  a  v a2s  . c  o  m
                if (clazz.isEnum()) {
                    typedObj = Enum.valueOf(clazz, value);
                } else if (clazz == BigDecimal.class) {
                    typedObj = new BigDecimal(value);
                } else {
                    typedObj = JavaClassHelper.parse(clazz, value);
                }
                entry.getValue().setInitializationValue(typedObj);
            } catch (ClassNotFoundException ex) {
                throw new InternalEngineException("Unknown variable type: " + type);
            }
        }
    }
}

From source file:com.evolveum.midpoint.web.page.admin.reports.component.RunReportPopupPanel.java

private InputPanel createTypedInputPanel(String componentId, IModel<JasperReportValueDto> model,
        String expression, JasperReportParameterDto param) {
    InputPanel panel;/*from w  ww.ja v  a2s  .  c  o  m*/
    Class<?> type;
    try {
        if (param.isMultiValue()) {
            type = param.getNestedType();
        } else {
            type = param.getType();
        }
    } catch (ClassNotFoundException e) {
        getSession().error("Could not find parameter type definition. Check the configuration.");
        throw new RestartResponseException(getPageBase());
    }

    if (type.isEnum()) {
        panel = WebComponentUtil.createEnumPanel(type, componentId, new PropertyModel<>(model, expression),
                this);
    } else if (XMLGregorianCalendar.class.isAssignableFrom(type)) {
        panel = new DatePanel(componentId, new PropertyModel<>(model, expression));
    } else if (param.getProperties() != null && param.getProperties().getTargetType() != null) { // render autocomplete box
        LookupTableType lookup = new LookupTableType();
        panel = new AutoCompleteTextPanel<String>(componentId,
                new LookupReportPropertyModel(model, expression, lookup, true), String.class) {

            private static final long serialVersionUID = 1L;

            @Override
            public Iterator<String> getIterator(String input) {
                return prepareAutoCompleteList(input, lookup, param).iterator();
            }
        };
    } else {
        panel = new TextPanel<>(componentId, new PropertyModel<>(model, expression), type);
    }
    List<FormComponent> components = panel.getFormComponents();
    for (FormComponent component : components) {
        component.add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
    }

    panel.setOutputMarkupId(true);
    return panel;
}

From source file:org.eclipse.wb.core.editor.actions.assistant.AbstractAssistantPage.java

/**
 * Creates {@link Group} for choosing one of the enum values for property.
 *//*from w w w.  ja va2 s  .  co m*/
protected final Group addEnumProperty(Composite parent, String property, String title, String enumClassName) {
    Object[][] titleAndValueArray;
    ClassLoader classLoader = GlobalState.getClassLoader();
    try {
        Class<?> enumClass = classLoader.loadClass(enumClassName);
        if (enumClass.isEnum()) {
            Enum<?>[] constants = (Enum<?>[]) enumClass.getEnumConstants();
            titleAndValueArray = new Object[constants.length][2];
            for (int i = 0; i < constants.length; i++) {
                Enum<?> constantValue = constants[i];
                titleAndValueArray[i][0] = constantValue.name();
                titleAndValueArray[i][1] = constantValue;
            }
        } else {
            titleAndValueArray = new Object[][] { {} };
        }
        return addChoiceProperty(parent, property, title, titleAndValueArray);
    } catch (ClassNotFoundException e) {
        DesignerPlugin.log(e);
        return new Group(parent, SWT.NONE);
    }
}

From source file:ch.algotrader.esper.EngineImpl.java

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setVariableValueFromString(String variableName, String value) {

    variableName = variableName.replace(".", "_");
    EPRuntime runtime = this.serviceProvider.getEPRuntime();
    if (runtime.getVariableValueAll().containsKey(variableName)) {
        Class clazz = runtime.getVariableValue(variableName).getClass();

        Object castedObj = null;/*from w w  w.  j  a  v  a 2 s .c o  m*/
        if (clazz.isEnum()) {
            castedObj = Enum.valueOf(clazz, value);
        } else {
            castedObj = JavaClassHelper.parse(clazz, value);
        }
        runtime.setVariableValue(variableName, castedObj);
    }
}

From source file:org.wso2.andes.configuration.AndesConfigurationManager.java

/**
 * Given the data type and the value read from a config, this returns the parsed value
 * of the property.//ww w  .j  a  v  a  2s  .  c  o  m
 *
 * @param key          The Key to the property being read (n xpath format as contained in file.)
 * @param dataType     Expected data type of the property
 * @param defaultValue This parameter should NEVER be null since we assign a default value to
 *                     every config property.
 * @param <T>          Expected data type of the property
 * @return Value of config in the expected data type.
 * @throws ConfigurationException
 */
public static <T> T deriveValidConfigurationValue(String key, Class<T> dataType, String defaultValue)
        throws ConfigurationException {

    if (log.isDebugEnabled()) {
        log.debug("Reading andes configuration value " + key);
    }

    String readValue = compositeConfiguration.getString(key);

    String validValue = defaultValue;

    // If the dataType is a Custom Config Module class, the readValue will be null (since the child properties
    // are the ones with values.). Therefore the warning is printed only in other situations.
    if (StringUtils.isBlank(readValue) && !CONFIG_MODULE_PACKAGE.equals(dataType.getPackage().getName())) {
        log.warn("Error when trying to read property : " + key + ". Switching to " + "default value : "
                + defaultValue);
    } else {
        validValue = overrideWithDecryptedValue(key, readValue);
    }

    if (log.isDebugEnabled()) {
        log.debug("Valid value read for andes configuration property " + key + " is : " + validValue);
    }

    try {

        if (Boolean.class.equals(dataType)) {
            return dataType.cast(Boolean.parseBoolean(validValue));

        } else if (Date.class.equals(dataType)) {
            // Sample date : "Sep 28 20:29:30 JST 2000"
            DateFormat df = new SimpleDateFormat("MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
            return dataType.cast(df.parse(validValue));

        } else if (dataType.isEnum()) {
            // this will indirectly forces programmer to define enum values in upper case
            return (T) Enum.valueOf((Class<? extends Enum>) dataType, validValue.toUpperCase(Locale.ENGLISH));

        } else if (CONFIG_MODULE_PACKAGE.equals(dataType.getPackage().getName())) {
            // Custom data structures defined within this package only need the root Xpath to extract the other
            // required child properties to construct the config object.
            return dataType.getConstructor(String.class).newInstance(key);

        } else {
            return dataType.getConstructor(String.class).newInstance(validValue);
        }

    } catch (NoSuchMethodException e) {
        throw new ConfigurationException(MessageFormat.format(GENERIC_CONFIGURATION_PARSE_ERROR, key), e);
    } catch (ParseException e) {
        throw new ConfigurationException(MessageFormat.format(GENERIC_CONFIGURATION_PARSE_ERROR, key), e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationException(MessageFormat.format(GENERIC_CONFIGURATION_PARSE_ERROR, key), e);
    } catch (InvocationTargetException e) {
        throw new ConfigurationException(MessageFormat.format(GENERIC_CONFIGURATION_PARSE_ERROR, key), e);
    } catch (InstantiationException e) {
        throw new ConfigurationException(MessageFormat.format(GENERIC_CONFIGURATION_PARSE_ERROR, key), e);
    }
}

From source file:org.modeldriven.fuml.assembly.ElementAssembler.java

private Object toEnumerationValue(String value, Classifier type) throws ClassNotFoundException,
        NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
    String pkg = metadata.getJavaPackageNameForClass(type);
    String qualifiedName = pkg + "." + type.getName();
    Class enumClass = Class.forName(qualifiedName);
    if (!enumClass.isEnum())
        throw new AssemblyException("expected class as enum, " + enumClass.getName());

    Method valueOf = enumClass.getMethod("valueOf", new Class[] { String.class });

    if (JavaKeyWords.getInstance().isKeyWord(value))
        value = value + "_";
    Object enumValue = valueOf.invoke(enumClass, value);
    return enumValue;
}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

protected ArrayNode buildReferencesArrayNode(final ObjectMapper objectMapper,
        final Map<URI, ObjectNode> schemaNodes, final Map<URI, LinkRelation> linkRelationCache,
        final Resource resource, final Prototype defaultPrototype) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final URI defaultSchemaUri = (defaultPrototype != null) ? defaultPrototype.getSchemaUri() : null;
    final String defaultSchemaName = (defaultPrototype != null)
            ? defaultPrototype.getUniqueName().getLocalName()
            : null;//w  w w.j a  va 2  s  .com

    final ArrayNode referencesNode = objectMapper.createArrayNode();

    final ConcurrentHashMap<URI, LinkTemplate> referenceTemplates = resource.getReferenceTemplates();
    final Set<URI> referenceRelationUris = referenceTemplates.keySet();

    if (referenceTemplates != null && !referenceTemplates.isEmpty()) {

        String selfResponseSchemaName = null;

        List<String> resourceParameterList = null;
        final UriTemplate uriTemplate = resource.getUriTemplate();
        final String[] parameterNames = uriTemplate.getParameterNames();
        if (parameterNames != null && parameterNames.length > 0) {

            resourceParameterList = new ArrayList<>();

            for (int i = 0; i < parameterNames.length; i++) {
                final String parameterName = parameterNames[i];

                URI keyedSchemaUri = null;

                if (defaultPrototype != null) {
                    final Set<String> allKeySlotNames = defaultPrototype.getAllKeySlotNames();
                    if (allKeySlotNames != null && allKeySlotNames.contains(parameterName)) {
                        keyedSchemaUri = defaultSchemaUri;
                    }
                }

                if (keyedSchemaUri == null) {

                    final Set<URI> referenceLinkRelationUris = resource
                            .getReferenceLinkRelationUris(Method.Get);
                    if (referenceLinkRelationUris != null && !referenceLinkRelationUris.isEmpty()) {
                        for (URI linkRelationUri : referenceLinkRelationUris) {
                            final LinkTemplate referenceTemplate = referenceTemplates.get(linkRelationUri);
                            final URI responseSchemaUri = referenceTemplate.getResponseSchemaUri();
                            final Prototype responseSchemaPrototype = schemaLoader
                                    .getPrototype(responseSchemaUri);
                            if (responseSchemaPrototype != null) {
                                final Set<String> allKeySlotNames = responseSchemaPrototype
                                        .getAllKeySlotNames();
                                if (allKeySlotNames != null && allKeySlotNames.contains(parameterName)) {
                                    keyedSchemaUri = responseSchemaUri;
                                    break;
                                }
                            }
                        }
                    }
                }

                String parameterTypeString = "?";

                if (keyedSchemaUri != null) {

                    final Prototype keyedPrototype = schemaLoader.getPrototype(keyedSchemaUri);
                    final ProtoSlot keyProtoSlot = keyedPrototype.getProtoSlot(parameterName);
                    if (keyProtoSlot instanceof PropertyProtoSlot) {
                        final PropertyProtoSlot keyPropertyProtoSlot = (PropertyProtoSlot) keyProtoSlot;
                        final ValueType parameterValueType = keyPropertyProtoSlot.getValueType();
                        final Type parameterHeapType = keyPropertyProtoSlot.getHeapValueType();
                        switch (parameterValueType) {
                        case Text: {
                            if (!String.class.equals(parameterHeapType)) {
                                final Class<?> syntaxClass = (Class<?>) parameterHeapType;
                                parameterTypeString = syntaxClass.getSimpleName();
                            } else {
                                parameterTypeString = parameterValueType.name();
                            }

                            break;
                        }
                        case SingleSelect: {
                            final Class<?> choicesEnumClass = (Class<?>) parameterHeapType;

                            if (choicesEnumClass.isEnum()) {
                                parameterTypeString = choicesEnumClass.getSimpleName();
                            } else {
                                // ?
                                parameterTypeString = parameterValueType.name();
                            }

                            break;
                        }
                        default: {
                            parameterTypeString = parameterValueType.name();
                            break;
                        }
                        }
                    }

                }

                resourceParameterList.add(parameterTypeString + " " + parameterName);
            }
        }

        for (final Method method : Method.values()) {
            for (final URI linkRelationUri : referenceRelationUris) {

                final LinkTemplate referenceTemplate = referenceTemplates.get(linkRelationUri);
                final LinkRelation linkRelation = getLinkRelation(linkRelationCache, linkRelationUri);

                if (method != linkRelation.getMethod()) {
                    continue;
                }

                final ObjectNode referenceNode = objectMapper.createObjectNode();
                referencesNode.add(referenceNode);

                referenceNode.put(PropertyName.method.name(), method.getProtocolGivenName());
                referenceNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));

                final String relationTitle = linkRelation.getTitle();
                referenceNode.put(PropertyName.relationTitle.name(), relationTitle);

                final URI responseSchemaUri = referenceTemplate.getResponseSchemaUri();
                String responseSchemaName = null;
                if (responseSchemaUri != null) {
                    final ObjectNode responseSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                            responseSchemaUri, schemaLoader);
                    referenceNode.put(PropertyName.responseSchema.name(), responseSchemaNode);

                    responseSchemaName = responseSchemaNode
                            .get(SchemaDesignFormatter.PropertyName.localName.name()).asText();
                }

                final URI requestSchemaUri = referenceTemplate.getRequestSchemaUri();

                String requestSchemaName = null;
                if (requestSchemaUri != null) {
                    final ObjectNode requestSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                            requestSchemaUri, schemaLoader);
                    referenceNode.put(PropertyName.requestSchema.name(), requestSchemaNode);

                    requestSchemaName = requestSchemaNode
                            .get(SchemaDesignFormatter.PropertyName.localName.name()).asText();
                }

                final StringBuilder signatureBuilder = new StringBuilder();

                if (responseSchemaName != null) {
                    signatureBuilder.append(responseSchemaName);
                } else {
                    signatureBuilder.append("void");
                }

                signatureBuilder.append(" ");

                String functionName = relationTitle;

                if (SystemLinkRelation.self.getUri().equals(linkRelationUri)) {
                    functionName = "get" + responseSchemaName;
                    selfResponseSchemaName = responseSchemaName;
                } else if (SystemLinkRelation.save.getUri().equals(linkRelationUri)) {
                    functionName = "save" + responseSchemaName;
                } else if (SystemLinkRelation.delete.getUri().equals(linkRelationUri)) {
                    functionName = "delete";
                    if (defaultSchemaName != null) {
                        functionName += defaultSchemaName;
                    } else if (selfResponseSchemaName != null) {
                        functionName += selfResponseSchemaName;
                    }
                }

                signatureBuilder.append(functionName).append(" ( ");

                String parameterString = null;
                if (resourceParameterList != null) {
                    final StringBuilder parameterStringBuilder = new StringBuilder();
                    final int parameterCount = resourceParameterList.size();
                    for (int i = 0; i < parameterCount; i++) {
                        final String parameter = resourceParameterList.get(i);
                        parameterStringBuilder.append(parameter);
                        if (i < parameterCount - 1) {
                            parameterStringBuilder.append(" , ");
                        }
                    }

                    parameterString = parameterStringBuilder.toString();
                    signatureBuilder.append(parameterString);
                }

                if (requestSchemaName != null) {
                    if (StringUtils.isNotBlank(parameterString)) {
                        signatureBuilder.append(" , ");
                    }

                    signatureBuilder.append(requestSchemaName);

                    signatureBuilder.append(" ");

                    final String parameterName = Character.toLowerCase(requestSchemaName.charAt(0))
                            + requestSchemaName.substring(1);
                    signatureBuilder.append(parameterName);
                }

                signatureBuilder.append(" ) ");

                final String signature = signatureBuilder.toString();
                referenceNode.put(PropertyName.signature.name(), signature);
            }

        }

    }

    return referencesNode;
}

From source file:org.apache.syncope.client.console.pages.ReportletConfModalPage.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private FieldPanel buildSinglePanel(final Class<?> type, final String fieldName, final String id) {
    FieldPanel result = null;//  w ww.  j  a va 2 s .c om
    PropertyModel model = new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName);
    if (ClassUtils.isAssignable(Boolean.class, type)) {
        result = new AjaxCheckBoxPanel(id, fieldName, model);
    } else if (ClassUtils.isAssignable(Number.class, type)) {
        result = new SpinnerFieldPanel<Number>(id, fieldName,
                (Class<Number>) ClassUtils.resolvePrimitiveIfNecessary(type), model, null, null);
    } else if (Date.class.equals(type)) {
        result = new DateTimeFieldPanel(id, fieldName, model, SyncopeConstants.DEFAULT_DATE_PATTERN);
    } else if (type.isEnum()) {
        result = new AjaxDropDownChoicePanel(id, fieldName, model)
                .setChoices(Arrays.asList(type.getEnumConstants()));
    }

    // treat as String if nothing matched above
    if (result == null) {
        result = new AjaxTextFieldPanel(id, fieldName, model);
    }

    return result;
}

From source file:com.mstiles92.plugins.stileslib.config.ConfigObject.java

@SuppressWarnings("rawtypes")
protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path, int depth)
        throws Exception {
    Class clazz = getClassAtDepth(field.getGenericType(), depth);
    if (ConfigObject.class.isAssignableFrom(clazz) && isConfigObject(obj)) {
        return getConfigObject((ConfigObject) obj, path, cs);
    } else if (Location.class.isAssignableFrom(clazz) && isLocation(obj)) {
        return getLocation((Location) obj);
    } else if (Vector.class.isAssignableFrom(clazz) && isVector(obj)) {
        return getVector((Vector) obj);
    } else if (Map.class.isAssignableFrom(clazz) && isMap(obj)) {
        return getMap((Map) obj, field, cs, path, depth);
    } else if (clazz.isEnum() && isEnum(clazz, obj)) {
        return getEnum((Enum) obj);
    } else if (List.class.isAssignableFrom(clazz) && isList(obj)) {
        Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
        if (ConfigObject.class.isAssignableFrom(subClazz) || Location.class.isAssignableFrom(subClazz)
                || Vector.class.isAssignableFrom(subClazz) || Map.class.isAssignableFrom(subClazz)
                || List.class.isAssignableFrom(subClazz) || subClazz.isEnum()) {
            return getList((List) obj, field, cs, path, depth);
        } else {//w  w  w.  ja va2  s.  c  o  m
            return obj;
        }
    } else {
        return obj;
    }
}

From source file:org.eclipse.smarthome.config.core.internal.ConfigMapper.java

private static Object objectConvert(Object value, Class<?> type) {
    Object result = value;//ww  w.j a  va2  s.  co  m
    // Handle the conversion case of BigDecimal to Float,Double,Long,Integer and the respective
    // primitive types
    String typeName = type.getSimpleName();
    if (value instanceof BigDecimal && !type.equals(BigDecimal.class)) {
        BigDecimal bdValue = (BigDecimal) value;
        if (type.equals(Float.class) || typeName.equals("float")) {
            result = bdValue.floatValue();
        } else if (type.equals(Double.class) || typeName.equals("double")) {
            result = bdValue.doubleValue();
        } else if (type.equals(Long.class) || typeName.equals("long")) {
            result = bdValue.longValue();
        } else if (type.equals(Integer.class) || typeName.equals("int")) {
            result = bdValue.intValue();
        }
    } else
    // Handle the conversion case of String to Float,Double,Long,Integer,BigDecimal,Boolean and the respective
    // primitive types
    if (value instanceof String && !type.equals(String.class)) {
        String bdValue = (String) value;
        if (type.equals(Float.class) || typeName.equals("float")) {
            result = Float.valueOf(bdValue);
        } else if (type.equals(Double.class) || typeName.equals("double")) {
            result = Double.valueOf(bdValue);
        } else if (type.equals(Long.class) || typeName.equals("long")) {
            result = Long.valueOf(bdValue);
        } else if (type.equals(BigDecimal.class)) {
            result = new BigDecimal(bdValue);
        } else if (type.equals(Integer.class) || typeName.equals("int")) {
            result = Integer.valueOf(bdValue);
        } else if (type.equals(Boolean.class) || typeName.equals("boolean")) {
            result = Boolean.valueOf(bdValue);
        } else if (type.isEnum()) {
            @SuppressWarnings({ "rawtypes", "unchecked" })
            final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
            @SuppressWarnings({ "unchecked" })
            final Enum<?> enumvalue = Enum.valueOf(enumType, value.toString());
            result = enumvalue;
        } else if (Collection.class.isAssignableFrom(type)) {
            result = Collections.singletonList(value);
        }
    }
    return result;
}