1 /*******************************************************************************
2  * Copyright (c) 2009, 2015 Matthew Hall and others.
3  *
4  * This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License 2.0
6  * which accompanies this distribution, and is available at
7  * https://www.eclipse.org/legal/epl-2.0/
8  *
9  * SPDX-License-Identifier: EPL-2.0
10  *
11  * Contributors:
12  *     Matthew Hall - initial API and implementation (bug 265561)
13  *     Matthew Hall - bug 268336
14  ******************************************************************************/
15 
16 package org.eclipse.core.internal.databinding.beans;
17 
18 import java.beans.PropertyChangeListener;
19 import java.beans.PropertyDescriptor;
20 
21 import org.eclipse.core.databinding.observable.IDiff;
22 import org.eclipse.core.databinding.property.IProperty;
23 import org.eclipse.core.databinding.property.ISimplePropertyListener;
24 import org.eclipse.core.databinding.property.NativePropertyListener;
25 
26 /**
27  * @param <S> type of the source object
28  * @param <T> type of the property value that is being listened to
29  * @param <D> type of the diff handled by this listener
30  * @since 3.3
31  *
32  */
33 public abstract class BeanPropertyListener<S, T, D extends IDiff> extends NativePropertyListener<S, D>
34 		implements PropertyChangeListener {
35 	private final PropertyDescriptor propertyDescriptor;
36 
BeanPropertyListener(IProperty property, PropertyDescriptor propertyDescriptor, ISimplePropertyListener<S, D> listener)37 	protected BeanPropertyListener(IProperty property, PropertyDescriptor propertyDescriptor,
38 			ISimplePropertyListener<S, D> listener) {
39 		super(property, listener);
40 		this.propertyDescriptor = propertyDescriptor;
41 	}
42 
43 	@SuppressWarnings("unchecked")
44 	@Override
propertyChange(java.beans.PropertyChangeEvent evt)45 	public void propertyChange(java.beans.PropertyChangeEvent evt) {
46 		if (evt.getPropertyName() == null
47 				|| propertyDescriptor.getName().equals(evt.getPropertyName())) {
48 			Object oldValue = evt.getOldValue();
49 			Object newValue = evt.getNewValue();
50 			D diff;
51 			if (evt.getPropertyName() == null || oldValue == null || newValue == null) {
52 				diff = null;
53 			} else {
54 				diff = computeDiff((T) oldValue, (T) newValue);
55 			}
56 			fireChange((S) evt.getSource(), diff);
57 		}
58 	}
59 
computeDiff(T oldValue, T newValue)60 	protected abstract D computeDiff(T oldValue, T newValue);
61 
62 	@Override
doAddTo(Object source)63 	protected void doAddTo(Object source) {
64 		BeanPropertyListenerSupport.hookListener(source, propertyDescriptor.getName(), this);
65 	}
66 
67 	@Override
doRemoveFrom(Object source)68 	protected void doRemoveFrom(Object source) {
69 		BeanPropertyListenerSupport.unhookListener(source, propertyDescriptor.getName(), this);
70 	}
71 }