Search in sources :

Example 1 with DynaBean

use of org.apache.commons.beanutils.DynaBean in project sonarqube by SonarSource.

the class FormBeanConfig method createActionForm.

// --------------------------------------------------------- Public Methods
/**
     * <p>Create and return an <code>ActionForm</code> instance appropriate to
     * the information in this <code>FormBeanConfig</code>.</p>
     *
     * <p>Although this method is not formally deprecated yet, where possible,
     * the form which accepts an <code>ActionContext</code> as an argument is
     * preferred, to help sever direct dependencies on the Servlet API.  As
     * the ActionContext becomes more familiar in Struts, this method will
     * almost certainly be deprecated.</p>
     *
     * @param servlet The action servlet
     * @return ActionForm instance
     * @throws IllegalAccessException if the Class or the appropriate
     *                                constructor is not accessible
     * @throws InstantiationException if this Class represents an abstract
     *                                class, an array class, a primitive type,
     *                                or void; or if instantiation fails for
     *                                some other reason
     */
public ActionForm createActionForm(ActionServlet servlet) throws IllegalAccessException, InstantiationException {
    Object obj = null;
    // Create a new form bean instance
    if (getDynamic()) {
        obj = getDynaActionFormClass().newInstance();
    } else {
        obj = formBeanClass().newInstance();
    }
    ActionForm form = null;
    if (obj instanceof ActionForm) {
        form = (ActionForm) obj;
    } else {
        form = new BeanValidatorForm(obj);
    }
    form.setServlet(servlet);
    if (form instanceof DynaBean && ((DynaBean) form).getDynaClass() instanceof MutableDynaClass) {
        DynaBean dynaBean = (DynaBean) form;
        MutableDynaClass dynaClass = (MutableDynaClass) dynaBean.getDynaClass();
        // Add properties
        dynaClass.setRestricted(false);
        FormPropertyConfig[] props = findFormPropertyConfigs();
        for (int i = 0; i < props.length; i++) {
            dynaClass.add(props[i].getName(), props[i].getTypeClass());
            dynaBean.set(props[i].getName(), props[i].initial());
        }
        dynaClass.setRestricted(isRestricted());
    }
    if (form instanceof BeanValidatorForm) {
        ((BeanValidatorForm) form).initialize(this);
    }
    return form;
}
Also used : DynaBean(org.apache.commons.beanutils.DynaBean) ActionForm(org.apache.struts.action.ActionForm) DynaActionForm(org.apache.struts.action.DynaActionForm) BeanValidatorForm(org.apache.struts.validator.BeanValidatorForm) MutableDynaClass(org.apache.commons.beanutils.MutableDynaClass)

Example 2 with DynaBean

use of org.apache.commons.beanutils.DynaBean in project jaffa-framework by jaffa-projects.

the class BeanHelper method setField.

/**
 * This method will introspect the bean & get the setter method for the input propertyName.
 * It will then try & convert the propertyValue to the appropriate datatype.
 * Finally it will invoke the setter.
 * @return A true indicates, the property was succesfully set to the passed value. A false indicates the property doesn't exist or the propertyValue passed is not compatible with the setter.
 * @param bean The bean class to be introspected.
 * @param propertyName The Property being searched for.
 * @param propertyValue The value to be set.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 */
public static boolean setField(Object bean, String propertyName, Object propertyValue) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    boolean result = false;
    if (bean instanceof DynaBean) {
        try {
            PropertyUtils.setProperty(bean, propertyName, propertyValue);
            result = true;
        } catch (NoSuchMethodException ignore) {
            // If the bean is a FlexBean instance, then the field could exist on the associated persistentObject
            if (bean instanceof FlexBean && ((FlexBean) bean).getPersistentObject() != null) {
                try {
                    PropertyUtils.setProperty(((FlexBean) bean).getPersistentObject(), propertyName, propertyValue);
                    result = true;
                } catch (NoSuchMethodException ignore2) {
                }
            }
        }
    } else {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        if (beanInfo != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            if (pds != null) {
                for (PropertyDescriptor pd : pds) {
                    if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) {
                        Method m = pd.getWriteMethod();
                        Object convertedPropertyValue = null;
                        if (propertyValue != null) {
                            if (pd.getPropertyType().isEnum()) {
                                convertedPropertyValue = findEnum(pd.getPropertyType(), propertyValue.toString());
                            } else {
                                try {
                                    convertedPropertyValue = DataTypeMapper.instance().map(propertyValue, pd.getPropertyType());
                                } catch (Exception e) {
                                    // do nothing
                                    break;
                                }
                            }
                        }
                        m.invoke(bean, new Object[] { convertedPropertyValue });
                        result = true;
                        break;
                    }
                }
            }
        }
        try {
            // Finally, check the FlexBean
            if (!result && bean instanceof IFlexFields && ((IFlexFields) bean).getFlexBean() != null && ((IFlexFields) bean).getFlexBean().getDynaClass().getDynaProperty(propertyName) != null) {
                ((IFlexFields) bean).getFlexBean().set(propertyName, propertyValue);
                result = true;
            }
        } catch (Exception ignore) {
        }
    }
    return result;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) DynaBean(org.apache.commons.beanutils.DynaBean) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) IFlexFields(org.jaffa.flexfields.IFlexFields) FlexBean(org.jaffa.flexfields.FlexBean) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 3 with DynaBean

use of org.apache.commons.beanutils.DynaBean in project jaffa-framework by jaffa-projects.

the class ExcelExportService method generateExcel.

public static Workbook generateExcel(QueryServiceConfig master, QueryServiceConfig child, String sheetName) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Workbook wb = null;
    String legacyExport = (String) ContextManagerFactory.instance().getProperty("jaffa.widgets.exportToExcel.legacy");
    if (legacyExport != null && legacyExport.equals("T")) {
        wb = new HSSFWorkbook();
    } else {
        wb = new SXSSFWorkbook(100);
    }
    try {
        // Creating worksheet
        Sheet sheet = null;
        if (sheetName != null)
            sheet = wb.createSheet(sheetName);
        else
            sheet = wb.createSheet();
        // creating a custom palette for the workbook
        CellStyle style = wb.createCellStyle();
        style = wb.createCellStyle();
        // setting the foreground color to gray
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        // Setting the border for the cells
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setAlignment(CellStyle.ALIGN_CENTER);
        // setting font weight
        Font titleFont = wb.createFont();
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);
        int rowNum = 0;
        Row headerRow = sheet.createRow(rowNum);
        int colIndex = 0;
        for (Object o : master.getColumnModel()) {
            String columnTitle = (String) ((DynaBean) o).get("header");
            if (columnTitle == null || columnTitle.length() == 0)
                columnTitle = (String) ((DynaBean) o).get("mapping");
            headerRow.createCell(colIndex).setCellValue(columnTitle);
            Cell cell = headerRow.getCell(colIndex);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(colIndex);
            colIndex += 1;
        }
        // Generate the Excel output by creating a simple HTML table
        if (child != null) {
            for (Object o : child.getColumnModel()) {
                String columnTitle = (String) ((DynaBean) o).get("header");
                if (columnTitle == null || columnTitle.length() == 0)
                    columnTitle = (String) ((DynaBean) o).get("mapping");
                headerRow.createCell(colIndex).setCellValue(columnTitle);
                Cell cell = headerRow.getCell(colIndex);
                cell.setCellStyle(style);
                sheet.autoSizeColumn(colIndex);
                colIndex += 1;
            }
        }
        // Invoke the query and obtain an array of Graph objects
        Object[] queryOutput = invokeQueryService(master.getCriteriaClassName(), master.getCriteriaObject(), master.getServiceClassName(), master.getServiceClassMethodName());
        // Add the data rows
        if (queryOutput != null) {
            for (Object row : queryOutput) {
                Object[] detailQueryOutput = new Object[0];
                if (child == null) {
                    rowNum += 1;
                    Row dataRow = sheet.createRow((short) rowNum);
                    int colNum = 0;
                    // extract the columns from master object
                    for (Object o : master.getColumnModel()) {
                        String mapping = (String) ((DynaBean) o).get("mapping");
                        Object value = null;
                        if (mapping.startsWith("appFields.")) {
                            mapping = mapping.substring(10);
                            try {
                                Object[] appFields = (Object[]) PropertyUtils.getProperty(row, "applicationFields");
                                for (Object field : appFields) {
                                    String name = (String) PropertyUtils.getProperty(field, "name");
                                    if (name.equals(mapping)) {
                                        value = (String) PropertyUtils.getProperty(field, "value");
                                    }
                                }
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Property not found: " + mapping, e);
                            }
                        } else {
                            try {
                                value = PropertyUtils.getProperty(row, mapping);
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Property not found: " + mapping, e);
                            }
                        }
                        dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                        colNum += 1;
                    }
                } else {
                    // child is not null
                    // load the child rows
                    String detailCriteriaObject = child.getCriteriaObject();
                    for (int i = 0; i < child.getMasterKeyFieldNames().length; i++) {
                        String kfn = child.getMasterKeyFieldNames()[i];
                        try {
                            String keyValue = (String) PropertyUtils.getProperty(row, kfn);
                            detailCriteriaObject = detailCriteriaObject.replace("{" + i + "}", keyValue);
                        } catch (Exception e) {
                            if (log.isDebugEnabled())
                                log.debug("Key property not found: " + kfn, e);
                        }
                    }
                    detailQueryOutput = invokeQueryService(child.getCriteriaClassName(), detailCriteriaObject, child.getServiceClassName(), "query");
                    // add the child columns
                    if (detailQueryOutput != null && detailQueryOutput.length > 0) {
                        for (Object detailRow : detailQueryOutput) {
                            rowNum += 1;
                            Row dataRow = sheet.createRow((short) rowNum);
                            int colNum = 0;
                            // extract the columns from master object
                            for (Object obj : master.getColumnModel()) {
                                String masterMapping = (String) ((DynaBean) obj).get("mapping");
                                Object masterValue = null;
                                try {
                                    masterValue = PropertyUtils.getProperty(row, masterMapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found: " + masterMapping, e);
                                }
                                dataRow.createCell(colNum).setCellValue(format(masterValue, (DynaBean) obj));
                                colNum += 1;
                            }
                            for (Object o : child.getColumnModel()) {
                                String mapping = (String) ((DynaBean) o).get("mapping");
                                Object value = null;
                                try {
                                    value = PropertyUtils.getProperty(detailRow, mapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found in child result: " + mapping, e);
                                }
                                dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                                colNum += 1;
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return wb;
}
Also used : SXSSFWorkbook(org.apache.poi.xssf.streaming.SXSSFWorkbook) Workbook(org.apache.poi.ss.usermodel.Workbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) Font(org.apache.poi.ss.usermodel.Font) InvocationTargetException(java.lang.reflect.InvocationTargetException) DynaBean(org.apache.commons.beanutils.DynaBean) SXSSFWorkbook(org.apache.poi.xssf.streaming.SXSSFWorkbook) JSONObject(net.sf.json.JSONObject) CellStyle(org.apache.poi.ss.usermodel.CellStyle) Row(org.apache.poi.ss.usermodel.Row) Sheet(org.apache.poi.ss.usermodel.Sheet) Cell(org.apache.poi.ss.usermodel.Cell)

Example 4 with DynaBean

use of org.apache.commons.beanutils.DynaBean in project sonar-java by SonarSource.

the class FormBeanConfig method canReuse.

/**
 * <p>Checks if the given <code>ActionForm</code> instance is suitable for
 * use as an alternative to calling this <code>FormBeanConfig</code>
 * instance's <code>createActionForm</code> method.</p>
 *
 * @param form an existing form instance that may be reused.
 * @return true if the given form can be reused as the form for this
 *         config.
 */
public boolean canReuse(ActionForm form) {
    if (form != null) {
        if (this.getDynamic()) {
            String className = ((DynaBean) form).getDynaClass().getName();
            if (className.equals(this.getName())) {
                log.debug("Can reuse existing instance (dynamic)");
                return (true);
            }
        } else {
            try {
                // check if the form's class is compatible with the class
                // we're configured for
                Class formClass = form.getClass();
                if (form instanceof BeanValidatorForm) {
                    BeanValidatorForm beanValidatorForm = (BeanValidatorForm) form;
                    if (beanValidatorForm.getInstance() instanceof DynaBean) {
                        String formName = beanValidatorForm.getStrutsConfigFormName();
                        if (getName().equals(formName)) {
                            log.debug("Can reuse existing instance (BeanValidatorForm)");
                            return true;
                        } else {
                            return false;
                        }
                    }
                    formClass = beanValidatorForm.getInstance().getClass();
                }
                Class configClass = ClassUtils.getApplicationClass(this.getType());
                if (configClass.isAssignableFrom(formClass)) {
                    log.debug("Can reuse existing instance (non-dynamic)");
                    return (true);
                }
            } catch (Exception e) {
                log.debug("Error testing existing instance for reusability; just create a new instance", e);
            }
        }
    }
    return false;
}
Also used : DynaBean(org.apache.commons.beanutils.DynaBean) DynaActionFormClass(org.apache.struts.action.DynaActionFormClass) MutableDynaClass(org.apache.commons.beanutils.MutableDynaClass) BeanValidatorForm(org.apache.struts.validator.BeanValidatorForm) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 5 with DynaBean

use of org.apache.commons.beanutils.DynaBean in project nimbus by nimbus-org.

the class DynaBeanMapJournalEditorService method toMap.

/**
 * ジャーナルとして与えられたDynaBean型の情報をジャーナルとして出力するMap情報に変換する。<br>
 *
 * @param finder 適切なJournalEditorを提供するEditorFinder
 * @param key ジャーナルのキー情報
 * @param value ジャーナル情報
 * @return ジャーナルとして出力するMap情報
 */
public Map toMap(EditorFinder finder, Object key, Object value) {
    final DynaBean bean = (DynaBean) value;
    final Map result = new HashMap();
    if (isOutputDynaClass()) {
        makeDynaClassFormat(finder, key, bean, result);
    }
    if (isOutputProperties()) {
        makePropertiesFormat(finder, key, bean, result);
    }
    return result;
}
Also used : DynaBean(org.apache.commons.beanutils.DynaBean)

Aggregations

DynaBean (org.apache.commons.beanutils.DynaBean)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)5 MutableDynaClass (org.apache.commons.beanutils.MutableDynaClass)4 BeanValidatorForm (org.apache.struts.validator.BeanValidatorForm)4 JSONObject (net.sf.json.JSONObject)2 HSSFWorkbook (org.apache.poi.hssf.usermodel.HSSFWorkbook)2 Cell (org.apache.poi.ss.usermodel.Cell)2 CellStyle (org.apache.poi.ss.usermodel.CellStyle)2 Font (org.apache.poi.ss.usermodel.Font)2 Row (org.apache.poi.ss.usermodel.Row)2 Sheet (org.apache.poi.ss.usermodel.Sheet)2 Workbook (org.apache.poi.ss.usermodel.Workbook)2 SXSSFWorkbook (org.apache.poi.xssf.streaming.SXSSFWorkbook)2 ActionForm (org.apache.struts.action.ActionForm)2 DynaActionForm (org.apache.struts.action.DynaActionForm)2 DynaActionFormClass (org.apache.struts.action.DynaActionFormClass)2 BeanInfo (java.beans.BeanInfo)1 IntrospectionException (java.beans.IntrospectionException)1 PropertyDescriptor (java.beans.PropertyDescriptor)1 Method (java.lang.reflect.Method)1