Example usage for java.beans PropertyChangeEvent PropertyChangeEvent

List of usage examples for java.beans PropertyChangeEvent PropertyChangeEvent

Introduction

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

Prototype

public PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue) 

Source Link

Document

Constructs a new PropertyChangeEvent .

Usage

From source file:org.kuali.kfs.module.tem.document.TravelDocumentBase.java

/**
 * @see org.kuali.kfs.module.tem.document.TravelDocument#addExpenseDetail(org.kuali.kfs.module.tem.businessobject.TemExpense, java.lang.Integer)
 *///from w ww . j a  va 2s  .com
@Override
@Transient
public void addExpenseDetail(TemExpense line, Integer index) {
    final String sequenceName = line.getSequenceName();
    final Long sequenceNumber = getSequenceAccessorService().getNextAvailableSequenceNumber(sequenceName,
            ImportedExpense.class);
    line.setId(sequenceNumber);
    line.setDocumentNumber(this.documentNumber);
    notifyChangeListeners(new PropertyChangeEvent(this, TemPropertyConstants.IMPORTED_EXPENSES, null, line));

    if (line instanceof ActualExpense) {
        getTravelExpenseService().updateTaxabilityOfActualExpense((ActualExpense) line, this,
                GlobalVariables.getUserSession().getPerson()); // when adding the expense detail, attempt to update the taxability if user can't edit taxability
        getActualExpenses().get(index).addExpenseDetails(line);
        if (!ObjectUtils.isNull(getTraveler()) && !StringUtils.isBlank(getTraveler().getTravelerTypeCode())
                && !StringUtils.isBlank(getTripTypeCode())) {
            getActualExpenses().get(index).refreshExpenseTypeObjectCode(getDocumentTypeName(),
                    getTraveler().getTravelerTypeCode(), getTripTypeCode());
        }
        notifyChangeListeners(new PropertyChangeEvent(this, TemPropertyConstants.ACTUAL_EXPENSES, null, line));
    } else {
        getImportedExpenses().get(index).addExpenseDetails(line);
        if (!ObjectUtils.isNull(getTraveler()) && !StringUtils.isBlank(getTraveler().getTravelerTypeCode())
                && !StringUtils.isBlank(getTripTypeCode())) {
            getImportedExpenses().get(index).refreshExpenseTypeObjectCode(getDocumentTypeName(),
                    getTraveler().getTravelerTypeCode(), getTripTypeCode());
        }
        notifyChangeListeners(
                new PropertyChangeEvent(this, TemPropertyConstants.IMPORTED_EXPENSES, null, line));
    }
}

From source file:edu.ku.brc.specify.ui.db.ResultSetTableModel.java

@Override
public void exectionDone(final CustomQueryIFace customQuery) {
    if (statusBar != null) {
        statusBar.incrementValue(getClass().getSimpleName());
    }//w w w.  j  av a  2 s .co m

    results.queryTaskDone(customQuery);
    List<?> list = customQuery.getDataObjects();

    List<ERTICaptionInfo> captions = results.getVisibleCaptionInfo();

    //log.debug("Results size: "+list.size());

    if (ids == null) {
        ids = new Vector<Integer>();
    } else {
        ids.clear();
    }

    if (!customQuery.isInError() && !customQuery.isCancelled() && list != null && list.size() > 0) {
        /*if (numColumns == 1)
        {
        for (Object rowObj : list)
        {
            Vector<Object> row = new Vector<Object>(list.size());
            row.add(rowObj);
            cache.add(row);
        }
                
        } else*/
        {

            int maxTableRows = results.getMaxTableRows();
            int rowNum = 0;
            for (Object rowObj : list) {
                if (rowNum == maxTableRows) {
                    break;
                }
                if (customQuery.isCancelled()) {
                    break;
                }
                //Vector<Object> row = new Vector<Object>(list.size()); //list.size()?????
                Vector<Object> row = new Vector<Object>(
                        rowObj.getClass().isArray() ? ((Object[]) rowObj).length : 1);
                if (rowObj != null && rowObj.getClass().isArray()) {
                    Object[] rowCols = (Object[]) rowObj;
                    int capInx = 0;
                    for (int col = 0; col < rowCols.length; col++) {
                        Object colObj = rowCols[col];
                        ERTICaptionInfo capInfo = captions.get(capInx);

                        if (col == 0) {
                            if (colObj instanceof Integer) {
                                ids.add((Integer) colObj);
                                if (doDebug)
                                    log.debug("*** 1 Adding id[" + colObj + "]");
                            } else {
                                //log.error("First Column must be Integer id! ["+colObj+"]");
                                row.add(capInfo.processValue(colObj));
                                capInx++;
                            }

                        } else if (capInfo.getColName() == null && capInfo.getColInfoList().size() > 0) {
                            int len = capInfo.getColInfoList().size();
                            Object[] val = new Object[len];
                            for (int i = 0; i < capInfo.getColInfoList().size(); i++) {
                                val[i] = capInfo.processValue(rowCols[col + i]);
                            }
                            row.add(capInfo.getUiFieldFormatter().formatToUI(val));
                            col += capInfo.getColInfoList().size() - 1;
                            capInx++;

                        } else {
                            Object obj = capInfo.processValue(colObj);
                            row.add(obj);
                            if (doDebug)
                                log.debug("*** 2 Adding id[" + obj + "]");
                            capInx++;
                        }

                    } // for
                } else {
                    row.add(rowObj);
                }
                cache.add(row);
                rowNum++;
            }
        }

        results.cacheFilled(cache);

        fireTableDataChanged();
    }

    if (propertyListener != null) {
        propertyListener
                .propertyChange(new PropertyChangeEvent(this, "rowCount", null, new Integer(cache.size())));
    }

    if (parentERTP != null) {
        CommandAction cmdAction = new CommandAction(ExpressSearchTask.EXPRESSSEARCH, "SearchComplete",
                customQuery);
        cmdAction.setProperty("QueryForIdResultsIFace", results);
        cmdAction.setProperty("ESResultsTablePanelIFace", parentERTP);
        CommandDispatcher.dispatch(cmdAction);
    }
}

From source file:edu.ku.brc.af.core.db.MySQLBackupService.java

public boolean doRestoreBulkDataInBackground(final String databaseName, final String options,
        final String restoreZipFilePath, final SimpleGlassPane glassPane, final String completionMsgKey,
        final PropertyChangeListener pcl, final boolean doSynchronously, final boolean doDropDatabase) {
    getNumberofTables();//from   w  w w  .java  2 s . co  m

    SynchronousWorker backupWorker = new SynchronousWorker() {
        long dspMegs = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            boolean skipTrackExceptions = BasicSQLUtils.isSkipTrackExceptions();
            BasicSQLUtils.setSkipTrackExceptions(false);
            try {
                String userName = itUsername != null ? itUsername : DBConnection.getInstance().getUserName();
                String password = itPassword != null ? itPassword : DBConnection.getInstance().getPassword();

                DBConnection currDBConn = DBConnection.getInstance();
                String dbName = currDBConn.getDatabaseName();
                DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
                if (dbMgr != null) {
                    boolean isConnected = dbMgr.connectToDBMS(userName, password, currDBConn.getServerName(),
                            dbName, currDBConn.isEmbedded());
                    if (isConnected) {
                        if (doDropDatabase) {
                            if (dbMgr.doesDBExists(databaseName) && !dbMgr.dropDatabase(databaseName)) {
                                log.error("Database[" + databaseName + "] could not be dropped before load.");
                                UIRegistry.showLocalizedError("MySQLBackupService.ERR_DRP_DB", databaseName);
                                return null;
                            }

                            if (!dbMgr.createDatabase(databaseName)) {
                                log.error("Database[" + databaseName + "] could not be created before load.");
                                UIRegistry.showLocalizedError("MySQLBackupService.CRE_DRP_DB", databaseName);
                                return null;
                            }
                        }

                        DatabaseDriverInfo driverInfo = DatabaseDriverInfo
                                .getDriver(DBConnection.getInstance().getDriverName());
                        String connStr = DBConnection.getInstance().getConnectionStr();

                        DBConnection itDBConn = DBConnection.createInstance(driverInfo.getDriverClassName(),
                                driverInfo.getDialectClassName(), databaseName, connStr, userName, password);
                        Connection connection = itDBConn.createConnection();
                        connection.setCatalog(databaseName);

                        List<File> unzippedFiles = ZipFileHelper.getInstance()
                                .unzipToFiles(new File(restoreZipFilePath));

                        boolean dbCreated = false;
                        for (File file : unzippedFiles) {
                            //System.out.println(file.getName());
                            if (file.getName().equals("createdb.sql")) {
                                long size = restoreFile(connection, file);
                                log.debug("size: " + size);
                                dbCreated = true;
                            }
                        }

                        if (dbCreated) {
                            for (File file : unzippedFiles) {
                                if (file.getName().endsWith("infile")) {
                                    String fPath = file.getCanonicalPath();
                                    if (UIHelper.isWindows()) {
                                        fPath = StringUtils.replace(fPath, "\\", "\\\\");
                                    }
                                    String sql = "LOAD DATA LOCAL INFILE '" + fPath + "' INTO TABLE "
                                            + FilenameUtils.getBaseName(file.getName());
                                    log.debug(sql);
                                    //System.err.println(sql);
                                    int rv = BasicSQLUtils.update(connection, sql);
                                    log.debug("done fPath[" + fPath + "] rv= " + rv);
                                    //System.err.println("done fPath["+fPath+"] rv= "+rv);
                                }
                            }
                        }

                        ZipFileHelper.getInstance().cleanUp();

                        /*if (!dbMgr.dropDatabase(databaseName))
                        {
                        log.error("Database["+databaseName+"] could not be dropped after load.");
                        UIRegistry.showLocalizedError("MySQLBackupService.ERR_DRP_DBAF", databaseName);
                        }*/

                        setProgress(100);

                        //errorMsg = sb.toString();

                        itDBConn.close();
                    } else {
                        // error can't connect
                    }
                } else {
                    // error
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                errorMsg = ex.toString();
                if (pcl != null) {
                    pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1));
                }

            } finally {
                BasicSQLUtils.setSkipTrackExceptions(skipTrackExceptions);
            }
            return null;
        }

        @Override
        protected void done() {
            super.done();

            JStatusBar statusBar = UIRegistry.getStatusBar();
            if (statusBar != null) {
                statusBar.setProgressDone(STATUSBAR_NAME);
            }

            if (glassPane != null) {
                UIRegistry.clearSimpleGlassPaneMsg();
            }

            if (StringUtils.isNotEmpty(errorMsg)) {
                UIRegistry.showError(errorMsg);
            }

            if (statusBar != null) {
                statusBar.setText(UIRegistry.getLocalizedMessage(completionMsgKey, dspMegs));
            }

            if (pcl != null) {
                pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, 0, 1));
            }
        }
    };

    if (glassPane != null) {
        glassPane.setProgress(0);
    }

    backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (MEGS.equals(evt.getPropertyName()) && glassPane != null) {
                int value = (Integer) evt.getNewValue();

                if (value < 100) {
                    glassPane.setProgress((Integer) evt.getNewValue());
                } else {
                    glassPane.setProgress(100);
                }
            }
        }
    });

    if (doSynchronously) {
        return backupWorker.doWork();
    }

    backupWorker.execute();
    return true;
}

From source file:org.kuali.kfs.module.tem.document.TravelDocumentBase.java

/**
 * Adds a new other expense line// w ww. j  a va2  s  .c  o m
 *
 * @see org.kuali.kfs.module.tem.document.TravelDocument#removeActualExpense(java.lang.Integer)
 */
@Override
@Transient
public void removeActualExpense(final Integer index) {
    final ActualExpense line = getActualExpenses().remove(index.intValue());
    notifyChangeListeners(new PropertyChangeEvent(this, TemPropertyConstants.ACTUAL_EXPENSES, line, null));

    //Remove detail lines which are associated with parentId
    int nextIndex = -1;
    while ((nextIndex = getNextDetailIndex(line.getId())) != -1) {
        final ActualExpense detailLine = getActualExpenses().remove(nextIndex);
        notifyChangeListeners(
                new PropertyChangeEvent(this, TemPropertyConstants.ACTUAL_EXPENSES, detailLine, null));
    }
}

From source file:org.kuali.kfs.module.tem.document.TravelDocumentBase.java

/**
 * @see org.kuali.kfs.module.tem.document.TravelDocument#removeExpense(org.kuali.kfs.module.tem.businessobject.TemExpense, java.lang.Integer)
 */// w  w w  .j a v  a2s. c  om
@Override
@Transient
public void removeExpense(TemExpense expense, Integer index) {
    TemExpense line = null;
    if (expense instanceof ActualExpense) {
        line = getActualExpenses().remove(index.intValue());
        notifyChangeListeners(new PropertyChangeEvent(this, TemPropertyConstants.ACTUAL_EXPENSES, line, null));
    } else {
        line = getImportedExpenses().remove(index.intValue());
        notifyChangeListeners(
                new PropertyChangeEvent(this, TemPropertyConstants.IMPORTED_EXPENSES, line, null));
    }
}

From source file:org.kuali.kfs.module.tem.document.TravelDocumentBase.java

/**
 * @see org.kuali.kfs.module.tem.document.TravelDocument#removeExpenseDetail(org.kuali.kfs.module.tem.businessobject.TemExpense, java.lang.Integer)
 *//*from w ww  . ja v a2  s.  co  m*/
@Override
@Transient
public void removeExpenseDetail(TemExpense expense, Integer index) {
    final TemExpense line = expense.getExpenseDetails().remove(index.intValue());
    notifyChangeListeners(new PropertyChangeEvent(this, TemPropertyConstants.EXPENSES_DETAILS, line, null));
}

From source file:edu.ku.brc.specify.tools.schemalocale.FieldItemPanel.java

/**
 * /* w  w  w .java 2s  .  c  o  m*/
 */
protected void fieldSelected() {
    boolean ignoreChanges = isIgnoreChanges();

    setIgnoreChanges(true);

    if (statusBar != null) {
        statusBar.setText("");
    }

    LocalizableItemIFace fld = getSelectedFieldItem();
    if (fld != null && tableInfo != null) {
        fieldInfo = fld != null ? tableInfo.getFieldByName(fld.getName()) : null;
        relInfo = fieldInfo == null ? tableInfo.getRelationshipByName(fld.getName()) : null;

        fillFormatSwticherCBX(tableInfo.getItemByName(fld.getName()));

        if (pcl != null) {
            pcl.propertyChange(new PropertyChangeEvent(fieldsList, "index", null, fld));
        }

        //fld = localizableIO.realize(fld);
        fieldDescText.setText(getDescStrForCurrLocale(fld));
        fieldNameText.setText(getNameDescStrForCurrLocale(fld));
        fieldHideChk.setSelected(fld.getIsHidden());

        String dspName = disciplineType != null ? disciplineType.getName() : null;
        if (AppContextMgr.getInstance().hasContext()
                && AppContextMgr.getInstance().getClassObject(Discipline.class) != null) {
            dspName = AppContextMgr.getInstance().getClassObject(Discipline.class).getType();
        }

        loadPickLists(dspName, fld);

        if (isDBSchema) {
            mustBeRequired = true;
            fieldReqChk.setSelected(false);

            DBTableInfo ti = DBTableIdMgr.getInstance().getInfoByTableName(currContainer.getName());
            if (ti != null) {
                DBFieldInfo fi = ti.getFieldByName(fld.getName());
                if (fi != null) {
                    String ts = fi.getType();
                    String typeStr = ts.indexOf('.') > -1 ? StringUtils.substringAfterLast(fi.getType(), ".")
                            : ts;
                    if (typeStr.equals("Calendar")) {
                        typeStr = "Date";
                    }
                    fieldTypeTxt.setText(typeStr);

                    String lenStr = fi.getLength() != -1 ? Integer.toString(fi.getLength()) : " ";
                    fieldLengthTxt.setText(lenStr);

                    fieldTypeLbl.setEnabled(true);
                    fieldTypeTxt.setEnabled(true);

                    fieldLengthLbl.setEnabled(StringUtils.isNotEmpty(lenStr));
                    fieldLengthTxt.setEnabled(StringUtils.isNotEmpty(lenStr));

                    mustBeRequired = fi.isRequiredInSchema();
                    fieldReqChk.setSelected(mustBeRequired || fld.getIsRequired());

                } else {
                    DBRelationshipInfo ri = ti.getRelationshipByName(fld.getName());
                    if (ri != null) {
                        String title = ri.getType().toString();
                        if (ri.getType() == DBRelationshipInfo.RelationshipType.OneToMany) {
                            title = DBRelationshipInfo.RelationshipType.OneToMany.toString();

                        } else if (ri.getType() == DBRelationshipInfo.RelationshipType.ManyToOne) {
                            title = DBRelationshipInfo.RelationshipType.ManyToOne.toString();
                        }
                        fieldTypeTxt.setText(title + " " + getResourceString("SL_TO") + " "
                                + getNameDescStrForCurrLocale(currContainer));
                        fieldTypeLbl.setEnabled(true);

                        fieldLengthTxt.setText(" ");
                        fieldLengthLbl.setEnabled(false);
                        fieldLengthTxt.setEnabled(false);

                        //fieldReqChk.setSelected(ri.isRequired());
                        fieldReqChk.setSelected(false);//fld.getIsRequired());
                    } else {
                        //throw new RuntimeException("couldn't find field or relationship.");
                    }
                }
            }
        }

        if (doAutoSpellCheck) {
            checker.spellCheck(fieldDescText);
            checker.spellCheck(fieldNameText);
        }

        enableUIControls(true);

    } else {
        enableUIControls(false);
        fieldDescText.setText("");
        fieldNameText.setText("");
        fieldHideChk.setSelected(false);
        fieldTypeTxt.setText("");
        fieldLengthTxt.setText("");
    }

    fillFormatBox(fieldInfo != null ? fieldInfo.getFormatter() : null);
    fillWebLinkBox();

    String label = SL_NONE;

    if (pickListCBX.getSelectedIndex() > 0) {
        label = SL_PICKLIST;
    }

    if (formatCombo.getSelectedIndex() > 0) {
        label = SL_FORMAT;
    }

    if (webLinkCombo.getSelectedIndex() > 0) {
        label = SL_WEBLINK;
    }

    formatSwitcherCombo.setSelectedItem(label);

    boolean ok = fld != null;
    fieldDescText.setEnabled(ok);
    fieldNameText.setEnabled(ok);
    fieldNameLbl.setEnabled(ok);
    fieldDescLbl.setEnabled(ok);

    setIgnoreChanges(ignoreChanges);

    prevField = fld;

    updateBtns();

    hasChanged = false;
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

protected void setPropertyValue(PropertyTokenHolder tokens, Object newValue) throws BeansException {
    String propertyName = tokens.canonicalName;

    if (tokens.keys != null) {
        // apply indexes and map keys: fetch value for all keys but the last one
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue = null;//from   w  ww.j a va2s  .c  o  m
        Type type;
        try {
            propValue = getPropertyValue(getterTokens);
            type = getPropertyType(getterTokens);
            if (propValue == null) {
                Class rawType = null;
                if (type instanceof ParameterizedType) {
                    if (((ParameterizedType) type).getRawType() instanceof Class) {
                        rawType = (Class) ((ParameterizedType) type).getRawType();
                    } else if (type instanceof Class) {
                        rawType = (Class) type;
                    }
                }
                if (rawType != null && List.class.isAssignableFrom(rawType)) {
                    PropertyTokenHolder propertyTokenHolder = new PropertyTokenHolder();
                    propertyTokenHolder.actualName = getterTokens.actualName;
                    propertyTokenHolder.canonicalName = getterTokens.canonicalName;
                    setPropertyValue(propertyTokenHolder, new ArrayList());
                }
            }
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // set value for last key
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "': returned null");
        } else if (propValue.getClass().isArray()) {
            Class requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (this.extractOldValueForEditor) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue,
                        newValue, requiredType);
                Array.set(propValue, Integer.parseInt(key), convertedValue);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, newValue);
                throw new TypeMismatchException(pce, requiredType, ex);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            List list = (List) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (this.extractOldValueForEditor && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    null);
            if (index < list.size()) {
                list.set(index, convertedValue);
            } else if (index >= list.size()) {
                for (int i = list.size(); i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + list.size()
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            }
        } else if (propValue instanceof Map) {
            Map map = (Map) propValue;
            propValue.getClass().getGenericSuperclass();
            Object oldValue = null;
            if (this.extractOldValueForEditor) {
                oldValue = map.get(key);
            }
            Type type2 = ((ParameterizedType) type).getActualTypeArguments()[1];
            Type type3 = ((ParameterizedType) type).getActualTypeArguments()[0];
            Class reqClass = null;
            Class keyReqClass = null;
            if (type2 instanceof Class) {
                reqClass = (Class) type2;
            } else if (type2 instanceof ParameterizedType) {
                reqClass = (Class) ((ParameterizedType) type2).getRawType();
            }

            if (type3 instanceof Class) {
                keyReqClass = (Class) type3;
            } else if (type3 instanceof ParameterizedType) {
                keyReqClass = (Class) ((ParameterizedType) type3).getRawType();
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    reqClass);
            Object convertedKey = doTypeConversionIfNecessary(key, keyReqClass);
            map.put(convertedKey, convertedValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + newValue
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName);
        if (pd == null || pd.getWriteMethod() == null) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName);
        }

        Method readMethod = pd.getReadMethod();
        Method writeMethod = pd.getWriteMethod();
        Object oldValue = null;

        if (this.extractOldValueForEditor && readMethod != null) {
            try {
                oldValue = readMethod.invoke(this.object, new Object[0]);
            } catch (Exception ex) {
                logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName,
                        ex);
            }
        }

        try {
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    pd.getPropertyType());

            if (pd.getPropertyType().isPrimitive() && (convertedValue == null || "".equals(convertedValue))) {
                throw new IllegalArgumentException("Invalid value [" + newValue + "] for property '"
                        + pd.getName() + "' of primitive type [" + pd.getPropertyType() + "]");
            }

            if (logger.isDebugEnabled()) {
                logger.debug("About to invoke write method [" + writeMethod + "] on object of class ["
                        + this.object.getClass().getName() + "]");
            }
            writeMethod.invoke(this.object, new Object[] { convertedValue });
            if (logger.isDebugEnabled()) {
                logger.debug("Invoked write method [" + writeMethod + "] with value of type ["
                        + pd.getPropertyType().getName() + "]");
            }
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, newValue);
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (IllegalArgumentException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new TypeMismatchException(pce, pd.getPropertyType(), ex);
        } catch (IllegalAccessException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java

/**
 * Performs necessary registration on inline components before actually
 * storing them.//from ww  w . ja  v a  2s.  c o m
 *
 * @param proxy
 *     the proxy to store the reference property for.
 * @param propertyDescriptor
 *     the reference property descriptor.
 * @param oldPropertyValue
 *     the old reference property value.
 * @param newPropertyValue
 *     the new reference property value.
 */
protected void storeReferenceProperty(Object proxy, IReferencePropertyDescriptor<?> propertyDescriptor,
        Object oldPropertyValue, Object newPropertyValue) {
    String propertyName = propertyDescriptor.getName();

    NestedReferenceTracker referenceTracker = null;
    if (referenceTrackers != null) {
        referenceTracker = referenceTrackers.get(propertyName);
    }

    // Handle owning component.
    if (oldPropertyValue instanceof IComponent && EntityHelper.isInlineComponentReference(propertyDescriptor)
            && isInitialized(oldPropertyValue)) {
        ((IComponent) oldPropertyValue).setOwningComponent(null, null);
    }
    if (newPropertyValue instanceof IComponent && EntityHelper.isInlineComponentReference(propertyDescriptor)
            && isInitialized(newPropertyValue)) {
        ((IComponent) newPropertyValue).setOwningComponent((IComponent) proxy, propertyDescriptor);
    }

    if (oldPropertyValue instanceof IPropertyChangeCapable) {
        if (isInitialized(oldPropertyValue)) {
            if (referenceTracker != null) {
                ((IPropertyChangeCapable) oldPropertyValue).removePropertyChangeListener(referenceTracker);
            }
            Set<String> nestedPropertyListening = null;
            if (fakePclAttachements != null) {
                nestedPropertyListening = fakePclAttachements.get(propertyName);
            }
            if (nestedPropertyListening != null) {
                for (String nestedPropertyName : nestedPropertyListening) {
                    ((IPropertyChangeCapable) oldPropertyValue).removePropertyChangeListener(nestedPropertyName,
                            createOrGetFakePcl());
                }
            }
            if (delayedFakePclAttachements != null) {
                delayedFakePclAttachements.remove(propertyName);
            }
        }
    }
    storeProperty(propertyName, newPropertyValue);
    if (newPropertyValue instanceof IPropertyChangeCapable) {
        Set<String> nestedPropertyListening = null;
        if (fakePclAttachements != null) {
            nestedPropertyListening = fakePclAttachements.get(propertyName);
        }
        if (nestedPropertyListening != null) {
            if (isInitialized(newPropertyValue)) {
                for (String nestedPropertyName : nestedPropertyListening) {
                    ((IPropertyChangeCapable) newPropertyValue)
                            .addWeakPropertyChangeListener(nestedPropertyName, createOrGetFakePcl());
                }
            } else {
                if (delayedFakePclAttachements == null) {
                    delayedFakePclAttachements = new THashMap<>(1, 1.0f);
                }
                delayedFakePclAttachements.put(propertyName, nestedPropertyListening);
            }
        }
        if (referenceTracker == null) {
            referenceTracker = new NestedReferenceTracker(proxy, propertyName,
                    EntityHelper.isInlineComponentReference(propertyDescriptor)
                            && !propertyDescriptor.isComputed());
            if (referenceTrackers == null) {
                referenceTrackers = new THashMap<>(1, 1.0f);
            }
            referenceTrackers.put(propertyName, referenceTracker);
        }
        referenceTracker.setInitialized(false);
        initializeInlineTrackerIfNeeded((IPropertyChangeCapable) newPropertyValue, propertyName,
                // To avoid breaking lazy initialization of oldPropertyValue
                !isInitialized(oldPropertyValue) || (isInitialized(newPropertyValue)
                        && !ObjectUtils.equals(oldPropertyValue, newPropertyValue)));
    } else if (referenceTracker != null) {
        if (oldPropertyValue instanceof IComponent
                // To avoid breaking lazy initialization optimisation
                && isInitialized(oldPropertyValue)) {
            for (Map.Entry<String, Object> property : ((IComponent) oldPropertyValue).straightGetProperties()
                    .entrySet()) {
                referenceTracker.propertyChange(new PropertyChangeEvent(oldPropertyValue, property.getKey(),
                        property.getValue(), null));
            }
        }
    }
}

From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java

/**
 * Performs (potentially delayed due to lazy initialization) inline tracker
 * attachment.//from w ww .ja v  a 2 s .  co m
 *
 * @param referenceProperty
 *     the reference to link the tracker to.
 * @param propertyName
 *     the property name of the tracker.
 * @param fireNestedPropertyChange
 *     Whenever the initialization is performed, does a first set of
 *     property change events be fired ?
 */
private void initializeInlineTrackerIfNeeded(IPropertyChangeCapable referenceProperty, String propertyName,
        boolean fireNestedPropertyChange) {
    if (referenceProperty != null && isInitialized(referenceProperty)) {
        NestedReferenceTracker storedTracker = null;
        if (referenceTrackers != null) {
            storedTracker = referenceTrackers.get(propertyName);
        }
        if (storedTracker != null && !storedTracker.isInitialized()) {
            storedTracker.setInitialized(true);
            referenceProperty.addWeakPropertyChangeListener(storedTracker);
            if (fireNestedPropertyChange && referenceProperty instanceof IComponent) {
                for (Map.Entry<String, Object> property : ((IComponent) referenceProperty)
                        .straightGetProperties().entrySet()) {
                    storedTracker.propertyChange(new PropertyChangeEvent(referenceProperty, property.getKey(),
                            IPropertyChangeCapable.UNKNOWN, property.getValue()));
                }
            }
        }
    }
}