List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception { if (obj == null) { throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001"); }/* w ww.j av a 2 s . co m*/ try { Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null); Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null); String clientVersion = (String) data.get("version"); if (objVersion != null && clientVersion != null) { try { long clientVersionLong = Long.parseLong(clientVersion); if (!objVersion.equals(clientVersionLong)) { throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null); } } catch (NumberFormatException nfe) { // Version from client isn't number - ignore } } } catch (NoSuchMethodException nme) { // No version control } Method[] methods = expectedClass.getMethods(); for (Method m : methods) { Class<?>[] paramTypes = m.getParameterTypes(); Class persistentClass = null; if (paramTypes.length == 1) { if (paramTypes[0].getAnnotation(Entity.class) != null) { persistentClass = paramTypes[0]; } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) { persistentClass = paramTypes[0]; } } ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName()) : null; if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1 && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class) || Enum.class.isAssignableFrom(paramTypes[0]) || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null)) || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType())))) { String fldName; if (m.getName().startsWith(GET_TRANSLATE)) { fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase() + m.getName().substring(GET_TRANSLATE_LENGTH + 1); } else { fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); } Object value = data.get(fldName); if (value == null) { fldName = m.getName().substring(3); value = data.get(fldName); } if (value != null) { Object typedVal; String val = null; if (value instanceof String) { val = (String) value; } log.log(Level.FINER, " value = " + value); if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType()))) { log.log(Level.FINER, "GET"); String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); Type[] actualTypeArguments = null; Class iterClass = expectedClass; while (iterClass != null) { try { Field field = iterClass.getDeclaredField(attrName); ParameterizedType genericType = (ParameterizedType) field.getGenericType(); actualTypeArguments = genericType.getActualTypeArguments(); break; } catch (NoSuchFieldException nsfe) { // do nothing iterate again } iterClass = iterClass.getSuperclass(); iterClass = iterClass.equals(Object.class) ? null : iterClass; } if (actualTypeArguments != null && actualTypeArguments.length == 1 && actualTypeArguments[0] instanceof Class) { Class assocClass = (Class) actualTypeArguments[0]; ServiceDescription assocService = findServiceByClassName(assocClass.getName()); Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null); if (value == null || !(value instanceof HashMap)) { log.log(Level.FINE, "No data for db property {0}", attrName); } else if (assocService != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { boolean wasMatchingGuiVal = false; ArrayList<String> removeKeys = new ArrayList<String>(); for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object guiValue = ((HashMap<String, Object>) object).get("id"); if (guiValue.equals(dbValId)) { removeKeys.add(key); wasMatchingGuiVal = true; mapRequestToObj((HashMap<String, Object>) guiValue, assocClass, dbVal); break; } } else if (object instanceof String) { // Association if (dbValId.equals(object)) { removeKeys.add(key); wasMatchingGuiVal = true; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } // Remove processed elements // Direct remove is firing concurrent modification exception for (String removeKey : removeKeys) { guiValueMap.remove(removeKey); } if (!wasMatchingGuiVal) { // Is not in list comming from GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else if (object instanceof String) { // Association try { Long id = new Long((String) object); Object assocObj = assocService.getFindById().invoke( assocService.getInstance(), ServiceContextStore.get(), id); if (assocObj != null) { dbValueSet.add(assocObj); } else { log.log(Level.WARNING, "Object with ID {0} not availabla via service {1}", new Object[] { id, assocService.getName() }); } } catch (Exception ex) { log.log(Level.WARNING, "No ID parsable from value {0} under key {1}", new Object[] { object, key }); } } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } else if (assocClass != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { Object matchingGuiVal = null; for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { HashMap<String, Object> guiVal = (HashMap<String, Object>) object; if (dbValId.equals(guiVal.get("id"))) { guiValueMap.remove(key); matchingGuiVal = guiVal; break; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } if (matchingGuiVal != null) { // Coming from GUI - update mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass, dbVal); } else { // Not in GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } } else { log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName); } typedVal = null; } else if (paramTypes[0].isAssignableFrom(String.class)) { typedVal = val; } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) { typedVal = Integer.parseInt(val); } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) { typedVal = Long.parseLong(val); } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) { typedVal = Double.parseDouble(val); } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) { typedVal = Float.parseFloat(val); } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) { typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val) || "y".equalsIgnoreCase(val); } else if (paramTypes[0].isAssignableFrom(Date.class)) { typedVal = dateFormat.parse(val); } else if (Enum.class.isAssignableFrom(paramTypes[0])) { try { Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class); typedVal = fromValueMethod.invoke(null, val); } catch (Exception ex) { typedVal = null; } try { if (typedVal == null) { Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class); typedVal = valueOfMethod.invoke(null, val); } } catch (Exception ex) { typedVal = null; } } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) { FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val); if (fileItem != null) { typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(), fileItem.getContentType(), fileItem.getInputStream()); } else { typedVal = null; } } else if (srvParam != null && srvParam.getFindById() != null) { if (value instanceof HashMap) { HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value; typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), new Long((String) embeddedObj.get("id"))); mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal); } else { try { Long parsedId = new Long(val); typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), parsedId); } catch (NumberFormatException nfe) { // wrong value typedVal = null; } } } else if (persistentClass != null) { String getMethodName = "g" + m.getName().substring(1); try { Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null); typedVal = getMethod.invoke(obj, (Object[]) null); } catch (NoSuchMethodException nsme) { typedVal = null; } if (typedVal == null) { typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value); } mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal); } else { log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); typedVal = null; } if (typedVal != null) { m.invoke(obj, typedVal); } } } else if (m.getName().startsWith(SET_PREFIX)) { log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); } } }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
/** * Checks if the given field is a valid pojo field: * - it is public/* w w w. java2s. c o m*/ * OR * - there are getter and setter methods for the field. * * @param f field to check * @param clazz class of field * @param typeHierarchy type hierarchy for materializing generic types */ private boolean isValidPojoField(Field f, Class<?> clazz, ArrayList<Type> typeHierarchy) { if (Modifier.isPublic(f.getModifiers())) { return true; } else { boolean hasGetter = false, hasSetter = false; final String fieldNameLow = f.getName().toLowerCase().replaceAll("_", ""); Type fieldType = f.getGenericType(); Class<?> fieldTypeWrapper = ClassUtils.primitiveToWrapper(f.getType()); TypeVariable<?> fieldTypeGeneric = null; if (fieldType instanceof TypeVariable) { fieldTypeGeneric = (TypeVariable<?>) fieldType; fieldType = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) fieldType); } for (Method m : clazz.getMethods()) { final String methodNameLow = m.getName().endsWith("_$eq") ? m.getName().toLowerCase().replaceAll("_", "").replaceFirst("\\$eq$", "_\\$eq") : m.getName().toLowerCase().replaceAll("_", ""); // check for getter if ( // The name should be "get<FieldName>" or "<fieldName>" (for scala) or "is<fieldName>" for boolean fields. (methodNameLow.equals("get" + fieldNameLow) || methodNameLow.equals("is" + fieldNameLow) || methodNameLow.equals(fieldNameLow)) && // no arguments for the getter m.getParameterTypes().length == 0 && // return type is same as field type (or the generic variant of it) (m.getGenericReturnType().equals(fieldType) || (fieldTypeWrapper != null && m.getReturnType().equals(fieldTypeWrapper)) || (fieldTypeGeneric != null && m.getGenericReturnType().equals(fieldTypeGeneric)))) { if (hasGetter) { throw new IllegalStateException("Detected more than one getter"); } hasGetter = true; } // check for setters (<FieldName>_$eq for scala) if ((methodNameLow.equals("set" + fieldNameLow) || methodNameLow.equals(fieldNameLow + "_$eq")) && m.getParameterTypes().length == 1 && // one parameter of the field's type (m.getGenericParameterTypes()[0].equals(fieldType) || (fieldTypeWrapper != null && m.getParameterTypes()[0].equals(fieldTypeWrapper)) || (fieldTypeGeneric != null && m.getGenericParameterTypes()[0].equals(fieldTypeGeneric))) && // return type is void. m.getReturnType().equals(Void.TYPE)) { if (hasSetter) { throw new IllegalStateException("Detected more than one setter"); } hasSetter = true; } } if (hasGetter && hasSetter) { return true; } else { if (!hasGetter) { LOG.debug(clazz + " does not contain a getter for field " + f.getName()); } if (!hasSetter) { LOG.debug(clazz + " does not contain a setter for field " + f.getName()); } return false; } } }
From source file:org.apache.syncope.console.pages.ReportletConfModalPage.java
private ListView<String> buildPropView() { LoadableDetachableModel<List<String>> propViewModel = new LoadableDetachableModel<List<String>>() { private static final long serialVersionUID = 5275935387613157437L; @Override/*www .ja v a 2 s. c o m*/ protected List<String> load() { List<String> result = new ArrayList<String>(); if (ReportletConfModalPage.this.reportletConf != null) { for (Field field : ReportletConfModalPage.this.reportletConf.getClass().getDeclaredFields()) { if (!ArrayUtils.contains(EXCLUDE_PROPERTIES, field.getName())) { result.add(field.getName()); } } } return result; } }; propView = new ListView<String>("propView", propViewModel) { private static final long serialVersionUID = 9101744072914090143L; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void populateItem(final ListItem<String> item) { final String fieldName = item.getModelObject(); Label label = new Label("key", fieldName); item.add(label); Field field = null; try { field = ReportletConfModalPage.this.reportletConf.getClass().getDeclaredField(fieldName); } catch (Exception e) { LOG.error("Could not find field {} in class {}", fieldName, ReportletConfModalPage.this.reportletConf.getClass(), e); } if (field == null) { return; } FormAttributeField annotation = field.getAnnotation(FormAttributeField.class); BeanWrapper wrapper = PropertyAccessorFactory .forBeanPropertyAccess(ReportletConfModalPage.this.reportletConf); Panel panel; if (String.class.equals(field.getType()) && annotation != null && annotation.userSearch()) { panel = new UserSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName)) .required(false).build(); // This is needed in order to manually update this.reportletConf with search panel selections panel.setDefaultModel(new Model<String>(fieldName)); } else if (String.class.equals(field.getType()) && annotation != null && annotation.roleSearch()) { panel = new RoleSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName)) .required(false).build(); // This is needed in order to manually update this.reportletConf with search panel selections panel.setDefaultModel(new Model<String>(fieldName)); } else if (List.class.equals(field.getType())) { Class<?> listItemType = String.class; if (field.getGenericType() instanceof ParameterizedType) { listItemType = (Class<?>) ((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0]; } if (listItemType.equals(String.class) && annotation != null) { List<String> choices; switch (annotation.schema()) { case UserSchema: choices = schemaRestClient.getSchemaNames(AttributableType.USER); break; case UserDerivedSchema: choices = schemaRestClient.getDerSchemaNames(AttributableType.USER); break; case UserVirtualSchema: choices = schemaRestClient.getVirSchemaNames(AttributableType.USER); break; case RoleSchema: choices = schemaRestClient.getSchemaNames(AttributableType.ROLE); break; case RoleDerivedSchema: choices = schemaRestClient.getDerSchemaNames(AttributableType.ROLE); break; case RoleVirtualSchema: choices = schemaRestClient.getVirSchemaNames(AttributableType.ROLE); break; case MembershipSchema: choices = schemaRestClient.getSchemaNames(AttributableType.MEMBERSHIP); break; case MembershipDerivedSchema: choices = schemaRestClient.getDerSchemaNames(AttributableType.MEMBERSHIP); break; case MembershipVirtualSchema: choices = schemaRestClient.getVirSchemaNames(AttributableType.MEMBERSHIP); break; default: choices = Collections.emptyList(); } panel = new AjaxPalettePanel("value", new PropertyModel<List<String>>(ReportletConfModalPage.this.reportletConf, fieldName), new ListModel<String>(choices), true); } else if (listItemType.isEnum()) { panel = new CheckBoxMultipleChoiceFieldPanel("value", new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName), new ListModel(Arrays.asList(listItemType.getEnumConstants()))); } else { if (((List) wrapper.getPropertyValue(fieldName)).isEmpty()) { ((List) wrapper.getPropertyValue(fieldName)).add(null); } panel = new MultiFieldPanel("value", new PropertyModel<List>(ReportletConfModalPage.this.reportletConf, fieldName), buildSinglePanel(field.getType(), fieldName, "panel")); } } else { panel = buildSinglePanel(field.getType(), fieldName, "value"); } item.add(panel); } }; return propView; }
From source file:org.apache.syncope.client.console.pages.ReportletConfModalPage.java
private ListView<String> buildPropView() { LoadableDetachableModel<List<String>> propViewModel = new LoadableDetachableModel<List<String>>() { private static final long serialVersionUID = 5275935387613157437L; @Override//from w w w. j a v a 2 s . co m protected List<String> load() { List<String> result = new ArrayList<String>(); if (ReportletConfModalPage.this.reportletConf != null) { for (Field field : ReportletConfModalPage.this.reportletConf.getClass().getDeclaredFields()) { if (!ArrayUtils.contains(EXCLUDE_PROPERTIES, field.getName())) { result.add(field.getName()); } } } return result; } }; propView = new ListView<String>("propView", propViewModel) { private static final long serialVersionUID = 9101744072914090143L; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void populateItem(final ListItem<String> item) { final String fieldName = item.getModelObject(); Label label = new Label("key", fieldName); item.add(label); Field field = null; try { field = ReportletConfModalPage.this.reportletConf.getClass().getDeclaredField(fieldName); } catch (Exception e) { LOG.error("Could not find field {} in class {}", fieldName, ReportletConfModalPage.this.reportletConf.getClass(), e); } if (field == null) { return; } FormAttributeField annotation = field.getAnnotation(FormAttributeField.class); BeanWrapper wrapper = PropertyAccessorFactory .forBeanPropertyAccess(ReportletConfModalPage.this.reportletConf); Panel panel; if (String.class.equals(field.getType()) && annotation != null && annotation.userSearch()) { panel = new UserSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName)) .required(false).build(); // This is needed in order to manually update this.reportletConf with search panel selections panel.setDefaultModel(new Model<String>(fieldName)); } else if (String.class.equals(field.getType()) && annotation != null && annotation.groupSearch()) { panel = new GroupSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName)) .required(false).build(); // This is needed in order to manually update this.reportletConf with search panel selections panel.setDefaultModel(new Model<String>(fieldName)); } else if (List.class.equals(field.getType())) { Class<?> listItemType = String.class; if (field.getGenericType() instanceof ParameterizedType) { listItemType = (Class<?>) ((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0]; } if (listItemType.equals(String.class) && annotation != null) { List<String> choices; switch (annotation.schema()) { case UserPlainSchema: choices = schemaRestClient.getPlainSchemaNames(AttributableType.USER); break; case UserDerivedSchema: choices = schemaRestClient.getDerSchemaNames(AttributableType.USER); break; case UserVirtualSchema: choices = schemaRestClient.getVirSchemaNames(AttributableType.USER); break; case GroupPlainSchema: choices = schemaRestClient.getPlainSchemaNames(AttributableType.GROUP); break; case GroupDerivedSchema: choices = schemaRestClient.getDerSchemaNames(AttributableType.GROUP); break; case GroupVirtualSchema: choices = schemaRestClient.getVirSchemaNames(AttributableType.GROUP); break; case MembershipPlainSchema: choices = schemaRestClient.getPlainSchemaNames(AttributableType.MEMBERSHIP); break; case MembershipDerivedSchema: choices = schemaRestClient.getDerSchemaNames(AttributableType.MEMBERSHIP); break; case MembershipVirtualSchema: choices = schemaRestClient.getVirSchemaNames(AttributableType.MEMBERSHIP); break; default: choices = Collections.emptyList(); } panel = new AjaxPalettePanel("value", new PropertyModel<List<String>>(ReportletConfModalPage.this.reportletConf, fieldName), new ListModel<String>(choices), true); } else if (listItemType.isEnum()) { panel = new CheckBoxMultipleChoiceFieldPanel("value", new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName), new ListModel(Arrays.asList(listItemType.getEnumConstants()))); } else { if (((List) wrapper.getPropertyValue(fieldName)).isEmpty()) { ((List) wrapper.getPropertyValue(fieldName)).add(null); } panel = new MultiFieldPanel("value", new PropertyModel<List>(ReportletConfModalPage.this.reportletConf, fieldName), buildSinglePanel(field.getType(), fieldName, "panel")); } } else { panel = buildSinglePanel(field.getType(), fieldName, "value"); } item.add(panel); } }; return propView; }
From source file:au.com.addstar.cellblock.configuration.AutoConfig.java
public boolean save() { try {/*from ww w .ja va 2 s.co m*/ onPreSave(); YamlConfiguration config = new YamlConfiguration(); Map<String, String> comments = new HashMap<>(); // Add all the category comments comments.putAll(mCategoryComments); // Add all the values for (Field field : getClass().getDeclaredFields()) { ConfigField configField = field.getAnnotation(ConfigField.class); if (configField == null) continue; String optionName = configField.name(); if (optionName.isEmpty()) optionName = field.getName(); field.setAccessible(true); String path = (configField.category().isEmpty() ? "" : configField.category() + ".") + optionName; //$NON-NLS-2$ // Ensure the secion exists if (!configField.category().isEmpty() && !config.contains(configField.category())) config.createSection(configField.category()); if (field.getType().isArray()) { // Integer if (field.getType().getComponentType().equals(Integer.TYPE)) config.set(path, Arrays.asList((Integer[]) field.get(this))); // Float else if (field.getType().getComponentType().equals(Float.TYPE)) config.set(path, Arrays.asList((Float[]) field.get(this))); // Double else if (field.getType().getComponentType().equals(Double.TYPE)) config.set(path, Arrays.asList((Double[]) field.get(this))); // Long else if (field.getType().getComponentType().equals(Long.TYPE)) config.set(path, Arrays.asList((Long[]) field.get(this))); // Short else if (field.getType().getComponentType().equals(Short.TYPE)) config.set(path, Arrays.asList((Short[]) field.get(this))); // Boolean else if (field.getType().getComponentType().equals(Boolean.TYPE)) config.set(path, Arrays.asList((Boolean[]) field.get(this))); // String else if (field.getType().getComponentType().equals(String.class)) config.set(path, Arrays.asList((String[]) field.get(this))); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-2$ } else if (List.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type List without specifying generic type for AutoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (type.equals(Integer.class) || type.equals(Float.class) || type.equals(Double.class) || type.equals(Long.class) || type.equals(Short.class) || type.equals(Boolean.class) || type.equals(String.class)) { config.set(path, field.get(this)); } else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + "<" + type.toString() + "> for AutoConfiguration"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (Set.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type Set without specifying generic type for AutoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (type.equals(Integer.class) || type.equals(Float.class) || type.equals(Double.class) || type.equals(Long.class) || type.equals(Short.class) || type.equals(Boolean.class) || type.equals(String.class)) { config.set(path, new ArrayList<Object>((Set<?>) field.get(this))); } else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + "<" + type.toString() + "> for AutoConfiguration"); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Integer if (field.getType().equals(Integer.TYPE)) config.set(path, field.get(this)); // Float else if (field.getType().equals(Float.TYPE)) config.set(path, field.get(this)); // Double else if (field.getType().equals(Double.TYPE)) config.set(path, field.get(this)); // Long else if (field.getType().equals(Long.TYPE)) config.set(path, field.get(this)); // Short else if (field.getType().equals(Short.TYPE)) config.set(path, field.get(this)); // Boolean else if (field.getType().equals(Boolean.TYPE)) config.set(path, field.get(this)); // ItemStack else if (field.getType().equals(ItemStack.class)) config.set(path, field.get(this)); // String else if (field.getType().equals(String.class)) config.set(path, field.get(this)); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-2$ } // Record the comment if (!configField.comment().isEmpty()) comments.put(path, configField.comment()); } String output = config.saveToString(); // Apply comments String category = ""; List<String> lines = new ArrayList<>(Arrays.asList(output.split("\n"))); for (int l = 0; l < lines.size(); l++) { String line = lines.get(l); if (line.startsWith("#")) continue; if (line.trim().startsWith("-")) continue; if (!line.contains(":")) continue; String path; line = line.substring(0, line.indexOf(":")); if (line.startsWith(" ")) path = category + "." + line.substring(2).trim(); else { category = line.trim(); path = line.trim(); } if (comments.containsKey(path)) { String indent = ""; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == ' ') indent += " "; else break; } // Add in the comment lines String[] commentLines = comments.get(path).split("\n"); lines.add(l++, ""); for (int i = 0; i < commentLines.length; i++) { commentLines[i] = indent + "# " + commentLines[i]; lines.add(l++, commentLines[i]); } } } output = ""; for (String line : lines) output += line + "\n"; FileWriter writer = new FileWriter(mFile); writer.write(output); writer.close(); return true; } catch (IllegalArgumentException | IOException | IllegalAccessException e) { e.printStackTrace(); } return false; }
From source file:fr.certu.chouette.command.Command.java
/** * @param objectType/* w w w. ja v a 2 s . c o m*/ * @param field * @param indent * @throws Exception */ private void printField(Class<?> objectType, Field field, String indent) throws Exception { String fieldName = field.getName().toLowerCase(); if (fieldName.equals("importeditems")) return; if (fieldName.endsWith("id") || fieldName.endsWith("ids")) { if (!fieldName.equals("objectid") && !fieldName.equals("creatorid") && !fieldName.equals("areacentroid")) return; } if (findAccessor(objectType, field.getName(), "get", false) == null && findAccessor(objectType, field.getName(), "is", false) == null) { return; } Class<?> type = field.getType(); if (type.isPrimitive()) { System.out.print(indent + "- " + field.getName()); System.out.print(" : type " + type.getName()); if (findAccessor(objectType, field.getName(), "set", false) == null) { System.out.print(" (readonly)"); } } else { if (type.getSimpleName().equals("List")) { String name = field.getName(); name = name.substring(0, name.length() - 1); ParameterizedType ptype = (ParameterizedType) field.getGenericType(); Class<?> itemType = (Class<?>) ptype.getActualTypeArguments()[0]; System.out.print(indent + "- " + name); System.out.print(" : collection of type " + itemType.getSimpleName()); if (findAccessor(objectType, name, "add", false) != null) { System.out.print(" (add allowed)"); } if (findAccessor(objectType, name, "remove", false) != null) { System.out.print(" (remove allowed)"); } type = itemType; } else { System.out.print(indent + "- " + field.getName()); System.out.print(" : type " + type.getSimpleName()); if (findAccessor(objectType, field.getName(), "set", false) == null) { System.out.print(" (readonly)"); } } } System.out.println(""); if (!type.isPrimitive()) printFieldDetails(type, indent); }
From source file:com.fluidops.iwb.api.ReadDataManagerImpl.java
/** * RDF string to Java Object/*from w ww . j av a2 s .c o m*/ */ @SuppressWarnings({ "unchecked" }) @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception caught for robustness.") private <T> T convert(Value s, Class<T> t, Map<Value, Object> resourceStack) { if (s == null) return null; // avoid endless recursion if (resourceStack != null) { Object alreadySeen = resourceStack.get(s); if (alreadySeen != null) { if (alreadySeen.getClass().isAssignableFrom(t)) return (T) alreadySeen; else // TODO: theoretically, a subject could be accessed as Type // T1 and later // as Type T2. So really, the stack should be Map<String, // Map<Class, Object>> // but this seems like a bit of overkill, so we just return // null if the type // seen for this resource before in the stack does not match return null; } } try { if (t == short.class || t == Short.class) return (T) new Short(s.stringValue()); if (t == byte.class || t == Byte.class) return (T) new Byte(s.stringValue()); if (t == boolean.class || t == Boolean.class) return (T) Boolean.valueOf(s.stringValue()); if (t == long.class || t == Long.class) return (T) new Long(s.stringValue()); if (t == float.class || t == Float.class) return (T) new Float(s.stringValue()); if (t == double.class || t == Double.class) return (T) new Double(s.stringValue()); if (t == int.class || t == Integer.class) return (T) new Integer(s.stringValue()); if (t == String.class) return (T) s.stringValue(); if (t == Date.class) return (T) literal2HumanDate(s.stringValue()); if (t == Calendar.class) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(literal2HumanDate(s.stringValue())); return (T) cal; } if (t == URL.class) return (T) new URL(s.stringValue()); if (t == java.net.URI.class) return (T) new java.net.URI(s.stringValue()); if (t == org.openrdf.model.URI.class) return (T) s; /* * todo // interface - use dynamic proxy if ( t.isInterface() || * Proxy.class.isAssignableFrom( t ) ) return (T)Proxy.newInstance( * s, this, t ); */ T instance = t.newInstance(); // create object only if it is necessary if (resourceStack == null) resourceStack = new HashMap<Value, Object>(); resourceStack.put(s, instance); for (Field f : t.getFields()) { if (Modifier.isStatic(f.getModifiers())) continue; if (Modifier.isFinal(f.getModifiers())) continue; if (List.class.isAssignableFrom(f.getType())) { @SuppressWarnings("rawtypes") Class listTypeValue = String.class; if (f.getGenericType() instanceof ParameterizedType) listTypeValue = (Class<?>) ((ParameterizedType) f.getGenericType()) .getActualTypeArguments()[0]; if (f.getAnnotation(RDFMapping.class) == null ? false : f.getAnnotation(RDFMapping.class).inverse()) { List<String> x = getInverseProps(s, RDFMappingUtil.uri(f), listTypeValue, false); f.set(instance, x); } else { List<T> x = new ArrayList<T>(); for (Value v : getProps((Resource) s, RDFMappingUtil.uri(f))) x.add((T) convert(v, listTypeValue, resourceStack)); f.set(instance, x); } } else { if (f.getName().equals("__resource")) f.set(instance, s); else if (f.getAnnotation(RDFMapping.class) == null ? false : f.getAnnotation(RDFMapping.class).inverse()) { Object x = getInversePropInternal(s, RDFMappingUtil.uri(f), f.getType(), resourceStack); f.set(instance, x); } else if (s instanceof Resource) { // for Resources, traverse deeper, for Literals, there // is no substructure Object x = getPropInternal(getProp((Resource) s, RDFMappingUtil.uri(f)), f.getType(), resourceStack); f.set(instance, x); } } } return instance; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.j2free.admin.ReflectionMarshaller.java
private ReflectionMarshaller(Class klass) throws Exception { instructions = new HashMap<Field, Converter>(); LinkedList<Field> fieldsToMarshall = new LinkedList<Field>(); // Only marshallOut entities if (!klass.isAnnotationPresent(Entity.class)) throw new Exception("Provided class is not an @Entity"); // Add the declared fields fieldsToMarshall.addAll(Arrays.asList(klass.getDeclaredFields())); /* Inheritence support * Continue up the inheritance ladder until: * - There are no more super classes (zuper == null), or * - The super class is not an @Entity *///from ww w .java2s . c om Class zuper = klass; while ((zuper = zuper.getSuperclass()) != null) { // get out if we find a super class that isn't an @Entity if (!klass.isAnnotationPresent(Entity.class)) break; // Add the declared fields // @todo, improve the inheritance support, the current way will overwrite // overridden fields in subclasses with the super class's field fieldsToMarshall.addAll(Arrays.asList(zuper.getDeclaredFields())); } /* By now, fieldsToMarshall should contain all the fields * so it's time to figure out how to access them. */ Method getter, setter; Converter converter; for (Field field : fieldsToMarshall) { int mod = field.getModifiers(); if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { log.debug("Skipping final or static field " + field.getName()); continue; } getter = setter = null; // if direct access doesn't work, look for JavaBean // getters and setters String fieldName = field.getName(); Class fieldType = field.getType(); try { getter = getGetter(field); } catch (NoSuchMethodException nsme) { log.debug("Failed to find getter for " + fieldName); } try { setter = getSetter(field); } catch (NoSuchMethodException nsme) { log.debug("Failed to find setter for " + fieldName); } if (getter == null && setter == null) { // Shit, we didn't figure out how to access it log.debug("Could not access field: " + field.getName()); } else { converter = new Converter(getter, setter); if (field.isAnnotationPresent(Id.class)) { log.debug("Found entityIdFied for " + klass.getName() + ": " + field.getName()); entityIdField = field; embeddedId = false; } if (field.isAnnotationPresent(EmbeddedId.class)) { log.debug("Found embedded entityIdFied for " + klass.getName() + ": " + field.getName()); entityIdField = field; embeddedId = true; } if (field.isAnnotationPresent(GeneratedValue.class) || setter == null) { converter.setReadOnly(true); } if (field.getType().isAnnotationPresent(Entity.class)) { converter.setEntity(fieldType); } Class superClass = field.getType(); if (superClass != null) { do { if (superClass == Collection.class) { try { Type type = field.getGenericType(); String typeString = type.toString(); while (typeString.matches("[^<]+?<[^>]+?>")) typeString = typeString.substring(typeString.indexOf("<") + 1, typeString.indexOf(">")); Class collectionType = Class.forName(typeString); converter.setCollection(collectionType); if (collectionType.getAnnotation(Entity.class) != null) converter.setEntity(collectionType); log.debug(field.getName() + " is entity = " + converter.isEntity()); log.debug(field.getName() + " collectionType = " + converter.getType().getSimpleName()); } catch (Exception e) { log.debug("error getting collection type", e); } finally { break; } } superClass = superClass.getSuperclass(); } while (superClass != null); } instructions.put(field, converter); } } }
From source file:org.debux.webmotion.jpa.GenericDAO.java
/** * Complete entity with parameters. Try to convert parameter, if the type not * match. To create an association on entity, you must pass only identifier. * /*w w w . j a v a 2 s. c om*/ * @param entity entity * @param parameters parameters * @return entity completed */ protected IdentifiableEntity extract(IdentifiableEntity entity, Parameters parameters) { try { Field[] fields = entityClass.getDeclaredFields(); for (Field field : fields) { String name = field.getName(); Class<?> type = field.getType(); Object[] values = parameters.get(name); // The identifier can't be set if (!IdentifiableEntity.ATTRIBUTE_NAME_ID.equals(name) && values != null) { if (values.length == 0) { // Null value beanUtil.setProperty(entity, name, null); } else if (type.isAnnotationPresent(javax.persistence.Entity.class)) { // Association List<Object> references = new ArrayList<Object>(values.length); for (Object value : values) { Object reference = manager.find(type, value); if (reference != null) { references.add(reference); } } Object converted = null; if (List.class.isAssignableFrom(type)) { converted = references; } else if (Set.class.isAssignableFrom(type)) { converted = new HashSet<Object>(references); } else if (SortedSet.class.isAssignableFrom(type)) { converted = new TreeSet<Object>(references); } else if (type.isArray()) { converted = references.toArray(); } else if (Map.class.isAssignableFrom(type)) { String keyName = IdentifiableEntity.ATTRIBUTE_NAME_ID; MapKey annotation = type.getAnnotation(MapKey.class); if (annotation != null) { String annotationName = annotation.name(); if (annotationName != null && !annotationName.isEmpty()) { keyName = annotationName; } } Map<Object, Object> map = new HashMap<Object, Object>(); for (Object object : references) { Object key = propertyUtils.getProperty(object, keyName); map.put(key, object); } converted = map; } else if (!references.isEmpty()) { converted = references.get(0); } beanUtil.setProperty(entity, name, converted); } else { // Basic object if (Collection.class.isAssignableFrom(type)) { Class convertType = String.class; Type genericType = field.getGenericType(); if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertType = (Class) parameterizedType.getActualTypeArguments()[0]; } Collection<Object> collection = null; if (Set.class.isAssignableFrom(type)) { collection = new HashSet<Object>(); } else if (SortedSet.class.isAssignableFrom(type)) { collection = new TreeSet(); } else { collection = new ArrayList<Object>(); } for (Object object : values) { Object convertedObject = convertUtils.convert(object, convertType); collection.add(convertedObject); } beanUtil.setProperty(entity, name, collection); } else if (Map.class.isAssignableFrom(type)) { throw new UnsupportedOperationException( "Map is not supported, you must create a specific entity."); } else { Object converted = convertUtils.convert(values, type); beanUtil.setProperty(entity, name, converted); } } } } return entity; } catch (IllegalAccessException iae) { throw new WebMotionException("Error during create instance", iae); } catch (InvocationTargetException ite) { throw new WebMotionException("Error during set field on instance", ite); } catch (NoSuchMethodException nsme) { throw new WebMotionException("Error during set field on instance", nsme); } }