Example usage for java.lang IllegalAccessException IllegalAccessException

List of usage examples for java.lang IllegalAccessException IllegalAccessException

Introduction

In this page you can find the example usage for java.lang IllegalAccessException IllegalAccessException.

Prototype

public IllegalAccessException(String s) 

Source Link

Document

Constructs an IllegalAccessException with a detail message.

Usage

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.MapFieldPersistenceProvider.java

protected Class<?> getStartingValueType(PopulateValueRequest populateValueRequest)
        throws ClassNotFoundException, IllegalAccessException {
    Class<?> startingValueType = null;
    String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass();
    if (valueClassName != null) {
        startingValueType = Class.forName(valueClassName);
    }//from w w w  .j a v  a2  s .  c om
    if (startingValueType == null) {
        startingValueType = populateValueRequest.getReturnType();
    }
    if (startingValueType == null) {
        throw new IllegalAccessException("Unable to determine the valueType for the rule field ("
                + populateValueRequest.getProperty().getName() + ")");
    }
    return startingValueType;
}

From source file:org.sparkcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity,
        Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties)
        throws ValidationException {
    Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider
                .filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;/*from w ww  .  j  a  va2 s .c  o  m*/
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity),
                unfilteredProperties);
    }
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager()
            .unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        for (Property property : entity.getProperties()) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR)
                    && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName()
                            + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: "
                            + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicSparkType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException(
                        "Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();

                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }

                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property,
                                metadata, returnType, value, persistenceManager, this);

                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(),
                                        validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }

                        if (attemptToPopulate) {
                            for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                FieldProviderResponse response = fieldPersistenceProvider.populateValue(request,
                                        instance);
                                if (FieldProviderResponse.NOT_HANDLED != response) {
                                    handled = true;
                                }
                                if (FieldProviderResponse.HANDLED_BREAK == response) {
                                    break;
                                }
                            }
                            if (!handled) {
                                defaultFieldPersistenceProvider
                                        .populateValue(
                                                new PopulateValueRequest(setId, fieldManager, property,
                                                        metadata, returnType, value, persistenceManager, this),
                                                instance);
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null
                                    && (metadata.getFieldType() != SupportedFieldType.ID || setId)
                                    && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }

            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, List<String>> entry : invalid.getPropertyValidationErrors().entrySet()) {
                Iterator<String> itr = entry.getValue().iterator();
                while (itr.hasNext()) {
                    sb.append(entry.getKey());
                    sb.append(" : ");
                    sb.append(itr.next());
                    if (itr.hasNext()) {
                        sb.append(" / ");
                    }
                }
            }

            throw new ValidationException(invalid, "The entity has failed validation - " + sb.toString());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}

From source file:org.kawanfw.sql.servlet.DatabaseMetaDataExecutor.java

/**
 * /*  w  ww .j a  v  a2  s.c o  m*/
 * Calls a remote metadata method from the PC <br>
 * 
 * @throws IOException
 *             all network, etc. errors
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException
 */
private void callMetaDataFunction(HttpServletRequest request, OutputStream out, Connection connection)
        throws SQLException, IOException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException

{

    // The method name
    String methodName = request.getParameter(Parameter.METHOD_NAME);
    // methodName = HtmlConverter.fromHtml(methodName);

    // The parms name
    String paramsTypes = request.getParameter(Parameter.PARAMS_TYPES);
    String paramsValues = request.getParameter(Parameter.PARAMS_VALUES);

    // Make sure all values are not null and trimed

    methodName = this.getTrimValue(methodName);
    paramsTypes = this.getTrimValue(paramsTypes);
    paramsValues = this.getTrimValue(paramsValues);

    debug("actionInvokeRemoteMethod:methodName       : " + methodName);

    // paramsTypes = HtmlConverter.fromHtml(paramsTypes);
    // paramsValues = HtmlConverter.fromHtml(paramsValues);

    List<String> listParamsTypes = ListOfStringTransport.fromJson(paramsTypes);
    List<String> listParamsValues = ListOfStringTransport.fromJson(paramsValues);

    debug("actionInvokeRemoteMethod:listParamsTypes      : " + listParamsTypes);
    debug("actionInvokeRemoteMethod:listParamsValues     : " + listParamsValues);

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    // Trap DatabaseMetaData.getTables() & DatabaseMetaData.getUDTs()
    // that have special array String[] or int[] parameters
    if (methodName.equals("getTables") || methodName.equals("getUDTs") || methodName.equals("getPrimaryKeys")) {
        DatabaseMetaDataSpecial databaseMetaDataSpecial = new DatabaseMetaDataSpecial(databaseMetaData,
                methodName, listParamsValues);
        ResultSet rs = databaseMetaDataSpecial.execute();
        dumpResultSetOnServletOutStream(rs);
        return;
    }

    @SuppressWarnings("rawtypes")
    Class[] argTypes = new Class[listParamsTypes.size()];
    Object[] values = new Object[listParamsValues.size()];

    for (int i = 0; i < listParamsTypes.size(); i++) {
        String value = listParamsValues.get(i);

        String javaType = listParamsTypes.get(i);
        JavaValueBuilder javaValueBuilder = new JavaValueBuilder(javaType, value);

        argTypes[i] = javaValueBuilder.getClassOfValue();
        values[i] = javaValueBuilder.getValue();

        // Trap NULL values
        if (values[i].equals("NULL")) {
            values[i] = null;
        }

        debug("argTypes[i]: " + argTypes[i]);
        debug("values[i]  : " + values[i]);
    }

    Class<?> c = Class.forName("java.sql.DatabaseMetaData");
    Object theObject = databaseMetaData;

    // Invoke the method
    Method main = null;
    Object resultObj = null;

    // Get the Drvier Info
    String database = "";
    String productVersion = "";
    String DriverName = "";
    String DriverVersion = "";
    String driverInfo = Tag.PRODUCT;

    // try {
    // database = databaseMetaData.getDatabaseProductName();
    // productVersion = databaseMetaData.getDatabaseProductVersion();
    // DriverName = databaseMetaData.getDriverName();
    // DriverVersion= databaseMetaData.getDriverVersion();
    // driverInfo += database + " " + productVersion + " " + DriverName +
    // " " + DriverVersion;
    // } catch (Exception e1) {
    // ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT +
    // "Impossible to get User Driver info.");
    // }

    database = databaseMetaData.getDatabaseProductName();
    productVersion = databaseMetaData.getDatabaseProductVersion();
    DriverName = databaseMetaData.getDriverName();
    DriverVersion = databaseMetaData.getDriverVersion();
    driverInfo += database + " " + productVersion + " " + DriverName + " " + DriverVersion;

    String methodParams = getMethodParams(values);

    try {
        main = c.getDeclaredMethod(methodName, argTypes);
    } catch (SecurityException e) {
        throw new SecurityException(driverInfo + " - Security - Impossible to get declared DatabaseMetaData."
                + methodName + "(" + methodParams + ")");
    } catch (NoSuchMethodException e) {
        throw new NoSuchMethodException(
                driverInfo + " - No Such Method - Impossible get declared DatabaseMetaData." + methodName + "("
                        + methodParams + ")");
    }

    try {
        resultObj = main.invoke(theObject, values);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                driverInfo + " - Impossible to call DatabaseMetaData." + methodName + "(" + methodParams + ")");
    } catch (IllegalAccessException e) {
        throw new IllegalAccessException(driverInfo + " - Impossible to access DatabaseMetaData method."
                + methodName + "(" + methodParams + ")");
    } catch (InvocationTargetException e) {
        throw new InvocationTargetException(e, driverInfo + " - Impossible to invoke DatabaseMetaData method."
                + methodName + "(" + methodParams + ")");
    }

    if (resultObj instanceof ResultSet) {
        ResultSet rs = (ResultSet) resultObj;
        dumpResultSetOnServletOutStream(rs);

    } else {
        // All other formats are handled in String
        String result = null;
        if (resultObj != null)
            result = resultObj.toString();
        debug("actionInvokeRemoteMethod:result: " + result);
        result = HtmlConverter.toHtml(result);

        //out.println(TransferStatus.SEND_OK);
        //out.println(result);
        ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
        ServerSqlManager.writeLine(out, result);
    }

}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.MediaFieldPersistenceProvider.java

protected Class<?> getStartingValueType(PopulateValueRequest populateValueRequest)
        throws ClassNotFoundException, IllegalAccessException {
    Class<?> startingValueType = null;
    if (!populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR)) {
        startingValueType = populateValueRequest.getReturnType();
    } else {//  w ww . j  a va2s.  com
        String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass();
        if (valueClassName != null) {
            startingValueType = Class.forName(valueClassName);
        }
        if (startingValueType == null) {
            startingValueType = populateValueRequest.getReturnType();
        }
    }
    if (startingValueType == null) {
        throw new IllegalAccessException("Unable to determine the valueType for the rule field ("
                + populateValueRequest.getProperty().getName() + ")");
    } else if (Media.class.equals(startingValueType)) {
        startingValueType = MediaImpl.class;
    }
    return startingValueType;
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity,
        Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties)
        throws ValidationException {
    final Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider
                .filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;//  www.ja va  2s . c om
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity),
                unfilteredProperties);
    }
    //Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values
    Property[] sortedProperties = entity.getProperties();
    Arrays.sort(sortedProperties, new Comparator<Property>() {
        @Override
        public int compare(Property o1, Property o2) {
            BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName());
            BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName());
            boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null
                    && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType()
                            || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType()
                            || SupportedFieldType.MEDIA == mo1.getFieldType()
                            || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null
                    && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType()
                            || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType()
                            || SupportedFieldType.MEDIA == mo2.getFieldType()
                            || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            if (isLate1 && !isLate2) {
                return 1;
            } else if (!isLate1 && isLate2) {
                return -1;
            }
            return 0;
        }
    });
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager()
            .unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        RuntimeException entityPersistenceException = null;
        for (Property property : sortedProperties) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR)
                    && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName()
                            + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: "
                            + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicBroadleafType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException(
                        "Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();

                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }

                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property,
                                metadata, returnType, value, persistenceManager, this);

                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(),
                                        validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }

                        if (attemptToPopulate) {
                            try {
                                boolean isBreakDetected = false;
                                for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                    if (!isBreakDetected || fieldPersistenceProvider.alwaysRun()) {
                                        FieldProviderResponse response = fieldPersistenceProvider
                                                .populateValue(request, instance);
                                        if (FieldProviderResponse.NOT_HANDLED != response) {
                                            handled = true;
                                        }
                                        if (FieldProviderResponse.HANDLED_BREAK == response) {
                                            isBreakDetected = true;
                                        }
                                    }
                                }
                                if (!handled) {
                                    defaultFieldPersistenceProvider.populateValue(
                                            new PopulateValueRequest(setId, fieldManager, property, metadata,
                                                    returnType, value, persistenceManager, this),
                                            instance);
                                }
                            } catch (ParentEntityPersistenceException
                                    | javax.validation.ValidationException e) {
                                entityPersistenceException = e;
                                cleanupFailedPersistenceAttempt(instance);
                                break;
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null
                                    && (metadata.getFieldType() != SupportedFieldType.ID || setId)
                                    && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }

            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, List<String>> entry : invalid.getPropertyValidationErrors().entrySet()) {
                Iterator<String> itr = entry.getValue().iterator();
                while (itr.hasNext()) {
                    sb.append(entry.getKey());
                    sb.append(" : ");
                    sb.append(itr.next());
                    if (itr.hasNext()) {
                        sb.append(" / ");
                    }
                }
            }

            throw new ValidationException(invalid, "The entity has failed validation - " + sb.toString());
        } else if (entityPersistenceException != null) {
            throw ExceptionHelper.refineException(entityPersistenceException.getCause());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}

From source file:io.apiman.manager.api.es.EsMarshallingTest.java

/**
 * Fabricates a new instance of the given bean type.  Uses reflection to figure
 * out all the fields and assign generated values for each.
 *///  ww w .  ja  v a 2s  . c  o m
private static <T> T createBean(Class<T> beanClass) throws InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
    T bean = beanClass.newInstance();
    Map<String, String> beanProps = BeanUtils.describe(bean);
    for (String key : beanProps.keySet()) {
        try {
            Field declaredField = beanClass.getDeclaredField(key);
            Class<?> fieldType = declaredField.getType();
            if (fieldType == String.class) {
                BeanUtils.setProperty(bean, key, StringUtils.upperCase(key));
            } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                BeanUtils.setProperty(bean, key, Boolean.TRUE);
            } else if (fieldType == Date.class) {
                BeanUtils.setProperty(bean, key, new Date(1));
            } else if (fieldType == Long.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 17L);
            } else if (fieldType == Integer.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 11);
            } else if (fieldType == Set.class) {
                // Initialize to a linked hash set so that order is maintained.
                BeanUtils.setProperty(bean, key, new LinkedHashSet());

                Type genericType = declaredField.getGenericType();
                String typeName = genericType.getTypeName();
                String typeClassName = typeName.substring(14, typeName.length() - 1);
                Class<?> typeClass = Class.forName(typeClassName);
                Set collection = (Set) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(bean, key);
                populateSet(collection, typeClass);
            } else if (fieldType == Map.class) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                map.put("KEY-1", "VALUE-1");
                map.put("KEY-2", "VALUE-2");
                BeanUtils.setProperty(bean, key, map);
            } else if (fieldType.isEnum()) {
                BeanUtils.setProperty(bean, key, fieldType.getEnumConstants()[0]);
            } else if (fieldType.getPackage() != null
                    && fieldType.getPackage().getName().startsWith("io.apiman.manager.api.beans")) {
                Object childBean = createBean(fieldType);
                BeanUtils.setProperty(bean, key, childBean);
            } else {
                throw new IllegalAccessException(
                        "Failed to handle property named [" + key + "] type: " + fieldType.getSimpleName());
            }
            //            String capKey = StringUtils.capitalize(key);
            //            System.out.println(key);;
        } catch (NoSuchFieldException e) {
            // Skip it - there is not really a bean property with this name!
        }
    }
    return bean;
}

From source file:io.apiman.manager.api.es.EsMarshallingTest.java

/**
 * Populate the given set with one or two items of the given type.
 * @param collection/*  w w  w . j av  a 2 s.c  om*/
 * @param typeClass
 */
private static void populateSet(Set collection, Class<?> typeClass)
        throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
        SecurityException, ClassNotFoundException {
    if (typeClass.isEnum()) {
        collection.add(typeClass.getEnumConstants()[0]);
        collection.add(typeClass.getEnumConstants()[1]);
    } else if (typeClass == String.class) {
        collection.add("VALUE_1");
        collection.add("VALUE_2");
    } else if (typeClass.getPackage().getName().startsWith("io.apiman.manager.api.beans")) {
        Object bean1 = createBean(typeClass);
        Object bean2 = createBean(typeClass);
        collection.add(bean1);
        collection.add(bean2);
    } else {
        throw new IllegalAccessException("Failed to populate Set of type: " + typeClass.getSimpleName());
    }
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.RuleFieldPersistenceProvider.java

protected boolean populateQuantityRule(PopulateValueRequest populateValueRequest, Serializable instance)
        throws FieldNotAvailableException, IllegalAccessException {
    String prop = populateValueRequest.getProperty().getName();
    Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop);
    OneToMany oneToMany = field.getAnnotation(OneToMany.class);
    if (oneToMany == null) {
        throw new UnsupportedOperationException(
                "RuleFieldPersistenceProvider is currently only compatible with collection fields when modelled using @OneToMany");
    }//from w w  w.  j a  v  a  2  s  .  c  om
    boolean dirty;//currently, this only works with Collection fields
    Class<?> valueType = getListFieldType(instance, populateValueRequest.getFieldManager(),
            populateValueRequest.getProperty(), populateValueRequest.getPersistenceManager());
    if (valueType == null) {
        throw new IllegalAccessException("Unable to determine the valueType for the rule field ("
                + populateValueRequest.getProperty().getName() + ")");
    }
    DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
    Collection<QuantityBasedRule> rules;
    rules = (Collection<QuantityBasedRule>) populateValueRequest.getFieldManager().getFieldValue(instance,
            populateValueRequest.getProperty().getName());
    Object parent = extractParent(populateValueRequest, instance);
    //AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version
    dirty = updateQuantityRule(
            populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager(),
            translator,
            RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()),
            populateValueRequest.getMetadata().getRuleIdentifier(),
            populateValueRequest.getProperty().getUnHtmlEncodedValue(), rules, valueType, parent,
            oneToMany.mappedBy(), populateValueRequest.getProperty());
    return dirty;
}

From source file:org.cloudgraph.cassandra.service.GraphDispatcher.java

private void update(DataGraph dataGraph, PlasmaDataObject dataObject)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    PlasmaType type = (PlasmaType) dataObject.getType();
    if (log.isDebugEnabled())
        log.debug(// w w  w.  j  ava2s . co m
                "updating " + type.getName() + " '" + ((PlasmaDataObject) dataObject).getUUIDAsString() + "'");

    List<Property> pkList = type.findProperties(KeyType.primary);
    if (pkList == null || pkList.size() == 0)
        throw new DataAccessException(
                "no pri-key properties found for type '" + dataObject.getType().getName() + "'");

    List<PropertyPair> pkPairs = new ArrayList<PropertyPair>();
    for (Property pkp : pkList) {
        PlasmaProperty pkProperty = (PlasmaProperty) pkp;
        Object pk = dataObject.get(pkProperty);
        if (pk == null)
            throw new DataAccessException("found null primary key property '" + pkProperty.getName()
                    + "' for type, " + type.getURI() + "#" + type.getName());
        Setting setting = dataGraph.getChangeSummary().getOldValue(dataObject, pkProperty);
        if (setting != null) { // it's been modified 
            // pk has been modified, yet we need it to lookup record, use the old value
            if (!pkProperty.isReadOnly()) {
                Object oldPk = setting.getValue();
                PropertyPair pair = this.createValue(dataObject, pk, oldPk, pkProperty);
                pkPairs.add(pair);
            } else
                throw new IllegalAccessException("attempt to modify read-only property, " + type.getURI() + "#"
                        + type.getName() + "." + pkProperty.getName());
        } else {
            PropertyPair pair = this.createValue(dataObject, pk, pkProperty);
            pkPairs.add(pair);
        }
    }

    // FIXME: get rid of cast - define instance properties in 'base type'
    Timestamp snapshotDate = (Timestamp) ((CoreDataObject) dataObject)
            .getValue(CoreConstants.PROPERTY_NAME_SNAPSHOT_TIMESTAMP);
    if (snapshotDate == null)
        throw new RequiredPropertyException(
                "instance property '" + CoreConstants.PROPERTY_NAME_SNAPSHOT_TIMESTAMP
                        + "' is required to update entity '" + type.getURI() + "#" + type.getName() + "'");
    else if (log.isDebugEnabled())
        log.debug("snapshot date: " + String.valueOf(snapshotDate));
    PlasmaProperty lockingUserProperty = (PlasmaProperty) type.findProperty(ConcurrencyType.pessimistic,
            ConcurrentDataFlavor.user);
    if (lockingUserProperty == null)
        if (log.isDebugEnabled())
            log.debug("could not find locking user property for type, " + type.getURI() + "#" + type.getName());

    PlasmaProperty lockingTimestampProperty = (PlasmaProperty) type.findProperty(ConcurrencyType.pessimistic,
            ConcurrentDataFlavor.time);
    if (lockingTimestampProperty == null)
        if (log.isDebugEnabled())
            log.debug("could not find locking timestamp property for type, " + type.getURI() + "#"
                    + type.getName());

    PlasmaProperty concurrencyUserProperty = (PlasmaProperty) type.findProperty(ConcurrencyType.optimistic,
            ConcurrentDataFlavor.user);
    if (concurrencyUserProperty == null)
        if (log.isDebugEnabled())
            log.debug("could not find optimistic concurrency (username) property for type, " + type.getURI()
                    + "#" + type.getName());

    PlasmaProperty concurrencyTimestampProperty = (PlasmaProperty) type.findProperty(ConcurrencyType.optimistic,
            ConcurrentDataFlavor.time);
    if (concurrencyTimestampProperty == null)
        if (log.isDebugEnabled())
            log.debug("could not find optimistic concurrency timestamp property for type, " + type.getURI()
                    + "#" + type.getName());

    List<Object> params = new ArrayList<Object>();
    StringBuilder select = this.statementFactory.createSelectConcurrent(type, pkPairs, 5, params);
    Map<String, PropertyPair> entity = this.statementExecutor.fetchRowMap(type, select);
    if (entity.size() == 0)
        throw new GraphServiceException("could not lock record of type, " + type.toString());

    //overwrite with original PK pairs as these may contain old/new value info
    for (PropertyPair pair : pkPairs)
        entity.put(pair.getProp().getName(), pair);

    if (concurrencyTimestampProperty != null && concurrencyUserProperty != null)
        checkAndRefreshConcurrencyFields(type, entity, concurrencyTimestampProperty, concurrencyUserProperty,
                snapshotDate);

    if (CoreHelper.isFlaggedLocked(dataObject))
        lock(dataObject, entity, lockingTimestampProperty, lockingUserProperty, snapshotDate);
    else if (CoreHelper.isFlaggedUnlocked(dataObject))
        unlock(dataObject, entity, lockingTimestampProperty, lockingUserProperty, snapshotDate);

    List<Property> properties = type.getProperties();
    for (Property p : properties) {
        PlasmaProperty property = (PlasmaProperty) p;
        if (property.isMany())
            continue; // do/could we invoke a "marshaler" here?
        if (property.isKey(KeyType.primary))
            continue; // handled above

        if (property.getConcurrent() != null)
            continue;

        Object oldValue = dataGraph.getChangeSummary().getOldValue(dataObject, property);
        if (oldValue != null) { // it's been modified  
            if (!property.isReadOnly()) {
                Object value = dataObject.get(property);
                if (value != null) {
                    PropertyPair pair = createValue(dataObject, value, property);
                    entity.put(property.getName(), pair);
                }
                //setEntityValue(entity, value, property);
            } else
                throw new IllegalAccessException("attempt to modify read-only property, " + type.getURI() + "#"
                        + type.getName() + "." + property.getName());
        }
    }

    if (this.statementFactory.hasUpdatableProperties(entity)) {
        StringBuilder update = this.statementFactory.createUpdate(type, entity);
        if (log.isDebugEnabled()) {
            log.debug("updating " + dataObject.getType().getName());
        }
        this.statementExecutor.execute(type, update, entity);
    }
}