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:de.hybris.platform.webservices.AbstractWebServicesTest.java

private Map<String, PropertyDescriptor> getPropertyDescriptors(final Class clazz) {
    final Map<String, PropertyDescriptor> result = new HashMap<String, PropertyDescriptor>();
    try {//ww  w. ja v a  2 s .com
        final PropertyDescriptor[] pdList = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        for (final PropertyDescriptor pd : pdList) {
            result.put(pd.getName(), pd);
        }
    } catch (final Exception e) {
        LOG.error(e.getMessage(), e);
        Assert.fail();
    }
    return result;
}

From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java

/**
 * Reflective test that the wabit object can be persisted as an object and all of
 * its properties are persisted with it.
 *//*from  w ww .j ava  2 s . c  o m*/
public void testPersistsObjectAsChild() throws Exception {

    //This may need to actually have the wabit object as a child to itself.
    WabitObject parent = new StubWabitObject();

    CountingWabitPersister persister = new CountingWabitPersister();
    WorkspacePersisterListener listener = new WorkspacePersisterListener(
            new StubWabitSession(new StubWabitSessionContext()), persister, true);
    SPObject wo = getObjectUnderTest();
    if (wo.getParent() == null) {
        wo.setParent(parent);
    }

    listener.childAdded(new SPChildEvent(parent, wo.getClass(), wo, 0, EventType.ADDED));

    assertTrue(persister.getPersistObjectCount() > 0);
    PersistedSPObject persistedWabitObject = persister.getAllPersistedObjects().get(0);
    assertEquals(wo.getClass().getSimpleName(), persistedWabitObject.getType());
    assertEquals(wo.getUUID(), persistedWabitObject.getUUID());

    //confirm we get one persist property for each getter/setter pair
    //confirm we get one persist property for each value in one of the constructors in the object.

    List<PropertyDescriptor> settableProperties = new ArrayList<PropertyDescriptor>(
            Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())));
    List<PersistedSPOProperty> allPropertyChanges = persister.getAllPropertyChanges();
    Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist();
    ignorableProperties.addAll(getPropertiesToIgnoreForEvents());

    List<PersistedSPOProperty> changesOnObject = new ArrayList<PersistedSPOProperty>();

    logger.debug("Looking through properties registered to persist...");
    for (int i = allPropertyChanges.size() - 1; i >= 0; i--) {
        if (allPropertyChanges.get(i).getUUID().equals(wo.getUUID())) {
            changesOnObject.add(allPropertyChanges.get(i));
            logger.debug(
                    "The property " + allPropertyChanges.get(i).getPropertyName() + " is ready to persist!");
        } else {
            logger.debug("The property " + allPropertyChanges.get(i).getPropertyName()
                    + " has not been set in WabitSessionPersister and"
                    + " WorkspacePersisterListener to persist properly!");
        }
    }

    List<String> settablePropertyNames = new ArrayList<String>();
    for (PropertyDescriptor pd : settableProperties) {
        settablePropertyNames.add(pd.getName());
    }

    settablePropertyNames.removeAll(ignorableProperties);

    if (settablePropertyNames.size() != changesOnObject.size()) {
        for (String descriptor : settablePropertyNames) {
            PersistedSPOProperty foundChange = null;
            for (PersistedSPOProperty propertyChange : changesOnObject) {
                if (propertyChange.getPropertyName().equals(descriptor)) {
                    foundChange = propertyChange;
                    break;
                }
            }
            assertNotNull("The property " + descriptor + " was not persisted", foundChange);
        }
    }
    logger.debug("Property names" + settablePropertyNames);
    assertTrue(settablePropertyNames.size() <= changesOnObject.size());

    WabitSessionPersisterSuperConverter factory = new WabitSessionPersisterSuperConverter(
            new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true);

    for (String descriptor : settablePropertyNames) {
        PersistedSPOProperty foundChange = null;
        for (PersistedSPOProperty propertyChange : changesOnObject) {
            if (propertyChange.getPropertyName().equals(descriptor)) {
                foundChange = propertyChange;
                break;
            }
        }
        assertNotNull("The property " + descriptor + " was not persisted", foundChange);
        assertTrue(foundChange.isUnconditional());
        assertEquals(wo.getUUID(), foundChange.getUUID());
        Object value = PropertyUtils.getSimpleProperty(wo, descriptor);

        //XXX will replace this later
        List<Object> additionalVals = new ArrayList<Object>();
        if (wo instanceof OlapQuery && descriptor.equals("currentCube")) {
            additionalVals.add(((OlapQuery) wo).getOlapDataSource());
        }
        Object valueConvertedToBasic = factory.convertToBasicType(value, additionalVals.toArray());
        logger.debug("Property \"" + descriptor + "\": expected \"" + valueConvertedToBasic + "\" but was \""
                + foundChange.getNewValue() + "\" of type " + foundChange.getDataType());

        assertEquals(valueConvertedToBasic, foundChange.getNewValue());
    }
}

From source file:com.github.erchu.beancp.commons.NameBasedMapConvention.java

@Override
public List<Binding> getBindings(final MappingInfo mappingsInfo, final Class sourceClass,
        final Class destinationClass) {
    List<Binding> result = new LinkedList<>();
    BeanInfo sourceBeanInfo, destinationBeanInfo;

    try {/*from ww w.j a  v  a 2s .c o  m*/
        destinationBeanInfo = Introspector.getBeanInfo(destinationClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", destinationClass), ex);
    }

    try {
        sourceBeanInfo = Introspector.getBeanInfo(sourceClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", sourceClass), ex);
    }

    boolean allDestinationMembersMapped = true;

    for (PropertyDescriptor destinationProperty : destinationBeanInfo.getPropertyDescriptors()) {
        Method destinationMember = destinationProperty.getWriteMethod();

        if (destinationMember != null) {
            BindingSide destinationBindingSide = new PropertyBindingSide(destinationProperty);

            if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
                continue;
            }

            List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                    destinationProperty.getName(), MemberAccessType.PROPERTY);

            if (sourceBindingSide != null) {
                BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

                Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                        sourceBindingSideArray, destinationBindingSide);

                if (binding != null) {
                    result.add(binding);
                }
            } else {
                allDestinationMembersMapped = false;
            }
        }
    }

    for (Field destinationMember : destinationClass.getFields()) {
        BindingSide destinationBindingSide = new FieldBindingSide(destinationMember);

        if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
            continue;
        }

        List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                destinationMember.getName(), MemberAccessType.FIELD);

        if (sourceBindingSide != null) {

            BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

            Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                    sourceBindingSideArray, destinationBindingSide);

            if (binding != null) {
                result.add(binding);
            }
        } else {
            allDestinationMembersMapped = false;
        }
    }

    if (_failIfNotAllDestinationMembersMapped) {
        if (allDestinationMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all destination members are mapped." + " This exception has been trown because "
                            + "failIfNotAllDestinationMembersMapped option is enabled.");
        }
    }

    if (_failIfNotAllSourceMembersMapped) {
        boolean allSourceMembersMapped = true;

        for (PropertyDescriptor sourceProperty : sourceBeanInfo.getPropertyDescriptors()) {
            Method sourceMember = sourceProperty.getReadMethod();

            if (sourceMember != null) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new PropertyBindingSide(sourceProperty);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        // if all properties are mapped we still need to check fields
        if (allSourceMembersMapped) {
            for (Field sourceMember : sourceClass.getFields()) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new FieldBindingSide(sourceMember);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        if (allSourceMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all source members are mapped." + " This exception has been trown because "
                            + "failIfNotAllSourceMembersMapped option is enabled.");
        }
    }

    return result;
}

From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java

/**
 * Uses reflection to find all the settable properties of the object under test,
 * and fails if any of them can be set without an event happening.
 *//*  ww  w  .j a  va2  s . c o m*/
public void testSettingPropertiesFiresEvents() throws Exception {

    CountingWabitListener listener = new CountingWabitListener();
    SPObject wo = getObjectUnderTest();
    wo.addSPListener(listener);

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

    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEvents.contains(property.getName()))
            continue;

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

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

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

        int oldChangeCount = listener.getPropertyChangeCount();
        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());

        try {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(wo, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)
            assertTrue(
                    "Event for set " + property.getName() + " on " + wo.getClass().getName() + " didn't fire!",
                    listener.getPropertyChangeCount() > oldChangeCount);
            if (listener.getPropertyChangeCount() == oldChangeCount + 1) {
                assertEquals("Property name mismatch for " + property.getName() + " in " + wo.getClass(),
                        property.getName(), listener.getLastPropertyEvent().getPropertyName());
                assertEquals("New value for " + property.getName() + " was wrong", newVal,
                        listener.getLastPropertyEvent().getNewValue());
            }
        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + wo.getClass().getName());
        }
    }

}

From source file:org.codehaus.groovy.grails.plugins.couchdb.domain.CouchDomainClass.java

private void evaluateClassProperties(PropertyDescriptor[] descriptors) {

    for (PropertyDescriptor descriptor : descriptors) {
        if (GrailsDomainConfigurationUtil.isNotConfigurational(descriptor)) {
            final CouchDomainClassProperty property = new CouchDomainClassProperty(this, descriptor);

            if (property.isAnnotatedWith(CouchId.class) || property.isAnnotatedWith(Id.class)) {
                this.identifier = property;
            } else if (property.isAnnotatedWith(CouchVersion.class)
                    || property.isAnnotatedWith(Version.class)) {
                this.version = property;
            } else if (property.isAnnotatedWith(CouchAttachments.class)) {
                this.attachments = property;
            } else {
                propertyMap.put(descriptor.getName(), property);
                if (property.isPersistent()) {
                    persistentProperties.put(descriptor.getName(), property);
                }//from  w  ww. java2  s .c  o  m
            }
        }
    }

    // if we don't have an annotated identifier, version, or attachments then try to find fields
    //  with the simple names and use them...
    if (this.identifier == null) {
        if (propertyMap.containsKey(GrailsDomainClassProperty.IDENTITY)) {
            this.identifier = (CouchDomainClassProperty) propertyMap.get(GrailsDomainClassProperty.IDENTITY);
            propertyMap.remove(GrailsDomainClassProperty.IDENTITY);
            persistentProperties.remove(GrailsDomainClassProperty.IDENTITY);
        } else {
            throw new GrailsDomainException(
                    "Identity property not found, but required in domain class [" + getFullName() + "]");
        }
    }

    if (this.identifier.getType() != String.class) {
        throw new GrailsDomainException(
                "Identity property in domain class [" + getFullName() + "] must be a String.");
    }

    if (this.version == null) {
        if (propertyMap.containsKey(GrailsDomainClassProperty.VERSION)) {
            this.version = (CouchDomainClassProperty) propertyMap.get(GrailsDomainClassProperty.VERSION);
            propertyMap.remove(GrailsDomainClassProperty.VERSION);
            persistentProperties.remove(GrailsDomainClassProperty.VERSION);
        } else {
            throw new GrailsDomainException(
                    "Version property not found, but required in domain class [" + getFullName() + "]");
        }
    }

    if (this.version.getType() != String.class) {
        throw new GrailsDomainException(
                "Version property in domain class [" + getFullName() + "] must be a String.");
    }

    if (this.attachments == null) {
        if (propertyMap.containsKey("attachments")) {
            this.attachments = (CouchDomainClassProperty) propertyMap.get("attachments");

            propertyMap.remove("attachments");
            persistentProperties.remove("attachments");
        }
    }

    this.identifier.setIdentity(true);

    // convert to arrays for optimization
    propertiesArray = propertyMap.values().toArray(new GrailsDomainClassProperty[propertyMap.size()]);
    persistentPropertyArray = persistentProperties.values()
            .toArray(new GrailsDomainClassProperty[persistentProperties.size()]);

}

From source file:de.extra.client.core.annotation.PropertyPlaceholderPluginConfigurer.java

private void setPluginProperties(final ConfigurableListableBeanFactory beanFactory, final Properties properties,
        final String beanName, final Class<?> clazz) {
    final PluginConfiguration annotationConfigutation = clazz.getAnnotation(PluginConfiguration.class);
    final MutablePropertyValues mutablePropertyValues = beanFactory.getBeanDefinition(beanName)
            .getPropertyValues();//from www.j  a  v  a  2  s  . c o  m

    for (final PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
        final Method setter = property.getWriteMethod();
        PluginValue valueAnnotation = null;
        if (setter != null && setter.isAnnotationPresent(PluginValue.class)) {
            valueAnnotation = setter.getAnnotation(PluginValue.class);
        }
        if (valueAnnotation != null) {
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            final String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (StringUtils.isEmpty(value)) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + key
                        + "=" + value + "]");
            }
            mutablePropertyValues.addPropertyValue(property.getName(), value);
        }
    }

    for (final Field field : clazz.getDeclaredFields()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("examining field=[" + clazz.getName() + "." + field.getName() + "]");
        }
        if (field.isAnnotationPresent(PluginValue.class)) {
            final PluginValue valueAnnotation = field.getAnnotation(PluginValue.class);
            final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

            if (property == null || property.getWriteMethod() == null) {
                throw new BeanCreationException(beanName,
                        "setter for property=[" + clazz.getName() + "." + field.getName() + "] not available.");
            }
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (value == null) {
                // DEFAULT Value suchen
                final int separatorIndex = key.indexOf(VALUE_SEPARATOR);
                if (separatorIndex != -1) {
                    final String actualPlaceholder = key.substring(0, separatorIndex);
                    final String defaultValue = key.substring(separatorIndex + VALUE_SEPARATOR.length());
                    value = resolvePlaceholder(actualPlaceholder, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                    if (value == null) {
                        value = defaultValue;
                    }
                }
            }

            if (value != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("setting property=[" + clazz.getName() + "." + field.getName() + "] value=[" + key
                            + "=" + value + "]");
                }
                mutablePropertyValues.addPropertyValue(field.getName(), value);
            } else if (!ignoreNullValues) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
        }
    }
}

From source file:ch.algotrader.service.ManagementServiceImpl.java

/**
 * {@inheritDoc}//from w ww .ja va2 s.c  o m
 */
@Override
@ManagedOperation(description = "Send an order")
@ManagedOperationParameters({
        @ManagedOperationParameter(name = "security", description = "<html><ul> <li> securityId (e.g. 123) </li> <li> symbol (e.g. GOOG) </li> <li> isin, prefix with &quot;isin:&quot;, (e.g. &quot;isin:EU0009654078&quot;) </li> <li> bbgid, prefix with &quot;bbgid:&quot;, (e.g. &quot;bbgid:BBG005NHP5P9&quot;) </li> <li> ric, prefix with &quot;ric:&quot;, (e.g. &quot;ric:.SPX&quot;) </li> <li> conid, prefix with &quot;conid:&quot;, (e.g. &quot;conid:12087817&quot;) </li> </ul></html>"),
        @ManagedOperationParameter(name = "quantity", description = "The requested quantity (positive value)"),
        @ManagedOperationParameter(name = "side", description = "<html>Side: <ul> <li> B (BUY) </li> <li> S (SELL) </li> <li> SS (SELL_SHORT) </li> </ul></html>"),
        @ManagedOperationParameter(name = "type", description = "<html>Order type: <ul> <li> M (Market) </li> <li> L (Limit) </li> <li> S (Stop) </li> <li> SL (StopLimit) </li> <li> TI (TickwiseIncremental) </li> <li> VI (VariableIncremental) </li> <li> SLI (Slicing) </li> <li> V (VWAP) </li> <li> TP (Target position) </li> <li> TL (Trailing Limit) </li> </ul> or order preference (e.g. 'SLICING' or 'VWAP')</html>"),
        @ManagedOperationParameter(name = "accountName", description = "accountName (optional)"),
        @ManagedOperationParameter(name = "exchangeName", description = "exchangeName (optional)"),
        @ManagedOperationParameter(name = "properties", description = "<html>Additional properties to be set on the order as a comma separated list (e.g. stop=12.0,limit=12.5).<p> In addition custom properties can be set on the order (e.g. FIX123=12, INTERNALportfolio=TEST)</hmlt>") })
public void sendOrder(final String security, final long quantity, final String side, final String type,
        String accountName, final String exchangeName, final String properties) {

    Validate.notEmpty(type, "Type is empty");
    Validate.notEmpty(security, "Security is empty");
    Side sideObject = null;
    if (!"TP".equals(type)) {
        Validate.notEmpty(side, "Side is empty");
        sideObject = Side.fromValue(side);
    }

    Strategy strategy = this.lookupService.getStrategyByName(this.engine.getStrategyName());
    Security securityObject = this.lookupService.getSecurity(getSecurityId(security));

    // instantiate the order
    Order order;
    if ("M".equals(type)) {
        order = MarketOrder.Factory.newInstance();
    } else if ("L".equals(type)) {
        order = LimitOrder.Factory.newInstance();
    } else if ("S".equals(type)) {
        order = StopOrder.Factory.newInstance();
    } else if ("SL".equals(type)) {
        order = StopLimitOrder.Factory.newInstance();
    } else if ("TI".equals(type)) {
        order = new TickwiseIncrementalOrder();
    } else if ("VI".equals(type)) {
        order = new VariableIncrementalOrder();
    } else if ("SLI".equals(type)) {
        order = new SlicingOrder();
    } else if ("V".equals(type)) {
        order = new VWAPOrder();
    } else if ("TP".equals(type)) {
        order = new TargetPositionOrder();
    } else if ("TL".equals(type)) {
        order = new TrailingLimitOrder();
    } else {

        // create the order from an OrderPreference
        order = this.orderService.createOrderByOrderPreference(type);
    }

    // set common values
    order.setStrategy(strategy);
    order.setSecurity(securityObject);
    order.setQuantity(Math.abs(quantity));
    order.setSide(sideObject);

    // set the account
    if (StringUtils.isEmpty(accountName)) {
        if (order.getAccount() == null) {
            accountName = this.commonConfig.getDefaultAccountName();
            Account accountByName = this.lookupService.getAccountByName(accountName);
            if (accountByName == null) {
                throw new IllegalArgumentException("Account '" + accountName + "' not found");
            }
            order.setAccount(accountByName);
        }
    } else {
        Account accountByName = this.lookupService.getAccountByName(accountName);
        if (accountByName == null) {
            throw new IllegalArgumentException("Account '" + accountName + "' not found");
        }
        order.setAccount(accountByName);
    }

    // set the exchange
    if (!StringUtils.isEmpty(exchangeName)) {
        Exchange exchange = this.lookupService.getExchangeByName(exchangeName);
        order.setExchange(exchange);
    }

    // set additional properties
    if (!StringUtils.isEmpty(properties)) {

        // get the properties
        Map<String, String> propertiesMap = new HashMap<>();
        for (String nameValue : properties.split(",")) {
            propertiesMap.put(nameValue.split("=")[0], nameValue.split("=")[1]);
        }

        // separate properties that correspond to actual Order fields from the rest
        Map<String, String> fields = new HashMap<>();
        PropertyDescriptor[] pds = BeanUtil.getPropertyDescriptors(order);
        for (PropertyDescriptor pd : pds) {
            String name = pd.getName();
            if (propertiesMap.containsKey(name)) {
                fields.put(name, propertiesMap.get(name));
                propertiesMap.remove(name);
            }
        }

        // populate the fields
        try {
            BeanUtil.populate(order, fields);
        } catch (ReflectiveOperationException ex) {
            throw new ServiceException(ex);
        }

        // create OrderProperty Entities for the remaining properties
        for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {

            OrderProperty orderProperty = OrderProperty.Factory.newInstance();

            String name = entry.getKey();
            if (name.toUpperCase().startsWith(OrderPropertyType.FIX.toString())) {
                name = name.substring(3);
                orderProperty.setType(OrderPropertyType.FIX);
            } else if (name.toUpperCase().startsWith(OrderPropertyType.IB.toString())) {
                name = name.substring(2);
                orderProperty.setType(OrderPropertyType.IB);
            } else if (name.toUpperCase().startsWith(OrderPropertyType.INTERNAL.toString())) {
                name = name.substring(8);
                orderProperty.setType(OrderPropertyType.INTERNAL);
            } else {
                throw new IllegalArgumentException("unrecognized property " + name);
            }
            orderProperty.setName(name);
            orderProperty.setValue(entry.getValue());

            order.addOrderProperties(name, orderProperty);
        }
    }

    // send orders
    this.orderService.sendOrder(order);

}

From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java

/**
 * This test uses the object under test to ensure that the
 * {@link WabitSessionPersister} updates each property appropriately on
 * persistence./*from   w ww  . j  a v a 2  s  .  c o m*/
 */
public void testPersisterUpdatesProperties() throws Exception {

    SPObject wo = getObjectUnderTest();

    WabitSessionPersister persister = new WabitSessionPersister("secondary test persister", session,
            getWorkspace(), true);

    WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter(
            new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true);
    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()));

    //Ignore properties that are not in events because we won't have an event
    //to respond to.
    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();

    Set<String> propertiesToIgnoreForPersisting = getPropertiesToIgnoreForPersisting();

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

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

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

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

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

        } catch (NoSuchMethodException e) {
            logger.debug(
                    "Skipping non-settable property " + property.getName() + " on " + wo.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 = getParentClass();
        }
        Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName());

        logger.debug("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal
                + "\" to newVal \"" + newVal + "\"");

        //XXX will replace this later
        List<Object> additionalVals = new ArrayList<Object>();
        if (wo instanceof OlapQuery && property.getName().equals("currentCube")) {
            additionalVals.add(((OlapQuery) wo).getOlapDataSource());
        }

        DataType type = PersisterUtils.getDataType(property.getPropertyType());
        Object basicNewValue = converterFactory.convertToBasicType(newVal, additionalVals.toArray());
        persister.begin();
        persister.persistProperty(wo.getUUID(), property.getName(), type,
                converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), basicNewValue);
        persister.commit();

        Object newValAfterSet = PropertyUtils.getSimpleProperty(wo, property.getName());
        Object basicExpectedValue = converterFactory.convertToBasicType(newValAfterSet,
                additionalVals.toArray());

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

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

/**
 * Tests the SPPersisterListener will persist a property change to its
 * target persister./* w  ww.j a v  a  2 s. c  om*/
 */
public void testSPListenerPersistsProperty() throws Exception {
    CountingSPPersister countingPersister = new CountingSPPersister();
    SPPersisterListener listener = new SPPersisterListener(countingPersister, getConverter());
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    SPObject wo = getSPObjectUnderTest();
    wo.addSPListener(listener);

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

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

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

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

        countingPersister.clearAllPropertyChanges();
        try {
            oldVal = PropertyUtils.getSimpleProperty(wo, property.getName());

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

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

        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());
        int oldChangeCount = countingPersister.getPersistPropertyCount();

        try {
            //The first property change at current is always the property change we are
            //looking for, this may need to be changed in the future to find the correct
            //property.
            PersistedSPOProperty propertyChange = null;

            try {
                logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                        + newVal.getClass().getName() + ")");
                wo.setMagicEnabled(false);
                BeanUtils.copyProperty(wo, property.getName(), newVal);

                assertTrue("Did not persist property " + property.getName(),
                        oldChangeCount < countingPersister.getPersistPropertyCount());

                for (PersistedSPOProperty nextPropertyChange : countingPersister.getPersistPropertyList()) {
                    if (nextPropertyChange.getPropertyName().equals(property.getName())) {
                        propertyChange = nextPropertyChange;
                        break;
                    }
                }
                assertNotNull("A property change event cannot be found for the property " + property.getName(),
                        propertyChange);

                assertEquals(wo.getUUID(), propertyChange.getUUID());
                assertEquals(property.getName(), propertyChange.getPropertyName());

                assertEquals(
                        "Old value of property " + property.getName() + " was wrong, value expected was  "
                                + oldVal + " but is " + countingPersister.getLastOldValue(),
                        getConverter().convertToBasicType(oldVal), propertyChange.getOldValue());

            } finally {
                wo.setMagicEnabled(true);
            }

            //Input streams from images are being compared by hash code not values
            if (Image.class.isAssignableFrom(property.getPropertyType())) {
                logger.debug(propertyChange.getNewValue().getClass());
                assertTrue(Arrays.equals(PersisterUtils.convertImageToStreamAsPNG((Image) newVal).toByteArray(),
                        PersisterUtils
                                .convertImageToStreamAsPNG((Image) getConverter()
                                        .convertToComplexType(propertyChange.getNewValue(), Image.class))
                                .toByteArray()));
            } else {
                assertEquals(getConverter().convertToBasicType(newVal), propertyChange.getNewValue());
            }
            Class<? extends Object> classType;
            if (oldVal != null) {
                classType = oldVal.getClass();
            } else {
                classType = newVal.getClass();
            }
            assertEquals(PersisterUtils.getDataType(classType), propertyChange.getDataType());
        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + wo.getClass().getName());
        }
    }
}

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

/**
 * Tests passing an object to an {@link SPPersisterListener} will persist
 * the object and all of the properties that have setters.
 *//* w w w.j  a v  a 2 s . com*/
public void testSPListenerPersistsNewObjects() throws Exception {
    CountingSPPersister persister = new CountingSPPersister();
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    SPObject objectUnderTest = getSPObjectUnderTest();

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

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

    //set all properties of the object
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        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;
        }

        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());

        try {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal);

        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + objectUnderTest.getClass().getName());
        }
    }

    //persist the object to the new target root
    new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest,
            objectUnderTest.getParent().getChildren(objectUnderTest.getClass()).indexOf(objectUnderTest));

    assertTrue(persister.getPersistPropertyCount() > 0);

    assertEquals(getSPObjectUnderTest().getUUID(), persister.getPersistObjectList().get(0).getUUID());

    //set all properties of the object
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        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;
        }

        Object newValue = null;

        boolean found = false;
        for (PersistedSPOProperty persistedSPO : persister.getPersistPropertyList()) {
            if (persistedSPO.getPropertyName().equals(property.getName())
                    && persistedSPO.getUUID().equals(getSPObjectUnderTest().getUUID())) {
                newValue = persistedSPO.getNewValue();
                found = true;
                break;
            }
        }

        assertTrue("Could not find the persist call for property " + property.getName(), found);

        if (oldVal == null) {
            assertNull(newValue);
        } else {
            assertPersistedValuesAreEqual(oldVal,
                    getConverter().convertToComplexType(newValue, oldVal.getClass()),
                    getConverter().convertToBasicType(oldVal), newValue, property.getPropertyType());
        }
    }
}