List of usage examples for java.lang Class getEnumConstants
public T[] getEnumConstants()
From source file:io.github.benas.jpopulator.impl.DefaultRandomizer.java
/** * Generate a random value for the given type. * * @param type the type for which a random value will be generated * @return a random value for the given type or null if the type is not supported */// w w w. jav a2s . co m public static Object getRandomValue(final Class type) { /* * String and Character types */ if (type.equals(String.class)) { return RandomStringUtils.randomAlphabetic(ConstantsUtil.DEFAULT_STRING_LENGTH); } if (type.equals(Character.TYPE) || type.equals(Character.class)) { return RandomStringUtils.randomAlphabetic(1).charAt(0); } /* * Boolean type */ if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) { return ConstantsUtil.RANDOM.nextBoolean(); } /* * Numeric types */ if (type.equals(Byte.TYPE) || type.equals(Byte.class)) { return (byte) (ConstantsUtil.RANDOM.nextInt()); } if (type.equals(Short.TYPE) || type.equals(Short.class)) { return (short) (ConstantsUtil.RANDOM.nextInt()); } if (type.equals(Integer.TYPE) || type.equals(Integer.class)) { return ConstantsUtil.RANDOM.nextInt(); } if (type.equals(Long.TYPE) || type.equals(Long.class)) { return ConstantsUtil.RANDOM.nextLong(); } if (type.equals(Double.TYPE) || type.equals(Double.class)) { return ConstantsUtil.RANDOM.nextDouble(); } if (type.equals(Float.TYPE) || type.equals(Float.class)) { return ConstantsUtil.RANDOM.nextFloat(); } if (type.equals(BigInteger.class)) { return new BigInteger( Math.abs(ConstantsUtil.RANDOM.nextInt(ConstantsUtil.DEFAULT_BIG_INTEGER_NUM_BITS_LENGTH)), ConstantsUtil.RANDOM); } if (type.equals(BigDecimal.class)) { return new BigDecimal(ConstantsUtil.RANDOM.nextDouble()); } if (type.equals(AtomicLong.class)) { return new AtomicLong(ConstantsUtil.RANDOM.nextLong()); } if (type.equals(AtomicInteger.class)) { return new AtomicInteger(ConstantsUtil.RANDOM.nextInt()); } /* * Date and time types */ if (type.equals(java.util.Date.class)) { return ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue(); } if (type.equals(java.sql.Date.class)) { return new java.sql.Date(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(java.sql.Time.class)) { return new java.sql.Time(ConstantsUtil.RANDOM.nextLong()); } if (type.equals(java.sql.Timestamp.class)) { return new java.sql.Timestamp(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(Calendar.class)) { return Calendar.getInstance(); } if (type.equals(org.joda.time.DateTime.class)) { return new org.joda.time.DateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.LocalDate.class)) { return new org.joda.time.LocalDate(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.LocalTime.class)) { return new org.joda.time.LocalTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.LocalDateTime.class)) { return new org.joda.time.LocalDateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.Duration.class)) { return new org.joda.time.Duration(Math.abs(ConstantsUtil.RANDOM.nextLong())); } if (type.equals(org.joda.time.Period.class)) { return new org.joda.time.Period(Math.abs(ConstantsUtil.RANDOM.nextInt())); } if (type.equals(org.joda.time.Interval.class)) { long startDate = Math.abs(ConstantsUtil.RANDOM.nextInt()); long endDate = startDate + Math.abs(ConstantsUtil.RANDOM.nextInt()); return new org.joda.time.Interval(startDate, endDate); } /* * Enum type */ if (type.isEnum() && type.getEnumConstants().length > 0) { Object[] enumConstants = type.getEnumConstants(); return enumConstants[ConstantsUtil.RANDOM.nextInt(enumConstants.length)]; } /* * Return null for any unsupported type */ return null; }
From source file:org.cloudgraph.store.mapping.StoreMapping.java
private CloudGraphStoreMapping deriveMapping() throws NoSuchFieldException, SecurityException { if (log.isDebugEnabled()) log.debug("deriving mapping"); CloudGraphStoreMapping result = new CloudGraphStoreMapping(); for (Class<?> c : this.annotatedClasses) { org.cloudgraph.store.mapping.annotation.Table tableAnnot = c .getAnnotation(org.cloudgraph.store.mapping.annotation.Table.class); if (log.isDebugEnabled()) log.debug("discovered " + tableAnnot.name() + " table mapping"); Table table = new Table(); result.getTables().add(table);/*from w w w . ja v a 2 s .com*/ table.setName(tableAnnot.name()); table.setDataColumnFamilyName(tableAnnot.dataColumnFamilyName()); table.setTombstoneRows(tableAnnot.tombstoneRows()); table.setTombstoneRowsOverwriteable(tableAnnot.tombstoneRowsOverwriteable()); table.setUniqueChecks(tableAnnot.uniqueChecks()); if (tableAnnot.hashAlgorithm().ordinal() != HashAlgorithmName.NONE.ordinal()) { HashAlgorithm hash = new HashAlgorithm(); hash.setName(tableAnnot.hashAlgorithm()); table.setHashAlgorithm(hash); } // add properties DataGraph dataGraph = new DataGraph(); table.getDataGraphs().add(dataGraph); org.plasma.sdo.annotation.Type typeAnnot = c.getAnnotation(org.plasma.sdo.annotation.Type.class); String typeName = typeAnnot.name(); if (typeName == null || typeName.trim().length() == 0) typeName = c.getSimpleName(); // use the enumeration class name dataGraph.setType(typeName); org.plasma.sdo.annotation.Namespace namespaceAnnot = c.getPackage() .getAnnotation(org.plasma.sdo.annotation.Namespace.class); dataGraph.setUri(namespaceAnnot.uri()); if (log.isDebugEnabled()) log.debug("added data graph for type: " + dataGraph.getUri() + "#" + dataGraph.getType()); ColumnKeyModel columnModel = new ColumnKeyModel(); columnModel.setFieldDelimiter("|"); columnModel.setReferenceMetadataDelimiter("#"); columnModel.setSequenceDelimiter("@"); dataGraph.setColumnKeyModel(columnModel); ColumnKeyField pkgColKeyField = new ColumnKeyField(); pkgColKeyField.setName(MetaFieldName.PKG); columnModel.getColumnKeyFields().add(pkgColKeyField); ColumnKeyField typeColKeyField = new ColumnKeyField(); typeColKeyField.setName(MetaFieldName.TYPE); columnModel.getColumnKeyFields().add(typeColKeyField); ColumnKeyField propColKeyField = new ColumnKeyField(); propColKeyField.setName(MetaFieldName.PROPERTY); columnModel.getColumnKeyFields().add(propColKeyField); RowKeyModel rowKeyModel = new RowKeyModel(); dataGraph.setRowKeyModel(rowKeyModel); rowKeyModel.setFieldDelimiter(tableAnnot.rowKeyFieldDelimiter()); for (Object o : c.getEnumConstants()) { Enum<?> enm = (Enum<?>) o; Field field = c.getField(enm.name()); org.cloudgraph.store.mapping.annotation.RowKeyField rowKeyFieldAnnot = field .getAnnotation(org.cloudgraph.store.mapping.annotation.RowKeyField.class); if (rowKeyFieldAnnot != null) { RowKeyField rowKeyField = new RowKeyField(); rowKeyModel.getRowKeyFields().add(rowKeyField); DataField userDefinedField = new DataField(); rowKeyField.setDataField(userDefinedField); userDefinedField.setPath(field.getName()); userDefinedField.setCodecType(rowKeyFieldAnnot.codecType()); } } } return result; }
From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java
@SuppressWarnings("unchecked") private JComponent initializeJComponentForParameter(final String strValue, final ParameterInfo info) throws ModelInformationException { JComponent field = null;/* w w w. j av a2 s . co m*/ if (info.isBoolean()) { field = new JCheckBox(); boolean value = Boolean.parseBoolean(strValue); ((JCheckBox) field).setSelected(value); } else if (info.isEnum() || info instanceof MasonChooserParameterInfo) { Object[] elements = null; if (info.isEnum()) { final Class<Enum<?>> type = (Class<Enum<?>>) info.getJavaType(); elements = type.getEnumConstants(); } else { final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) info; elements = chooserInfo.getValidStrings(); } final JComboBox list = new JComboBox(elements); if (info.isEnum()) { try { @SuppressWarnings("rawtypes") final Object value = Enum.valueOf((Class<? extends Enum>) info.getJavaType(), strValue); list.setSelectedItem(value); } catch (final IllegalArgumentException e) { throw new ModelInformationException(e.getMessage() + " for parameter: " + info.getName() + "."); } } else { try { final int value = Integer.parseInt(strValue); list.setSelectedIndex(value); } catch (final NumberFormatException e) { throw new ModelInformationException( "Invalid value for parameter " + info.getName() + " (not a number)."); } } field = list; } else if (info.isFile()) { field = new JPanel(); final JTextField textField = new JTextField(); if (!strValue.isEmpty()) { final File file = new File(strValue); textField.setText(file.getName()); textField.setToolTipText(file.getAbsolutePath()); } field.add(textField); } else if (info instanceof MasonIntervalParameterInfo) { field = new JPanel(); final JTextField textField = new JTextField(strValue); field.add(textField); } else { field = new JTextField(strValue); } return field; }
From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java
/** Edits the information object <code>info</code> so this method fills the appropriate * components with the informations of <code>info</code>. *//*from w w w . ja v a 2 s. co m*/ private void edit(final ParameterInfo info) { changeText(info.getName(), info.getType()); if (info instanceof SubmodelInfo) { final SubmodelInfo sInfo = (SubmodelInfo) info; editSubmodelInfo(sInfo); } else { String view = null; switch (info.getDefinitionType()) { case ParameterInfo.CONST_DEF: { if (info.isEnum() || info instanceof MasonChooserParameterInfo) { view = "ENUM"; constDef.setSelected(true); incrDef.setEnabled(false); listDef.setEnabled(false); Object[] elements = null; if (info.isEnum()) { @SuppressWarnings("unchecked") final Class<Enum<?>> type = (Class<Enum<?>>) info.getJavaType(); elements = type.getEnumConstants(); } else { final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) info; elements = chooserInfo.getValidStrings(); } final DefaultComboBoxModel model = (DefaultComboBoxModel) enumDefBox.getModel(); model.removeAllElements(); for (final Object object : elements) { model.addElement(object); } if (info.isEnum()) enumDefBox.setSelectedItem(info.getValue()); else enumDefBox.setSelectedIndex((Integer) info.getValue()); } else if (info.isFile()) { view = "FILE"; constDef.setSelected(true); final File file = (File) info.getValue(); if (file != null) { fileTextField.setText(file.getName()); fileTextField.setToolTipText(file.getAbsolutePath()); } } else { view = "CONST"; constDef.setSelected(true); constDefField.setText(info.valuesToString()); } break; } case ParameterInfo.LIST_DEF: view = "LIST"; listDef.setSelected(true); listDefArea.setText(info.valuesToString()); break; case ParameterInfo.INCR_DEF: view = "INCREMENT"; incrDef.setSelected(true); incrStartValueField.setText(info.startToString()); incrEndValueField.setText(info.endToString()); incrStepField.setText(info.stepToString()); } final CardLayout cl = (CardLayout) rightMiddle.getLayout(); cl.show(rightMiddle, view); enableDisableSettings(true); if (!info.isNumeric()) incrDef.setEnabled(false); if (info.isEnum() || info instanceof MasonChooserParameterInfo || info.isFile()) { incrDef.setEnabled(false); listDef.setEnabled(false); } modifyButton.setEnabled(true); } }
From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) { try {/*from ww w . ja va 2s. c o m*/ T item = clazz.newInstance(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) { Method writeMethod = pd.getWriteMethod(); if (writeMethod == null || pd.getReadMethod() == null || // countrolParam.getExcludeFieldList() != null && countrolParam.getExcludeFieldList().contains(pd.getName())// ) {// continue; } Class fieldClazz = pd.getPropertyType(); Long numIndex = countrolParam.getNumIndex(); // int enumIndex = countrolParam.getEnumIndex(); Random random = countrolParam.getRandom(); long strIndex = countrolParam.getStrIndex(); int charIndex = countrolParam.getCharIndex(); Calendar time = countrolParam.getTime(); if (TypeUtil.isBaseType(fieldClazz)) { if (TypeUtil.isNumberType(fieldClazz)) { if (fieldClazz == Byte.class) { writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F))); } else if (fieldClazz == Short.class) { writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF))); } else if (fieldClazz == Integer.class) { writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF))); } else if (fieldClazz == Long.class) { writeMethod.invoke(item, Long.valueOf((long) numIndex)); } else if (fieldClazz == Float.class) { writeMethod.invoke(item, Float.valueOf((float) numIndex)); } else if (fieldClazz == Double.class) { writeMethod.invoke(item, Double.valueOf((double) numIndex)); } else if (fieldClazz == byte.class) {// writeMethod.invoke(item, (byte) (numIndex & 0x7F)); } else if (fieldClazz == short.class) { writeMethod.invoke(item, (short) (numIndex & 0x7FFF)); } else if (fieldClazz == int.class) { writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF)); } else if (fieldClazz == long.class) { writeMethod.invoke(item, (long) numIndex); } else if (fieldClazz == float.class) { writeMethod.invoke(item, (float) numIndex); } else if (fieldClazz == double.class) { writeMethod.invoke(item, (double) numIndex); } numIndex++; if (numIndex < 0) { numIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setNumIndex(numIndex); } else if (fieldClazz == boolean.class) { writeMethod.invoke(item, random.nextBoolean()); } else if (fieldClazz == Boolean.class) { writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean())); } else if (fieldClazz == char.class) { writeMethod.invoke(item, CHAR_RANGE[charIndex]); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == Character.class) { writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == String.class) { if (countrolParam.getUniqueFieldList() != null && countrolParam.getUniqueFieldList().contains(pd.getName())) { StringBuilder sb = new StringBuilder(); convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb); writeMethod.invoke(item, sb.toString()); strIndex += countrolParam.getStrStep(); if (strIndex < 0) { strIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setStrIndex(strIndex); } else { writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } } else if (fieldClazz == Date.class) { writeMethod.invoke(item, time.getTime()); time.add(Calendar.DAY_OF_YEAR, 1); } else if (fieldClazz.isEnum()) { int index = random.nextInt(fieldClazz.getEnumConstants().length); writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]); } else { // throw new RuntimeException("out of countrol Class " + fieldClazz.getName()); } } else { parseClassList.push(fieldClazz); // TODO ? Set<Class> set = new HashSet<Class>(parseClassList); if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) { Object bean = produceBean(fieldClazz, countrolParam, parseClassList); writeMethod.invoke(item, bean); } parseClassList.pop(); } } return item; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java
protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception { HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>(); RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager(); if (xmlNodeInfo != null) { if (xmlNodeInfo.isInheritable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); propertyTemplate = new AutoPropertyTemplate("parent"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); }/* ww w .j a va 2s . c o m*/ if (xmlNodeInfo.isScopable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope"); propertyTemplate.setPrimitive(true); Object[] ecs = Scope.class.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); properties.put(propertyTemplate.getName(), propertyTemplate); } if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) { Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType()); if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } if (InterceptableDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } } for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) { String propertyName = entry.getKey(); String value = entry.getValue(); AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName); propertyTemplate.setDefaultValue(value); propertyTemplate.setPrimitive(true); propertyTemplate.setFixed(true); propertyTemplate.setVisible(false); properties.put(propertyName, propertyTemplate); } for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) { String propertyName = entry.getKey(); XmlProperty xmlProperty = entry.getValue(); TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType()); Class<?> propertyType = null; if (propertyTypeInfo != null) { propertyType = propertyTypeInfo.getType(); } AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); if (propertyType != null && !propertyType.equals(String.class)) { propertyTemplate.setType(propertyType.getName()); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); properties.put(propertyName, propertyTemplate); } } PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && propertyDescriptor.getWriteMethod() != null) { if (readMethod.getDeclaringClass() != type) { try { readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes()); } catch (NoSuchMethodException e) { continue; } } String propertyName = propertyDescriptor.getName(); XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class); if (xmlSubNode != null) { continue; } TypeInfo propertyTypeInfo; Class<?> propertyType = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(propertyType)) { propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true); propertyType = propertyTypeInfo.getType(); } else { propertyTypeInfo = new TypeInfo(propertyType, false); } AutoPropertyTemplate propertyTemplate = null; XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class); if (xmlProperty != null) { if (xmlProperty.unsupported()) { continue; } propertyTemplate = properties.get(propertyName); if (propertyTemplate == null) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); } if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName) || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) { propertyTemplate.setHighlight(1); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes()); if (clientTypes > 0) { propertyTemplate.setClientTypes(clientTypes); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class) || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); } if (propertyTemplate != null) { propertyTemplate.setType(propertyDescriptor.getPropertyType().getName()); if (propertyType.isEnum()) { Object[] ecs = propertyType.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); } ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class); if (componentReference != null) { ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager, componentReference.value(), "id"); propertyTemplate.setReference(referenceTemplate); } IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class); if (ideProperty != null) { propertyTemplate.setVisible(ideProperty.visible()); propertyTemplate.setEditor(ideProperty.editor()); propertyTemplate.setHighlight(ideProperty.highlight()); if (StringUtils.isNotEmpty(ideProperty.enumValues())) { propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;")); } } ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class); if (clientProperty != null) { propertyTemplate.setDefaultValue(clientProperty.escapeValue()); } properties.put(propertyName, propertyTemplate); } } } return properties.values(); }
From source file:fr.esrf.icat.manager.core.part.EntityEditDialog.java
@Override protected Control createDialogArea(final Composite parent) { final Composite container = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(3, false); layout.marginRight = 5;//www . j a v a 2s .c o m layout.marginLeft = 10; container.setLayout(layout); comboMapping = new HashMap<>(); fieldValues = new HashMap<>(); // we are sure we have at least one entity, use the 1st one for anything general (field types, etc.) final WrappedEntityBean firstEntity = entities.get(0); for (final String field : firstEntity.getMutableFields()) { Label lblAuthn = new Label(container, SWT.NONE); lblAuthn.setText(StringUtils.capitalize(field) + ":"); final Button checkEdit = new Button(container, SWT.CHECK); checkEdit.setEnabled(false); checkEdit.setVisible(false); final Class<?> clazz = firstEntity.getReturnType(field); Object initialValue = null; boolean notSet = true; for (WrappedEntityBean entity : entities) { try { Object value = entity.get(field); if (notSet) { initialValue = value; notSet = false; } else if ((null == value && null != initialValue) || (null != value && !value.equals(initialValue))) { initialValue = null; checkEdit.setImage(MULTI_IMAGE); checkEdit.setSelection(false); checkEdit.setEnabled(true); checkEdit.setVisible(true); break; } } catch (Exception e) { LOG.error("Error getting initial value for " + field, e); } } final boolean hasInitialValue = initialValue != null; if (firstEntity.isEntity(field)) { final Combo combo = new Combo(container, SWT.DROP_DOWN | SWT.BORDER); new Label(container, SWT.NONE); //empty left label final Label label = new Label(container, SWT.RIGHT); label.setLayoutData(new GridData(SWT.END, SWT.CENTER, true, false)); label.setImage(WARNING_IMAGE); final Label warningLabel = new Label(container, SWT.LEFT); warningLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, true, false)); combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); final EntityListProposalContentProvider proposalProvider = new EntityListProposalContentProvider( client, firstEntity.getReturnType(field).getSimpleName(), initialValue, label, warningLabel, container); warningLabel.setText(proposalProvider.getCurrentFilter()); final ContentProposalAdapter contentProposalAdapter = new ContentProposalAdapter(combo, new ComboContentAdapter(), proposalProvider, DEFAULT_KEYSTROKE, DEFAULT_ACTIVATION_CHARS); contentProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); contentProposalAdapter.setPropagateKeys(true); contentProposalAdapter.setAutoActivationDelay(1000); contentProposalAdapter.addContentProposalListener(new IContentProposalListener2() { @Override public void proposalPopupOpened(ContentProposalAdapter adapter) { } @Override public void proposalPopupClosed(ContentProposalAdapter adapter) { // when the proposal popup closes we set the content of the combo to the proposals final String[] currentItems = proposalProvider.getCurrentItems(); if (currentItems != null && currentItems.length > 0) { combo.setItems(currentItems); } final String currentText = proposalProvider.getCurrentText(); final int caretPosition = proposalProvider.getCaretPosition(); combo.setText(currentText); combo.setSelection(new Point(caretPosition, caretPosition)); } }); combo.setItems(proposalProvider.getInitialItems()); if (hasInitialValue) { combo.select(0); } comboMapping.put(field, new ImmutablePair<Object[], Combo>(new Object[] { proposalProvider }, combo)); if (checkEdit.isEnabled()) { combo.setEnabled(false); checkEdit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { combo.setEnabled(checkEdit.getSelection()); } }); } } else if (Enum.class.isAssignableFrom(clazz)) { final Combo combo = new Combo(container, SWT.DROP_DOWN | SWT.BORDER); final Object[] c = clazz.getEnumConstants(); final String[] s = new String[c.length]; int selected = -1; for (int i = 0; i < c.length; i++) { s[i] = c[i].toString(); if (initialValue != null && c[i].equals(initialValue)) { selected = i; } } // replacement for AutocompleteComboSelector to avoid selecting the 1st value in the combo when // no proposal is accepted (or field is emptied) new AutocompleteCombo(combo) { @Override protected AutocompleteContentProposalProvider getContentProposalProvider(String[] proposals) { return new AutocompleteSelectorContentProposalProvider(proposals, this.combo); } }; combo.setItems(s); if (selected >= 0) { combo.select(selected); } combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); comboMapping.put(field, new ImmutablePair<Object[], Combo>(c, combo)); if (checkEdit.isEnabled()) { combo.setEnabled(false); checkEdit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { combo.setEnabled(checkEdit.getSelection()); } }); } } else if (clazz.equals(Boolean.class) || clazz.equals(boolean.class)) { final Button btn = new Button(container, SWT.CHECK); btn.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); if (null == initialValue) { if (isSingle) { try { firstEntity.set(field, Boolean.FALSE); } catch (Exception e) { LOG.error("Error setting " + field + " to " + Boolean.FALSE); } } } else { btn.setSelection((Boolean) initialValue); } btn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean value = btn.getSelection(); fieldValues.put(field, value); } }); if (checkEdit.isEnabled()) { btn.setEnabled(false); checkEdit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final boolean selected = checkEdit.getSelection(); btn.setEnabled(selected); if (selected) { fieldValues.put(field, btn.getSelection()); } else { fieldValues.remove(field); } } }); } } else if (Calendar.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz) || XMLGregorianCalendar.class.isAssignableFrom(clazz)) { final CDateTime cdt = new CDateTime(container, CDT.BORDER | CDT.SPINNER | CDT.TAB_FIELDS | CDT.DATE_MEDIUM | CDT.TIME_MEDIUM); cdt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); if (null != initialValue) { Date initialDate = null; if (initialValue instanceof Calendar) { initialDate = ((Calendar) initialValue).getTime(); } else if (initialValue instanceof XMLGregorianCalendar) { initialDate = ((XMLGregorianCalendar) initialValue).toGregorianCalendar().getTime(); } else if (initialValue instanceof Date) { initialDate = (Date) initialValue; } cdt.setSelection(initialDate); } cdt.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fieldValues.put(field, makeCorrectDateValue(clazz, cdt.getSelection())); } }); if (checkEdit.isEnabled()) { cdt.setEnabled(false); checkEdit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final boolean selected = checkEdit.getSelection(); cdt.setEnabled(selected); if (selected) { fieldValues.put(field, makeCorrectDateValue(clazz, cdt.getSelection())); } else { fieldValues.remove(field); } } }); } } else if (Number.class.isAssignableFrom(clazz)) { final Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); if (null != initialValue) { text.setText(initialValue.toString()); } final Color original = text.getForeground(); text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { text.setForeground(original); String value = text.getText(); if (null == value) { value = ICATEntity.EMPTY_STRING; } final Object numVal = makeCorrectNumericValue(clazz, value); if (null == numVal) { text.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_RED)); } else { fieldValues.put(field, numVal); } } }); if (checkEdit.isEnabled()) { text.setEnabled(false); checkEdit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final boolean selected = checkEdit.getSelection(); text.setEnabled(selected); if (selected) { fieldValues.put(field, makeCorrectNumericValue(clazz, text.getText())); } else { fieldValues.remove(field); } } }); } } else { // Assumes String final Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); if (null == initialValue) { if (isSingle) { try { firstEntity.set(field, ICATEntity.EMPTY_STRING); } catch (Exception e) { LOG.error("Error setting " + field + " to EMPTY_STRING"); } } } else { text.setText(initialValue.toString()); } text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String value = text.getText(); if (null == value) { value = ICATEntity.EMPTY_STRING; } fieldValues.put(field, value); } }); if (checkEdit.isEnabled()) { text.setEnabled(false); checkEdit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final boolean selected = checkEdit.getSelection(); text.setEnabled(selected); if (selected) { fieldValues.put(field, text.getText()); } else { fieldValues.remove(field); } } }); } } } return container; }
From source file:tufts.vue.LWComponent.java
String getDescriptionOfSetBits(Class enumType, long bits) { final StringBuilder buf = new StringBuilder(); //buf.append(enumType.getSimpleName()); buf.append(enumType.getSimpleName().substring(0, 2)); buf.append('('); boolean first = true; for (Object eValue : enumType.getEnumConstants()) { final Enum e = (Enum) eValue; if ((bits & (1 << e.ordinal())) != 0) { if (!first) buf.append(','); buf.append(eValue);/*from w w w. j a va 2 s . com*/ //buf.append(':');buf.append(e.ordinal()); first = false; } } buf.append(')'); return buf.toString(); }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * do a case-insensitive matching/*from w w w . j a v a 2s .c o m*/ * @param theEnumClass class of the enum * @param <E> generic type * * @param string * @param exceptionOnNotFound true if exception should be thrown on not found * @return the enum or null or exception if not found * @throws RuntimeException if there is a problem */ public static <E extends Enum<?>> E enumValueOfIgnoreCase(Class<E> theEnumClass, String string, boolean exceptionOnNotFound) throws RuntimeException { if (!exceptionOnNotFound && isBlank(string)) { return null; } for (E e : theEnumClass.getEnumConstants()) { if (equalsIgnoreCase(string, e.name())) { return e; } } StringBuilder error = new StringBuilder("Cant find " + theEnumClass.getSimpleName() + " from string: '") .append(string); error.append("', expecting one of: "); for (E e : theEnumClass.getEnumConstants()) { error.append(e.name()).append(", "); } throw new RuntimeException(error.toString()); }
From source file:org.structr.core.script.ScriptingTest.java
@Test public void testSetPropertyWithDynamicNodes() { this.cleanDatabaseAndSchema(); /**//from ww w .j av a 2 s .c o m * This test creates two connected SchemaNodes and tests the script-based * association of one instance with several others in the onCreate method. */ final long currentTimeMillis = System.currentTimeMillis(); Class sourceType = null; Class targetType = null; PropertyKey targetsProperty = null; EnumProperty testEnumProperty = null; PropertyKey testBooleanProperty = null; PropertyKey testIntegerProperty = null; PropertyKey testStringProperty = null; PropertyKey testDoubleProperty = null; PropertyKey testDateProperty = null; Class testEnumType = null; // setup phase: create schema nodes try (final Tx tx = app.tx()) { // create two nodes and associate them with each other final SchemaNode sourceNode = createTestNode(SchemaNode.class, "Source"); final SchemaNode targetNode = createTestNode(SchemaNode.class, "Target"); final List<SchemaProperty> properties = new LinkedList<>(); properties.add(createTestNode(SchemaProperty.class, new NodeAttribute(AbstractNode.name, "testBoolean"), new NodeAttribute(SchemaProperty.propertyType, "Boolean"))); properties.add(createTestNode(SchemaProperty.class, new NodeAttribute(AbstractNode.name, "testInteger"), new NodeAttribute(SchemaProperty.propertyType, "Integer"))); properties.add(createTestNode(SchemaProperty.class, new NodeAttribute(AbstractNode.name, "testString"), new NodeAttribute(SchemaProperty.propertyType, "String"))); properties.add(createTestNode(SchemaProperty.class, new NodeAttribute(AbstractNode.name, "testDouble"), new NodeAttribute(SchemaProperty.propertyType, "Double"))); properties.add(createTestNode(SchemaProperty.class, new NodeAttribute(AbstractNode.name, "testEnum"), new NodeAttribute(SchemaProperty.propertyType, "Enum"), new NodeAttribute(SchemaProperty.format, "OPEN, CLOSED, TEST"))); properties.add(createTestNode(SchemaProperty.class, new NodeAttribute(AbstractNode.name, "testDate"), new NodeAttribute(SchemaProperty.propertyType, "Date"))); sourceNode.setProperty(SchemaNode.schemaProperties, properties); final List<SchemaMethod> methods = new LinkedList<>(); methods.add(createTestNode(SchemaMethod.class, new NodeAttribute(AbstractNode.name, "onCreate"), new NodeAttribute(SchemaMethod.source, "{ var e = Structr.get('this'); e.targets = Structr.find('Target'); }"))); methods.add(createTestNode(SchemaMethod.class, new NodeAttribute(AbstractNode.name, "doTest01"), new NodeAttribute(SchemaMethod.source, "{ var e = Structr.get('this'); e.testEnum = 'OPEN'; }"))); methods.add(createTestNode(SchemaMethod.class, new NodeAttribute(AbstractNode.name, "doTest02"), new NodeAttribute(SchemaMethod.source, "{ var e = Structr.get('this'); e.testEnum = 'CLOSED'; }"))); methods.add(createTestNode(SchemaMethod.class, new NodeAttribute(AbstractNode.name, "doTest03"), new NodeAttribute(SchemaMethod.source, "{ var e = Structr.get('this'); e.testEnum = 'TEST'; }"))); methods.add(createTestNode(SchemaMethod.class, new NodeAttribute(AbstractNode.name, "doTest04"), new NodeAttribute(SchemaMethod.source, "{ var e = Structr.get('this'); e.testEnum = 'INVALID'; }"))); methods.add(createTestNode(SchemaMethod.class, new NodeAttribute(AbstractNode.name, "doTest05"), new NodeAttribute(SchemaMethod.source, "{ var e = Structr.get('this'); e.testBoolean = true; e.testInteger = 123; e.testString = 'testing..'; e.testDouble = 1.2345; e.testDate = new Date(" + currentTimeMillis + "); }"))); sourceNode.setProperty(SchemaNode.schemaMethods, methods); final PropertyMap propertyMap = new PropertyMap(); propertyMap.put(SchemaRelationshipNode.sourceId, sourceNode.getUuid()); propertyMap.put(SchemaRelationshipNode.targetId, targetNode.getUuid()); propertyMap.put(SchemaRelationshipNode.sourceJsonName, "source"); propertyMap.put(SchemaRelationshipNode.targetJsonName, "targets"); propertyMap.put(SchemaRelationshipNode.sourceMultiplicity, "*"); propertyMap.put(SchemaRelationshipNode.targetMultiplicity, "*"); propertyMap.put(SchemaRelationshipNode.relationshipType, "HAS"); app.create(SchemaRelationshipNode.class, propertyMap); tx.success(); } catch (Throwable t) { t.printStackTrace(); fail("Unexpected exception."); } try (final Tx tx = app.tx()) { final ConfigurationProvider config = StructrApp.getConfiguration(); sourceType = config.getNodeEntityClass("Source"); targetType = config.getNodeEntityClass("Target"); targetsProperty = StructrApp.key(sourceType, "targets"); // we need to cast to EnumProperty in order to obtain the dynamic enum type testEnumProperty = (EnumProperty) StructrApp.key(sourceType, "testEnum"); testEnumType = testEnumProperty.getEnumType(); testBooleanProperty = StructrApp.key(sourceType, "testBoolean"); testIntegerProperty = StructrApp.key(sourceType, "testInteger"); testStringProperty = StructrApp.key(sourceType, "testString"); testDoubleProperty = StructrApp.key(sourceType, "testDouble"); testDateProperty = StructrApp.key(sourceType, "testDate"); assertNotNull(sourceType); assertNotNull(targetType); assertNotNull(targetsProperty); // create 5 target nodes createTestNodes(targetType, 5); // create source node createTestNodes(sourceType, 5); tx.success(); } catch (Throwable t) { t.printStackTrace(); fail("Unexpected exception."); } // check phase: source node should have all five target nodes associated with HAS try (final Tx tx = app.tx()) { // check all source nodes for (final Object obj : app.nodeQuery(sourceType).getAsList()) { assertNotNull("Invalid nodeQuery result", obj); final GraphObject sourceNode = (GraphObject) obj; // test contents of "targets" property final Object targetNodesObject = sourceNode.getProperty(targetsProperty); assertTrue("Invalid getProperty result for scripted association", targetNodesObject instanceof List); final List list = (List) targetNodesObject; assertEquals("Invalid getProperty result for scripted association", 5, list.size()); } final GraphObject sourceNode = app.nodeQuery(sourceType).getFirst(); // set testEnum property to OPEN via doTest01 function call, check result sourceNode.invokeMethod("doTest01", Collections.EMPTY_MAP, true); assertEquals("Invalid setProperty result for EnumProperty", testEnumType.getEnumConstants()[0], sourceNode.getProperty(testEnumProperty)); // set testEnum property to CLOSED via doTest02 function call, check result sourceNode.invokeMethod("doTest02", Collections.EMPTY_MAP, true); assertEquals("Invalid setProperty result for EnumProperty", testEnumType.getEnumConstants()[1], sourceNode.getProperty(testEnumProperty)); // set testEnum property to TEST via doTest03 function call, check result sourceNode.invokeMethod("doTest03", Collections.EMPTY_MAP, true); assertEquals("Invalid setProperty result for EnumProperty", testEnumType.getEnumConstants()[2], sourceNode.getProperty(testEnumProperty)); // set testEnum property to INVALID via doTest03 function call, expect previous value & error try { sourceNode.invokeMethod("doTest04", Collections.EMPTY_MAP, true); assertEquals("Invalid setProperty result for EnumProperty", testEnumType.getEnumConstants()[2], sourceNode.getProperty(testEnumProperty)); fail("Setting EnumProperty to invalid value should result in an Exception!"); } catch (FrameworkException fx) { } // test other property types sourceNode.invokeMethod("doTest05", Collections.EMPTY_MAP, true); assertEquals("Invalid setProperty result for BooleanProperty", true, sourceNode.getProperty(testBooleanProperty)); assertEquals("Invalid setProperty result for IntegerProperty", 123, sourceNode.getProperty(testIntegerProperty)); assertEquals("Invalid setProperty result for StringProperty", "testing..", sourceNode.getProperty(testStringProperty)); assertEquals("Invalid setProperty result for DoubleProperty", 1.2345, sourceNode.getProperty(testDoubleProperty)); assertEquals("Invalid setProperty result for DateProperty", new Date(currentTimeMillis), sourceNode.getProperty(testDateProperty)); tx.success(); } catch (FrameworkException fex) { fex.printStackTrace(); fail("Unexpected exception."); } }