Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getName.

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java

/**
 * Constructs the model for an entity/*  ww  w .j a v  a 2 s .  c o  m*/
 * 
 * @param entityClass
 *            the class of the entity
 * @return
 */
@SuppressWarnings("unchecked")
private synchronized <T> EntityModel<T> constructModel(String reference, Class<T> entityClass) {
    EntityModel<T> result = (EntityModel<T>) cache.get(reference);
    if (result == null) {
        boolean nested = reference.indexOf('.') > 0;

        // construct the basic model
        EntityModelImpl<T> model = constructModelInner(entityClass, reference);

        Map<String, String> attributeGroupMap = determineAttributeGroupMapping(model, entityClass);
        model.addAttributeGroup(EntityModel.DEFAULT_GROUP);

        alreadyProcessed.put(reference, entityClass);

        // keep track of main attributes - if no main attribute is defined, mark
        // either the
        // first string attribute or the first searchable attribute as the main
        boolean mainAttributeFound = false;
        AttributeModel firstStringAttribute = null;
        AttributeModel firstSearchableAttribute = null;

        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(entityClass);
        // create attribute models for all attributes
        List<AttributeModel> tempModelList = new ArrayList<>();
        for (PropertyDescriptor descriptor : descriptors) {
            if (!skipAttribute(descriptor.getName())) {
                List<AttributeModel> attributeModels = constructAttributeModel(descriptor, model,
                        model.getEntityClass(), nested, null);

                for (AttributeModel attributeModel : attributeModels) {

                    // check if the main attribute has been found
                    mainAttributeFound |= attributeModel.isMainAttribute();

                    // also keep track of the first string property...
                    if (firstStringAttribute == null && String.class.equals(attributeModel.getType())) {
                        firstStringAttribute = attributeModel;
                    }
                    // ... and the first searchable property
                    if (firstSearchableAttribute == null && attributeModel.isSearchable()) {
                        firstSearchableAttribute = attributeModel;
                    }
                    tempModelList.add(attributeModel);
                }
            }
        }

        // assign ordering and sort
        determineAttributeOrder(entityClass, reference, tempModelList);
        Collections.sort(tempModelList);

        // add the attributes to the model
        for (AttributeModel attributeModel : tempModelList) {
            // determine the attribute group name
            String group = attributeGroupMap.get(attributeModel.getName());
            if (StringUtils.isEmpty(group)) {
                group = EntityModel.DEFAULT_GROUP;
            }

            model.addAttributeModel(group, attributeModel);
        }

        if (!mainAttributeFound && !nested) {
            if (firstStringAttribute != null) {
                firstStringAttribute.setMainAttribute(true);
            } else if (firstSearchableAttribute != null) {
                firstSearchableAttribute.setMainAttribute(true);
            }
        }

        String sortOrder = null;
        Model annot = entityClass.getAnnotation(Model.class);
        if (annot != null && !StringUtils.isEmpty(annot.sortOrder())) {
            sortOrder = annot.sortOrder();
        }

        String sortOrderMsg = getEntityMessage(reference, EntityModel.SORT_ORDER);
        if (!StringUtils.isEmpty(sortOrderMsg)) {
            sortOrder = sortOrderMsg;
        }
        setSortOrder(model, sortOrder);
        cache.put(reference, model);
        result = model;
    }
    return result;
}

From source file:ca.sqlpower.object.PersistedSPObjectTest.java

/**
 * Tests the {@link SPSessionPersister} can update every settable property
 * on an object based on a persist call.
 *//*www. j a v a  2  s .  co m*/
public void testSPPersisterPersistsProperties() throws Exception {
    SPSessionPersister persister = new TestingSessionPersister("Testing Persister", root, getConverter());
    persister.setWorkspaceContainer(root.getWorkspaceContainer());
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    SPObject objectUnderTest = getSPObjectUnderTest();

    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass()));

    Set<String> propertiesToPersist = findPersistableBeanProperties(false, false);

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

        //Changing the UUID of the object makes it referenced as a different object
        //and would make the check later in this test fail.
        if (property.getName().equals("UUID"))
            continue;

        if (!propertiesToPersist.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName());

            // check for a setter
            if (property.getWriteMethod() == null)
                continue;

        } catch (NoSuchMethodException e) {
            logger.debug("Skipping non-settable property " + property.getName() + " on "
                    + objectUnderTest.getClass().getName());
            continue;
        }

        //special case for parent types. If a specific wabit object has a tighter parent then
        //WabitObject the getParentClass should return the parent type.
        Class<?> propertyType = property.getPropertyType();
        if (property.getName().equals("parent")) {
            propertyType = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType();
            logger.debug("Persisting parent, type is " + propertyType);
        }
        Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName());

        System.out.println("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal
                + "\" to newVal \"" + newVal + "\"");

        DataType type = PersisterUtils.getDataType(property.getPropertyType());
        Object basicNewValue = getConverter().convertToBasicType(newVal);
        persister.begin();
        persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type,
                getConverter().convertToBasicType(oldVal), basicNewValue);
        persister.commit();

        Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName());
        Object basicExpectedValue = getConverter().convertToBasicType(newValAfterSet);

        assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue,
                property.getPropertyType());
    }
}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

/**
 * Writes bean description recursively.//w w w  .ja v  a2  s. co m
 *
 * @param jgen
 *         to write to
 * @param currentVocab
 *         in context
 * @param valueType
 *         class of value
 * @param allRootParameters
 *         of the method that receives the request body
 * @param rootParameter
 *         the request body
 * @param currentCallValue
 *         the value at the current recursion level
 * @param propertyPath
 *         of the current recursion level
 * @throws IntrospectionException
 * @throws IOException
 */
private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType,
        ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue,
        String propertyPath) throws IntrospectionException, IOException {

    Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>();

    // collect supported properties from ctor

    Constructor[] constructors = valueType.getConstructors();
    // find default ctor
    Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
    // find ctor with JsonCreator ann
    if (constructor == null) {
        constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
    }
    if (constructor == null) {
        // TODO this can be a generic collection, find a way to describe it
        LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type "
                + valueType.getName());
        return;
    }

    int parameterCount = constructor.getParameterTypes().length;
    if (parameterCount > 0) {
        Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

        Class[] parameters = constructor.getParameterTypes();
        int paramIndex = 0;
        for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
            for (Annotation annotation : annotationsOnParameter) {
                if (JsonProperty.class == annotation.annotationType()) {
                    JsonProperty jsonProperty = (JsonProperty) annotation;
                    // TODO use required attribute of JsonProperty
                    String paramName = jsonProperty.value();

                    Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName);

                    ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter(
                            new MethodParameter(constructor, paramIndex), propertyValue);

                    // TODO collect ctor params, setter params and process
                    // TODO then handle single, collection and bean for both
                    properties.put(paramName, constructorParamInputParameter);
                    paramIndex++; // increase for each @JsonProperty
                }
            }
        }
        Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                + constructor.getName() + " are annotated with @JsonProperty");
    }

    // collect supported properties from setters

    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(valueType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map
    // TODO distinguish which properties should be printed as supported - now just setters
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);

        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                propertyDescriptor.getName());

        MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);
        ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter,
                propertyValue);

        properties.put(propertyName, propertySetterInputParameter);
    }

    // write all supported properties
    // TODO we are using the annotatedParameter.parameterName but should use the key of properties here:
    for (ActionInputParameter annotatedParameter : properties.values()) {
        String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName()
                : propertyPath + '.' + annotatedParameter.getParameterName();
        if (DataType.isSingleValueType(annotatedParameter.getParameterType())) {

            final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters);

            if (rootParameter.isIncluded(nextPropertyPathLevel)
                    && !rootParameter.isExcluded(nextPropertyPathLevel)) {
                writeSupportedProperty(jgen, currentVocab, annotatedParameter,
                        annotatedParameter.getParameterName(), possiblePropertyValues);
            }
            // TODO collections?
            //                        } else if (DataType.isArrayOrCollection(parameterType)) {
            //                            Object[] callValues = rootParameter.getValues();
            //                            int items = callValues.length;
            //                            for (int i = 0; i < items; i++) {
            //                                Object value;
            //                                if (i < callValues.length) {
            //                                    value = callValues[i];
            //                                } else {
            //                                    value = null;
            //                                }
            //                                recurseSupportedProperties(jgen, currentVocab, rootParameter
            // .getParameterType(),
            //                                        allRootParameters, rootParameter, value);
            //                            }
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", annotatedParameter.getParameterName());
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = annotatedParameter.getParameterType().getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                    annotatedParameter.getParameterName());

            recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(),
                    allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java

@RequestMapping(value = "/action/downloadQueryCsv/discoursedb_data.csv", method = RequestMethod.GET)
@ResponseBody//from   w  ww.j a  va2 s.  c om
String downloadQueryCsv(HttpServletResponse response, @RequestParam("query") String query,
        HttpServletRequest hsr, HttpSession session) throws IOException {

    securityUtils.authenticate(hsr, session);
    response.setContentType("application/csv; charset=utf-8");
    response.setHeader("Content-Disposition", "attachment");

    try {
        logger.info("Got query for csv: " + query);

        DdbQuery q = new DdbQuery(selector, discoursePartService, query);

        Page<BrowsingContributionResource> lbcr = q.retrieveAllContributions()
                .map(c -> new BrowsingContributionResource(c, annoService));

        StringBuilder output = new StringBuilder();
        ArrayList<String> headers = new ArrayList<String>();
        for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(BrowsingContributionResource.class)) {
            String name = pd.getName();
            if (!name.equals("class") && !name.equals("id") && !name.equals("links")) {
                headers.add(name);
            }
        }
        output.append(String.join(",", headers));
        output.append("\n");

        for (BrowsingContributionResource bcr : lbcr.getContent()) {
            String comma = "";
            BeanWrapper wrap = PropertyAccessorFactory.forBeanPropertyAccess(bcr);
            for (String hdr : headers) {

                String item = "";
                try {
                    item = wrap.getPropertyValue(hdr).toString();
                    item = item.replaceAll("\"", "\"\"");
                    item = item.replaceAll("^\\[(.*)\\]$", "$1");
                } catch (Exception e) {
                    logger.info(e.toString() + " For header " + hdr + " item " + item);
                    item = "";
                }
                if (hdr.equals("annotations") && item.length() > 0) {
                    logger.info("Annotation is " + item);
                }
                output.append(comma + "\"" + item + "\"");
                comma = ",";
            }
            output.append("\n");
        }
        return output.toString();
    } catch (Exception e) {
        return "ERROR:" + e.getMessage();
    }
}

From source file:ca.sqlpower.object.PersistedSPObjectTest.java

/**
 * This test will make changes to the {@link SPObject} under test and then
 * cause an exception forcing the persister to roll back the changes in the
 * object.// w ww .  j a  v a 2 s .c o m
 * <p>
 * Both the changes have to come through the persister initially before the
 * exception and they have to be reset after the exception.
 */
public void testSessionPersisterRollsBackProperties() throws Exception {
    SPObject objectUnderTest = getSPObjectUnderTest();
    final Map<PropertyDescriptor, Object> initialProperties = new HashMap<PropertyDescriptor, Object>();
    final Map<PropertyDescriptor, Object> newProperties = new HashMap<PropertyDescriptor, Object>();

    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass()));

    Set<String> propertiesToPersist = findPersistableBeanProperties(false, false);

    Set<String> ignorePropertySet = getRollbackTestIgnorePropertySet();

    NewValueMaker valueMaker = createNewValueMaker(getRootObject(), getPLIni());

    SPSessionPersister persister = new TestingSessionPersister("tester", getRootObject(), getConverter());
    persister.setWorkspaceContainer(getRootObject().getWorkspaceContainer());

    failureReason = null;

    SPPersisterListener listener = new SPPersisterListener(new CountingSPPersister(), converter) {

        private boolean transactionAlreadyFinished = false;

        @Override
        public void transactionEnded(TransactionEvent e) {
            if (transactionAlreadyFinished)
                return;
            transactionAlreadyFinished = true;
            try {
                for (Map.Entry<PropertyDescriptor, Object> newProperty : newProperties.entrySet()) {
                    Object objectUnderTest = getSPObjectUnderTest();
                    Object newVal = newProperty.getValue();
                    Object basicNewValue = converter.convertToBasicType(newVal);

                    Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest,
                            newProperty.getKey().getName());
                    Object basicExpectedValue = converter.convertToBasicType(newValAfterSet);

                    logger.debug("Testing property " + newProperty.getKey().getName());
                    assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue,
                            newProperty.getKey().getPropertyType());
                }
            } catch (Throwable ex) {
                failureReason = ex;
                throw new RuntimeException(ex);
            }
            throw new RuntimeException("Forcing rollback.");
        }
    };
    //Transactions begin and commits are currently sent on the workspace.
    getRootObject().getParent().addSPListener(listener);

    persister.begin();
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

        //Changing the UUID of the object makes it referenced as a different object
        //and would make the check later in this test fail.
        if (property.getName().equals("UUID"))
            continue;

        if (!propertiesToPersist.contains(property.getName()))
            continue;

        if (ignorePropertySet.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName());

            // check for a setter
            if (property.getWriteMethod() == null)
                continue;

        } catch (NoSuchMethodException e) {
            logger.debug("Skipping non-settable property " + property.getName() + " on "
                    + objectUnderTest.getClass().getName());
            continue;
        }

        initialProperties.put(property, oldVal);

        //special case for parent types. If a specific wabit object has a tighter parent then
        //WabitObject the getParentClass should return the parent type.
        Class<?> propertyType = property.getPropertyType();
        if (property.getName().equals("parent")) {
            propertyType = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType();
            logger.debug("Persisting parent, type is " + propertyType);
        }
        Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName());

        DataType type = PersisterUtils.getDataType(property.getPropertyType());
        Object basicNewValue = converter.convertToBasicType(newVal);
        persister.begin();
        persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type,
                converter.convertToBasicType(oldVal), basicNewValue);
        persister.commit();

        newProperties.put(property, newVal);
    }

    try {
        persister.commit();
        fail("An exception should make the persister hit the exception block.");
    } catch (Exception e) {
        //continue, exception expected.
    }

    if (failureReason != null) {
        throw new RuntimeException("Failed when asserting properties were " + "fully persisted.",
                failureReason);
    }

    for (Map.Entry<PropertyDescriptor, Object> entry : initialProperties.entrySet()) {
        assertEquals("Property " + entry.getKey().getName() + " did not match after rollback.",
                entry.getValue(), PropertyUtils.getSimpleProperty(objectUnderTest, entry.getKey().getName()));
    }
}

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private List<Column2Property> getColumnsFromObj(Object obj, String[] columns) {
    Class clazz = obj.getClass();
    List<Column2Property> validColumns = new ArrayList<Column2Property>();

    // ???/*from   ww w . j  a  v a2 s.c  om*/
    for (Field field : clazz.getDeclaredFields()) {
        boolean skip = true;
        String columnName = null;
        Annotation[] annotations = field.getAnnotations();
        for (Annotation a : annotations) {
            if (a instanceof Column) {
                columnName = ((Column) a).name();
                if (columns != null && !_inarray_(columns, columnName))
                    skip = true;
                else {
                    skip = false;
                }

                break;
            }
        }

        String s = field.getName();
        PropertyDescriptor pd = null;

        if (!skip) {
            // ?gettersetter
            try {
                pd = new PropertyDescriptor(s, clazz);
                if (pd == null || pd.getWriteMethod() == null || pd.getReadMethod() == null) {
                    skip = true;
                }
            } catch (Exception e) {
                skip = true;
            }
        }

        if (!skip) {
            Column2Property c = new Column2Property();
            c.propertyName = pd.getName();
            c.setterMethodName = pd.getWriteMethod().getName();
            c.getterMethodName = pd.getReadMethod().getName();
            c.columnName = columnName;
            validColumns.add(c);
        }
    }

    Column2Property c = new Column2Property();
    c.propertyName = "id";
    c.setterMethodName = "setId";
    c.getterMethodName = "getId";
    c.columnName = "C_ID";
    validColumns.add(c);

    return validColumns;
}

From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java

/**
 * Overwrite the default values with annotation values
 * /* ww  w .j  av a 2  s .  co  m*/
 * @param parentClass
 * @param model
 * @param descriptor
 */
private void setAnnotationOverrides(Class<?> parentClass, AttributeModelImpl model,
        PropertyDescriptor descriptor, boolean nested) {
    Attribute attribute = ClassUtils.getAnnotation(parentClass, descriptor.getName(), Attribute.class);

    // overwrite with annotation values
    if (attribute != null) {
        if (!StringUtils.isEmpty(attribute.displayName())) {
            model.setDisplayName(attribute.displayName());
            // by default, set prompt and description to the display
            // name as
            // well -
            // they are overwritten in the following code if they are
            // explicitly set
            model.setPrompt(attribute.displayName());
            model.setDescription(attribute.displayName());
        }

        if (!StringUtils.isEmpty(attribute.defaultValue())) {
            String defaultValue = attribute.defaultValue();
            setDefaultValue(model, defaultValue);
        }
        if (!StringUtils.isEmpty(attribute.description())) {
            model.setDescription(attribute.description());
        }
        if (!StringUtils.isEmpty(attribute.displayFormat())) {
            model.setDisplayFormat(attribute.displayFormat());
        }
        if (!StringUtils.isEmpty(attribute.prompt())) {
            model.setPrompt(attribute.prompt());
        }

        if (attribute.readOnly()) {
            model.setReadOnly(true);
        }

        // set visibility (but not for nested attributes - these are hidden by default)
        if (attribute.visible() != null && !VisibilityType.INHERIT.equals(attribute.visible()) && !nested) {
            model.setVisible(VisibilityType.SHOW.equals(attribute.visible()));
            model.setVisibleInTable(model.isVisible());
        }

        if (attribute.searchable() && !nested) {
            model.setSearchable(true);
        }

        if (!attribute.sortable()) {
            model.setSortable(false);
        }

        if (attribute.main() && !nested) {
            model.setMainAttribute(true);
        }

        if (attribute.showInTable() != null && !VisibilityType.INHERIT.equals(attribute.showInTable())
                && !nested) {
            model.setVisibleInTable(VisibilityType.SHOW.equals(attribute.showInTable()));
        }

        if (attribute.complexEditable()) {
            model.setComplexEditable(true);
        }

        if (attribute.image()) {
            model.setImage(true);
        }

        if (attribute.week()) {
            model.setWeek(true);
        }

        if (!StringUtils.isEmpty(attribute.allowedExtensions())) {
            String[] extensions = attribute.allowedExtensions().split(",");
            Set<String> hashSet = Sets.newHashSet(extensions);
            model.setAllowedExtensions(hashSet);
        }

        if (!StringUtils.isEmpty(attribute.trueRepresentation())) {
            model.setTrueRepresentation(attribute.trueRepresentation());
        }

        if (!StringUtils.isEmpty(attribute.falseRepresentation())) {
            model.setFalseRepresentation(attribute.falseRepresentation());
        }

        if (attribute.detailFocus()) {
            model.setDetailFocus(true);
        }

        if (attribute.percentage()) {
            model.setPercentage(true);
        }

        if (attribute.currency()) {
            model.setCurrency(true);
        }

        if (attribute.dateType() != null && !AttributeDateType.INHERIT.equals(attribute.dateType())) {
            model.setDateType(attribute.dateType());
        }

        // overrule select mode - by default, this overrules the search select mode as well
        if (attribute.selectMode() != null && !AttributeSelectMode.INHERIT.equals(attribute.selectMode())) {
            model.setSelectMode(attribute.selectMode());
            model.setSearchSelectMode(attribute.selectMode());
        }

        // set multiple search
        if (attribute.multipleSearch()) {
            model.setMultipleSearch(true);
            // by default, use a fancy list for multiple search
            model.setSearchSelectMode(AttributeSelectMode.FANCY_LIST);
        }

        if (!AttributeSelectMode.INHERIT.equals(attribute.searchSelectMode())) {
            model.setSearchSelectMode(attribute.searchSelectMode());
        }

        model.setSearchCaseSensitive(attribute.searchCaseSensitive());
        model.setSearchPrefixOnly(attribute.searchPrefixOnly());

        if (attribute.textFieldMode() != null
                && !AttributeTextFieldMode.INHERIT.equals(attribute.textFieldMode())) {
            model.setTextFieldMode(attribute.textFieldMode());
        }

        if (attribute.precision() > -1) {
            model.setPrecision(attribute.precision());
        }

        if (attribute.minLength() > -1) {
            model.setMinLength(attribute.minLength());
        }

        if (attribute.maxLength() > -1) {
            model.setMaxLength(attribute.maxLength());
        }

        if (attribute.url()) {
            model.setUrl(true);
        }

        if (!StringUtils.isEmpty(attribute.replacementSearchPath())) {
            model.setReplacementSearchPath(attribute.replacementSearchPath());
        }

        if (!StringUtils.isEmpty(attribute.quickAddPropertyName())) {
            model.setQuickAddPropertyName(attribute.quickAddPropertyName());
            model.setQuickAddAllowed(true);
        }

        if (attribute.required()) {
            model.setRequired(true);
        }

        if (!attribute.useThousandsGrouping()) {
            model.setUseThousandsGrouping(false);
        }

        if (attribute.searchForExactValue()) {
            model.setSearchForExactValue(true);
        }

        if (!StringUtils.isEmpty(attribute.fileNameProperty())) {
            model.setFileNameProperty(attribute.fileNameProperty());
        }
    }
}

From source file:com.complexible.pinto.RDFMapper.java

private IRI getProperty(final PropertyDescriptor thePropertyDescriptor) {
    final RdfProperty aAnnotation = getPropertyAnnotation(thePropertyDescriptor);

    if (aAnnotation == null || Strings.isNullOrEmpty(aAnnotation.value())) {
        return mValueFactory.createIRI(mDefaultNamespace + thePropertyDescriptor.getName());
    } else {/*from w w  w  .j a v a 2  s  .  co m*/
        return iri(aAnnotation.value());
    }
}

From source file:com.googlecode.wicketwebbeans.model.BeanMetaData.java

private void init() {
    // Check if bean supports PropertyChangeListeners.
    hasAddPropertyChangeListenerMethod = getAddPropertyChangeListenerMethod() != null;
    hasRemovePropertyChangeListenerMethod = getRemovePropertyChangeListenerMethod() != null;

    String baseBeanClassName = getBaseClassName(beanClass);

    // Deduce actions from the component.
    List<Method> actionMethods = getActionMethods(component.getClass());
    for (Method method : actionMethods) {
        String name = method.getName();
        String prefixedName = ACTION_PROPERTY_PREFIX + name;
        String label = getLabelFromLocalizer(baseBeanClassName, prefixedName);
        if (label == null) {
            label = createLabel(name);//w w  w.  ja v a2s.  co  m
        }

        ElementMetaData actionMeta = new ElementMetaData(this, prefixedName, label, null);
        actionMeta.setAction(true);
        elements.add(actionMeta);
    }

    // Create defaults based on the bean itself.
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor descriptor : descriptors) {
        String name = descriptor.getName();

        // Skip getClass() and methods that are not readable or hidden.
        if (name.equals("class") || descriptor.getReadMethod() == null || descriptor.isHidden()) {
            continue;
        }

        String label = getLabelFromLocalizer(baseBeanClassName, name);
        if (label == null) {
            label = descriptor.getDisplayName();
        }

        if (label.equals(name)) {
            label = createLabel(name);
        }

        ElementMetaData propertyMeta = new ElementMetaData(this, name, label,
                descriptor.getReadMethod().getGenericReturnType());
        propertyMeta.setViewOnly(isViewOnly());
        elements.add(propertyMeta);

        if (descriptor.getWriteMethod() == null) {
            propertyMeta.setViewOnly(true);
        }

        deriveElementFromAnnotations(descriptor, propertyMeta);
    }

    // Collect various sources of metadata for the bean we're interested in. 
    collectAnnotations();
    collectFromBeanProps();
    collectBeansAnnotation(beansMetaData, false);

    // Process action annotations on component.
    for (Method method : getActionMethods(component.getClass())) {
        Action action = method.getAnnotation(Action.class);
        processActionAnnotation(action, method.getName());
    }

    // Determine the hierarchy of Bean contexts. I.e., the default Bean is always processed first, followed by those that
    // extend it, etc. This acts as a stack.
    List<Bean> beansHier = buildContextStack();

    // Apply beans in order from highest to lowest. The default context will always be first.
    boolean foundSpecifiedContext = false;
    for (Bean bean : beansHier) {
        if (context != null && context.equals(bean.context())) {
            foundSpecifiedContext = true;
        }

        processBeanAnnotation(bean);
    }

    // Ensure that if a context was specified, that we found one in the metadata. Otherwise it might have been a typo.
    if (context != null && !foundSpecifiedContext) {
        throw new RuntimeException("Could not find specified context '" + context + "' in metadata.");
    }

    // Post-process Bean-level parameters
    if (!getBooleanParameter(PARAM_DISPLAYED)) {
        elements.clear();
        tabs.clear();
    }

    // Configure tabs
    if (tabs.isEmpty()) {
        // Create single default tab.
        tabs.add(new TabMetaData(this, DEFAULT_TAB_ID, getParameter(PARAM_LABEL)));
    }

    String defaultTabId = tabs.get(0).getId();

    if (!getBooleanParameter(PARAM_EXPLICIT_ONLY) || defaultTabId.equals(DEFAULT_TAB_ID)) {
        // Post-process each property based on bean parameters
        for (ElementMetaData elementMeta : elements) {
            // If element is not on a tab, add it to the first. If it's an
            // action, it must have been assigned an order to
            // appear on a tab. Otherwise it is a global action.
            if (elementMeta.getTabId() == null && (!elementMeta.isAction()
                    || (elementMeta.isAction() && elementMeta.isActionSpecifiedInProps()))) {
                elementMeta.setTabId(defaultTabId);
            }
        }
    }

    // Remove elements not specified in props
    if (getBooleanParameter(PARAM_EXPLICIT_ONLY)) {
        for (Iterator<ElementMetaData> iter = elements.iterator(); iter.hasNext();) {
            ElementMetaData element = iter.next();
            if (!element.isSpecifiedInProps()) {
                iter.remove();
            }
        }
    }

    Collections.sort(elements, new Comparator<ElementMetaData>() {
        public int compare(ElementMetaData o1, ElementMetaData o2) {
            return (o1.getOrder() > o2.getOrder() ? 1 : (o1.getOrder() < o2.getOrder() ? -1 : 0));
        }
    });
}