List of usage examples for java.beans Introspector decapitalize
public static String decapitalize(String name)
From source file:com.freetmp.common.util.ClassUtils.java
public static String getShortNameAsProperty(Class<?> clazz) { String shortName = ClassUtils.getShortName(clazz); int dotIndex = shortName.lastIndexOf(PACKAGE_SEPARATOR); shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName); return Introspector.decapitalize(shortName); }
From source file:org.crazydog.util.spring.ClassUtils.java
/** * Return the short string name of a Java class in uncapitalized JavaBeans * property format. Strips the outer class name in case of an inner class. * @param clazz the class/*from w w w.java2 s. com*/ * @return the short name rendered in a standard JavaBeans property format * @see Introspector#decapitalize(String) */ public static String getShortNameAsProperty(Class<?> clazz) { String shortName = ClassUtils.getShortName(clazz); int dotIndex = shortName.lastIndexOf(PACKAGE_SEPARATOR); shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName); return Introspector.decapitalize(shortName); }
From source file:org.toobsframework.data.beanutil.BeanMonkey.java
private static Object evaluatePropertyValue(String name, String className, String namespace, Object value, Map properties, Object bean) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, PermissionException { // Perform the assignment for this property if (className.startsWith(configuration.getProperty("toobs.beanmonkey.dataPackage"))) { className = className.substring(className.lastIndexOf(".") + 1); IObjectLoader odao = null;//from ww w . j a va 2s. c om ICollectionLoader cdao = null; Object daoObject = beanFactory.getBean(Introspector.decapitalize(className) + "Dao"); if (daoObject == null) { throw new InvocationTargetException(new Exception( "DAO class " + Introspector.decapitalize(className) + "Dao could not be loaded")); } if (daoObject instanceof IObjectLoader) { odao = (IObjectLoader) daoObject; } else { cdao = (ICollectionLoader) daoObject; } String guid = null; if (value != null && value.getClass().isArray()) { if (properties.containsKey(PlatformConstants.MULTI_ACTION_INSTANCE)) { Object[] oldValue = (Object[]) value; Integer instance = (Integer) properties.get(PlatformConstants.MULTI_ACTION_INSTANCE); if (oldValue.length >= instance + 1) { guid = ((String[]) oldValue)[instance]; } else { throw new RuntimeException("Instance " + instance + " not found in " + oldValue + " for: " + name + " class: " + className + " in: " + bean); } } else { guid = ((String[]) value)[0]; } } else { guid = (String) value; } if (guid != null && guid.length() > 0) { String personId = (String) properties.get("personId"); try { if (odao != null) { value = odao.load(guid); } else { value = cdao.load(Integer.parseInt(guid)); } } catch (PermissionException pe) { log.error("PermissionException loading object " + className + "." + name + " with guid " + guid + " by person " + personId); throw pe; } finally { } } else { value = null; } } else if ((className.equals("java.util.ArrayList") || className.equals("java.util.List")) && !(value instanceof java.util.List)) { Object[] values = null; if (value != null && value.getClass().isArray()) { values = ((Object[]) value); } else { values = new Object[1]; values[0] = (Object) value; } value = new ArrayList(); for (int aa = 0; aa < values.length; aa++) { if (!"".equals(values[aa])) ((ArrayList) value).add(values[aa]); } if (((ArrayList) value).size() == 0) value = null; } else if (className.equals("java.util.Collection")) { className = null; String typeProp = (namespace != null ? namespace : "") + name + "-Type"; if (properties.get(typeProp) != null && properties.get(typeProp).getClass().isArray()) { className = ((String[]) properties.get(typeProp))[0]; } else { className = (String) properties.get(typeProp); } if (className == null) { throw new InvocationTargetException(new Exception("Missing collection type for " + name)); } IObjectLoader odao = null; ICollectionLoader cdao = null; Object daoObject = beanFactory.getBean(Introspector.decapitalize(className) + "Dao"); if (daoObject == null) { throw new InvocationTargetException(new Exception( "DAO class " + Introspector.decapitalize(className) + "Dao could not be loaded")); } if (daoObject instanceof IObjectLoader) { odao = (IObjectLoader) daoObject; } else { cdao = (ICollectionLoader) daoObject; } Object[] guids = null; if (value != null && value.getClass().isArray()) { guids = ((Object[]) value); } else if (value != null && value instanceof ArrayList) { guids = new Object[((ArrayList) value).size()]; for (int i = 0; i < guids.length; i++) { guids[i] = (Object) ((ArrayList) value).get(i); } } else { guids = new Object[1]; guids[0] = (Object) value; } String personId = (String) properties.get("personId"); java.util.Collection valueList = (java.util.Collection) PropertyUtils.getProperty(bean, name); valueList.clear(); for (int i = 0; i < guids.length; i++) { if (odao != null) { if (((String) guids[i]).length() == 0) continue; value = odao.load((String) guids[i]); } else if (cdao != null) { value = cdao.load((Integer) guids[i]); } if (value != null) { valueList.add(value); } else { if (beanFactory.containsBean(className + "CollectionCreator")) { ICollectionCreator collectionCreator = (ICollectionCreator) beanFactory .getBean(className + "CollectionCreator"); try { collectionCreator.addCollectionElements(guids[i], valueList, properties, personId, namespace); } catch (Exception e) { throw new InvocationTargetException(e); } } } } value = valueList; } else if (className.equals("java.lang.String") && value != null && value.getClass().isArray() && ((Object[]) value).length > 1 && properties.containsKey(PlatformConstants.MULTI_ACTION_INSTANCE)) { Object[] oldValue = (Object[]) value; Integer instance = (Integer) properties.get(PlatformConstants.MULTI_ACTION_INSTANCE); if (oldValue.length >= instance + 1) { value = oldValue[instance]; } else { throw new RuntimeException("Instance " + instance + " not found in " + oldValue + " for: " + name + " class: " + className + " in: " + bean); } } else if (className.equals("java.lang.String") && value != null && value.getClass().isArray() && ((Object[]) value).length > 1) { Object[] oldValue = (Object[]) value; String newValue = new String(); for (int i = 0; i < oldValue.length; i++) { if (i > 0) { newValue = newValue + ";"; } newValue = newValue + oldValue[i]; } value = newValue; } else if ((className.equals("java.lang.Integer") || className.equals("java.lang.Boolean")) && value != null) { if (value.getClass().isArray() && ((Object[]) value).length == 1 && ((Object[]) value)[0].equals("")) { value = null; } else if (!value.getClass().isArray() && String.valueOf(value).equals("")) { value = null; } } else if (className.equals("java.util.Date") && value != null) { if (value.getClass().isArray()) { value = StringToDateConverter.convert(value); } } return value; }
From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java
/** * Establish relationship with related domain class * * @param entity/*from w w w. java 2 s . c o m*/ * @param property Establishes a relationship between this class and the domain class property * @param context * @param hasOneMap */ private ToOne establishDomainClassRelationship(PersistentEntity entity, PropertyDescriptor property, MappingContext context, Map hasOneMap) { ToOne association = null; Class propType = property.getPropertyType(); ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(propType); // establish relationship to type Map relatedClassRelationships = getAllAssociationMap(cpf); Map mappedBy = cpf.getStaticPropertyValue(MAPPED_BY, Map.class); if (mappedBy == null) mappedBy = Collections.emptyMap(); Class<?> relatedClassPropertyType = null; // if there is a relationships map use that to find out // whether it is mapped to a Set String relatedClassPropertyName = null; if (!forceUnidirectional(property, mappedBy)) { if (relatedClassRelationships != null && !relatedClassRelationships.isEmpty()) { PropertyDescriptor[] descriptors = ReflectionUtils.getPropertiesOfType(entity.getJavaClass(), propType); relatedClassPropertyName = findOneToManyThatMatchesType(entity, relatedClassRelationships); // if there is only one property on many-to-one side of the relationship then // try to establish if it is bidirectional if (descriptors.length == 1 && isNotMappedToDifferentProperty(property, relatedClassPropertyName, mappedBy)) { if (StringUtils.hasText(relatedClassPropertyName)) { // get the type of the property relatedClassPropertyType = cpf.getPropertyType(relatedClassPropertyName); } } // if there is more than one property on the many-to-one side then we need to either // find out if there is a mappedBy property or whether a convention is used to decide // on the mapping property else if (descriptors.length > 1) { if (mappedBy.containsValue(property.getName())) { for (Object o : mappedBy.keySet()) { String mappedByPropertyName = (String) o; if (property.getName().equals(mappedBy.get(mappedByPropertyName))) { Class<?> mappedByRelatedType = (Class<?>) relatedClassRelationships .get(mappedByPropertyName); if (mappedByRelatedType != null && propType.isAssignableFrom(mappedByRelatedType)) relatedClassPropertyType = cpf.getPropertyType(mappedByPropertyName); } } } else { String classNameAsProperty = Introspector.decapitalize(propType.getName()); if (property.getName().equals(classNameAsProperty) && !mappedBy.containsKey(relatedClassPropertyName)) { relatedClassPropertyType = cpf.getPropertyType(relatedClassPropertyName); } } } } // otherwise retrieve all the properties of the type from the associated class if (relatedClassPropertyType == null) { PropertyDescriptor[] descriptors = ReflectionUtils.getPropertiesOfType(propType, entity.getJavaClass()); // if there is only one then the association is established if (descriptors.length == 1) { relatedClassPropertyType = descriptors[0].getPropertyType(); relatedClassPropertyName = descriptors[0].getName(); } } } // establish relationship based on this type // uni-directional one-to-one final boolean isAssociationEntity = isPersistentEntity(relatedClassPropertyType); if (relatedClassPropertyType == null || isAssociationEntity) { association = propertyFactory.createOneToOne(entity, context, property); if (hasOneMap.containsKey(property.getName())) { association.setForeignKeyInChild(true); } } // bi-directional many-to-one else if (Collection.class.isAssignableFrom(relatedClassPropertyType) || Map.class.isAssignableFrom(relatedClassPropertyType)) { association = propertyFactory.createManyToOne(entity, context, property); } // bi-directional if (association != null) { PersistentEntity associatedEntity = getOrCreateAssociatedEntity(entity, context, propType); association.setAssociatedEntity(associatedEntity); boolean isNotCircular = entity != associatedEntity; if (relatedClassPropertyName != null && isNotCircular) { association.setReferencedPropertyName(relatedClassPropertyName); } } return association; }
From source file:com.flipkart.poseidon.serviceclients.generator.ServiceGenerator.java
private void addImplMethods(ServiceIDL serviceIdl, JCodeModel jCodeModel, JDefinedClass jDefinedClass) { String commandName = serviceIdl.getService().getCommandName(); if (commandName == null || commandName.isEmpty()) { commandName = Introspector.decapitalize(serviceIdl.getService().getName() + "HttpRequest"); }// w w w. ja v a 2s .com addSimpleMethod(jCodeModel, jDefinedClass, "getCommandName", commandName); if (serviceIdl.getService().getObjectMapperClass() != null) { JType methodReturnType = jCodeModel.ref(ObjectMapper.class); JMethod method = jDefinedClass.method(JMod.PROTECTED, methodReturnType, "getObjectMapper"); method.annotate(jCodeModel.ref("Override")); method.javadoc().addReturn().append(methodReturnType); method.body()._return(JExpr.ref("customObjectMapper").invoke("getObjectMapper")); } }
From source file:dinistiq.Dinistiq.java
/** * Injects all available dependencies into a given bean and records all dependencies. * * @param key key / name/ id of the bean * @param bean bean instance/*from www .j a v a 2s .c o m*/ * @param dependencies dependencies map where the dependecies of the bean are recorded with the given key * @throws Exception */ private void injectDependencies(Map<String, Set<Object>> dependencies, String key, Object bean) throws Exception { // Prepare values from properties files Properties beanProperties = getProperties(key); LOG.debug("injectDependencies({}) bean properties {}", key, beanProperties.keySet()); // fill injected fields Class<? extends Object> beanClass = bean.getClass(); String beanClassName = beanClass.getName(); while (beanClass != Object.class) { if (bean instanceof Map) { fillMap(bean, getProperties(key)); LOG.info("injectDependencies() filled map '{}' {}", key, bean); return; // If it's a map we don't need to inject anything beyond some map properties files. } // if for (Field field : beanClass.getDeclaredFields()) { LOG.debug("injectDependencies({}) field {}", key, field.getName()); if (field.getAnnotation(Inject.class) != null) { Named named = field.getAnnotation(Named.class); String name = (named == null) ? null : (StringUtils.isBlank(named.value()) ? field.getName() : named.value()); LOG.info("injectDependencies({}) {} :{} needs injection with name {}", key, field.getName(), field.getGenericType(), name); Object b = getValue(beanProperties, dependencies, key, field.getType(), field.getGenericType(), name); final boolean accessible = field.isAccessible(); try { field.setAccessible(true); field.set(bean, b); } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { LOG.error("injectDependencies() error setting field " + field.getName() + " :" + field.getType().getName() + " at '" + key + "' :" + beanClassName, e); } finally { field.setAccessible(accessible); } // try/catch } // if } // for beanClass = beanClass.getSuperclass(); } // while // call methods with annotated injections for (Method m : bean.getClass().getMethods()) { if (m.getAnnotation(Inject.class) != null) { LOG.debug("injectDependencies({}) inject parameters on method {}", key, m.getName()); Class<? extends Object>[] parameterTypes = m.getParameterTypes(); Type[] genericParameterTypes = m.getGenericParameterTypes(); Annotation[][] parameterAnnotations = m.getParameterAnnotations(); Object[] parameters = getParameters(beanProperties, dependencies, key, parameterTypes, genericParameterTypes, parameterAnnotations); try { m.invoke(bean, parameters); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { LOG.error("injectDependencies() error injecting for method " + m.getName() + " at '" + key + "' :" + beanClassName, ex); } // try/catch } // if } // for // Fill in manually set values from properties file for (String property : beanProperties.stringPropertyNames()) { String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); LOG.debug("injectDependencies({}) {} -> {}", key, property, methodName); Method m = null; // Have to find it just by name for (Method me : bean.getClass().getMethods()) { if (me.getName().equals(methodName) && (me.getParameterTypes().length > 0)) { m = me; } // if } // for if (m == null) { LOG.warn("injectDependencies({}) no setter method found for property {}", key, property); } else { String propertyName = Introspector.decapitalize(m.getName().substring(3)); Class<?> parameterType = m.getParameterTypes()[0]; Type genericType = m.getGenericParameterTypes()[0]; LOG.debug("injectDependencies({}) writable property found {} :{} {}", key, propertyName, parameterType, genericType); String propertyValue = beanProperties.getProperty(propertyName); // Must definetely be there without additional check boolean isBoolean = (parameterType == Boolean.class) || (m.getParameterTypes()[0] == Boolean.TYPE); boolean isCollection = Collection.class.isAssignableFrom(parameterType); Object[] parameters = new Object[1]; LOG.debug("injectDependencies({}) trying to set value {} (bool {}) (collection {}) '{}'", key, propertyName, isBoolean, isCollection, propertyValue); try { parameters[0] = getReferenceValue(propertyValue); if (isBoolean && (parameters[0] instanceof String)) { parameters[0] = Boolean.valueOf(propertyValue); } // if if ("long".equals(parameterType.getName())) { parameters[0] = new Long(propertyValue); } // if if ("int".equals(parameterType.getName())) { parameters[0] = new Integer(propertyValue); } // if if ("float".equals(parameterType.getName())) { parameters[0] = new Float(propertyValue); } // if if ("double".equals(parameterType.getName())) { parameters[0] = new Double(propertyValue); } // if if (isCollection) { if (!Collection.class.isAssignableFrom(parameters[0].getClass())) { Collection<Object> values = List.class.isAssignableFrom(parameterType) ? new ArrayList<>() : new HashSet<>(); for (String value : propertyValue.split(",")) { values.add(getReferenceValue(value)); } // for parameters[0] = values; } // if if (dependencies != null) { for (Object d : (Collection<?>) parameters[0]) { if (beans.containsValue(d)) { dependencies.get(key).add(d); } // if } // if } // if } else { if ((dependencies != null) && (beans.containsValue(parameters[0]))) { dependencies.get(key).add(parameters[0]); } // if } // if LOG.debug("injectDependencies({}) setting value {} '{}' :{}", key, propertyName, parameters[0], parameters[0].getClass()); m.invoke(bean, parameters); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { LOG.error("injectDependencies() error setting property " + propertyName + " to '" + propertyValue + "' at " + key + " :" + beanClassName, ex); } // try/catch } // if } // for }
From source file:com.github.sevntu.checkstyle.checks.coding.CustomDeclarationOrderCheck.java
/** * Get name without prefix./*from www .j av a2 s . c o m*/ * @param aName name * @param aPrefix prefix * @return name without prefix or null if name does not have such prefix. */ private static String getNameWithoutPrefix(String aName, String aPrefix) { String result = null; if (aName.startsWith(aPrefix)) { result = aName.substring(aPrefix.length()); result = Introspector.decapitalize(result); } return result; }
From source file:org.gvnix.service.roo.addon.addon.util.WsdlParserUtils.java
/** * Map an XML name to a Java identifier per the mapping rules of JSR 101 (in * version 1.0 this is "Chapter 20: Appendix: Mapping of XML Names" * //from ww w . ja v a 2 s . c o m * @param name is the xml name * @return the java name per JSR 101 specification */ public static String xmlNameToJava(String name) { // protect ourselves from garbage if (name == null || name.equals("")) return name; char[] nameArray = name.toCharArray(); int nameLen = name.length(); StringBuffer result = new StringBuffer(nameLen); boolean wordStart = false; // The mapping indicates to convert first character. int i = 0; while (i < nameLen && (isPunctuation(nameArray[i]) || !Character.isJavaIdentifierStart(nameArray[i]))) { i++; } if (i < nameLen) { // Decapitalization code used to be here, but we use the // Introspector function now after we filter out all bad chars. result.append(nameArray[i]); // wordStart = !Character.isLetter(nameArray[i]); wordStart = !Character.isLetter(nameArray[i]) && nameArray[i] != "_".charAt(0); } else { // The identifier cannot be mapped strictly according to // JSR 101 if (Character.isJavaIdentifierPart(nameArray[0])) { result.append("_" + nameArray[0]); } else { // The XML identifier does not contain any characters // we can map to Java. Using the length of the string // will make it somewhat unique. result.append("_" + nameArray.length); } } // The mapping indicates to skip over // all characters that are not letters or // digits. The first letter/digit // following a skipped character is // upper-cased. for (++i; i < nameLen; ++i) { char c = nameArray[i]; // if this is a bad char, skip it and remember to capitalize next // good character we encounter if (isPunctuation(c) || !Character.isJavaIdentifierPart(c)) { wordStart = true; continue; } if (wordStart && Character.isLowerCase(c)) { result.append(Character.toUpperCase(c)); } else { result.append(c); } // If c is not a character, but is a legal Java // identifier character, capitalize the next character. // For example: "22hi" becomes "22Hi" // wordStart = !Character.isLetter(c); wordStart = !Character.isLetter(c) && c != "_".charAt(0); } // covert back to a String String newName = result.toString(); // Follow JavaBean rules, but we need to check if the first // letter is uppercase first if (Character.isUpperCase(newName.charAt(0))) newName = Introspector.decapitalize(newName); // check for Java keywords if (isJavaKeyword(newName)) newName = makeNonJavaKeyword(newName); return newName; }
From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java
private List<String> _getTransients(Entity entity, boolean parent) throws Exception { File modelFile = null;//w w w. j a v a2 s.co m if (parent) { modelFile = new File(_outputPath + "/model/impl/" + entity.getName() + "ModelImpl.java"); } else { modelFile = new File(_outputPath + "/model/impl/" + entity.getName() + "Impl.java"); } String content = FileUtils.readFileToString(modelFile); Matcher matcher = _getterPattern.matcher(content); Set<String> getters = new HashSet<>(); while (!matcher.hitEnd()) { boolean found = matcher.find(); if (found) { String property = matcher.group(); if (property.contains("get")) { property = property.substring(property.indexOf("get") + 3, property.length() - 1); } else { property = property.substring(property.indexOf("is") + 2, property.length() - 1); } if (!entity.hasColumn(property) && !entity.hasColumn(Introspector.decapitalize(property))) { property = Introspector.decapitalize(property); getters.add(property); } } } matcher = _setterPattern.matcher(content); Set<String> setters = new HashSet<>(); while (!matcher.hitEnd()) { boolean found = matcher.find(); if (found) { String property = matcher.group(); property = property.substring(property.indexOf("set") + 3, property.length() - 1); if (!entity.hasColumn(property) && !entity.hasColumn(Introspector.decapitalize(property))) { property = Introspector.decapitalize(property); setters.add(property); } } } getters.retainAll(setters); List<String> transients = new ArrayList<>(getters); Collections.sort(transients); return transients; }
From source file:net.yasion.common.core.bean.wrapper.ExtendedBeanInfo.java
private String propertyNameFor(Method method) { return Introspector.decapitalize(method.getName().substring(3, method.getName().length())); }