Integrated resource model related changes with eclipse plug-ins.
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ServiceProviderPlugin / src / oic / simulator / serviceprovider / view / AttributeEditingSupport.java
1 /*
2  * Copyright 2015 Samsung Electronics All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package oic.simulator.serviceprovider.view;
18
19 import java.util.Date;
20 import java.util.List;
21
22 import oic.simulator.serviceprovider.Activator;
23 import oic.simulator.serviceprovider.manager.ResourceManager;
24 import oic.simulator.serviceprovider.model.AttributeElement;
25 import oic.simulator.serviceprovider.model.AutomationSettingHelper;
26 import oic.simulator.serviceprovider.model.Resource;
27 import oic.simulator.serviceprovider.model.ResourceRepresentation;
28 import oic.simulator.serviceprovider.model.SingleResource;
29 import oic.simulator.serviceprovider.utils.AttributeValueBuilder;
30 import oic.simulator.serviceprovider.utils.Utility;
31 import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog;
32
33 import org.eclipse.jface.dialogs.MessageDialog;
34 import org.eclipse.jface.viewers.CellEditor;
35 import org.eclipse.jface.viewers.CheckboxCellEditor;
36 import org.eclipse.jface.viewers.ComboBoxCellEditor;
37 import org.eclipse.jface.viewers.EditingSupport;
38 import org.eclipse.jface.viewers.IStructuredSelection;
39 import org.eclipse.jface.viewers.TreeViewer;
40 import org.eclipse.jface.window.Window;
41 import org.eclipse.swt.SWT;
42 import org.eclipse.swt.custom.CCombo;
43 import org.eclipse.swt.events.ModifyEvent;
44 import org.eclipse.swt.events.ModifyListener;
45 import org.eclipse.swt.widgets.Display;
46 import org.eclipse.swt.widgets.MessageBox;
47 import org.eclipse.swt.widgets.Tree;
48 import org.eclipse.swt.widgets.TreeItem;
49 import org.eclipse.ui.IPartListener2;
50 import org.eclipse.ui.IWorkbenchPartReference;
51 import org.oic.simulator.AttributeProperty;
52 import org.oic.simulator.AttributeValue;
53 import org.oic.simulator.AttributeValue.TypeInfo;
54 import org.oic.simulator.AttributeValue.ValueType;
55 import org.oic.simulator.ILogger.Level;
56 import org.oic.simulator.InvalidArgsException;
57 import org.oic.simulator.SimulatorResourceAttribute;
58 import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
59
60 /**
61  * This class provides editing support to the resources attributes table in the
62  * attributes view.
63  */
64 public class AttributeEditingSupport {
65
66     private AttributeValueEditor attValueEditor;
67     private AutomationEditor     automationEditor;
68
69     public AttributeValueEditor createAttributeValueEditor(TreeViewer viewer) {
70         attValueEditor = new AttributeValueEditor(viewer);
71         return attValueEditor;
72     }
73
74     public AutomationEditor createAutomationEditor(TreeViewer viewer) {
75         automationEditor = new AutomationEditor(viewer);
76         return automationEditor;
77     }
78
79     class AttributeValueEditor extends EditingSupport {
80
81         private final TreeViewer viewer;
82         private CCombo           comboBox;
83
84         public AttributeValueEditor(TreeViewer viewer) {
85             super(viewer);
86             this.viewer = viewer;
87
88             // Using the part listener to refresh the viewer on various part
89             // events.
90             // If combo list is open, then click events on other parts of the
91             // view or outside the combo should hide the editor.
92             // Refreshing the viewer hides the combo and other editors which are
93             // active.
94             IPartListener2 partListener;
95             partListener = new IPartListener2() {
96
97                 @Override
98                 public void partVisible(IWorkbenchPartReference partRef) {
99                 }
100
101                 @Override
102                 public void partOpened(IWorkbenchPartReference partRef) {
103                 }
104
105                 @Override
106                 public void partInputChanged(IWorkbenchPartReference partRef) {
107                 }
108
109                 @Override
110                 public void partHidden(IWorkbenchPartReference partRef) {
111                 }
112
113                 @Override
114                 public void partDeactivated(IWorkbenchPartReference partRef) {
115                     String viewId = partRef.getId();
116                     if (viewId.equals(AttributeView.VIEW_ID)) {
117                         refreshViewer();
118                     }
119                 }
120
121                 @Override
122                 public void partClosed(IWorkbenchPartReference partRef) {
123                 }
124
125                 @Override
126                 public void partBroughtToTop(IWorkbenchPartReference partRef) {
127                 }
128
129                 @Override
130                 public void partActivated(IWorkbenchPartReference partRef) {
131                     String viewId = partRef.getId();
132                     if (viewId.equals(AttributeView.VIEW_ID)) {
133                         refreshViewer();
134                     }
135                 }
136             };
137
138             try {
139                 Activator.getDefault().getWorkbench()
140                         .getActiveWorkbenchWindow().getActivePage()
141                         .addPartListener(partListener);
142             } catch (NullPointerException e) {
143                 Activator
144                         .getDefault()
145                         .getLogManager()
146                         .log(Level.ERROR.ordinal(),
147                                 new Date(),
148                                 "There is an error while configuring the listener for UI.\n"
149                                         + Utility.getSimulatorErrorString(e,
150                                                 null));
151             }
152         }
153
154         public void refreshViewer() {
155             if (null == viewer)
156                 return;
157
158             Tree tree = viewer.getTree();
159             if (null == tree || tree.isDisposed())
160                 return;
161
162             viewer.refresh();
163         }
164
165         @Override
166         protected boolean canEdit(Object arg0) {
167             return true;
168         }
169
170         @Override
171         protected CellEditor getCellEditor(final Object element) {
172             ResourceManager resourceManager = Activator.getDefault()
173                     .getResourceManager();
174
175             Resource res = resourceManager.getCurrentResourceInSelection();
176             if (null == res) {
177                 return null;
178             }
179
180             // If selected resource is not a single resource, then editor
181             // support is not required.
182             if (!(res instanceof SingleResource)) {
183                 return null;
184             }
185
186             final SimulatorResourceAttribute attribute;
187             if (!(element instanceof AttributeElement)) {
188                 return null;
189             }
190
191             final AttributeElement attributeElement = ((AttributeElement) element);
192             attribute = attributeElement.getSimulatorResourceAttribute();
193             if (null == attribute) {
194                 return null;
195             }
196
197             // CellEditor is not required as the automation is in progress.
198             if (attributeElement.isAutoUpdateInProgress()) {
199                 return null;
200             }
201
202             final AttributeValue val = attribute.value();
203             if (null == val) {
204                 return null;
205             }
206
207             final TypeInfo type = val.typeInfo();
208             if (type.mBaseType == ValueType.RESOURCEMODEL) {
209                 return null;
210             }
211
212             AttributeProperty prop = attribute.property();
213             if (null == prop) {
214                 return null;
215             }
216
217             if (!resourceManager.isAttHasRangeOrAllowedValues(attribute)) {
218                 return null;
219             }
220
221             String values[] = null;
222             List<String> valueSet = resourceManager
223                     .getAllValuesOfAttribute(attribute);
224             values = Utility.convertListToStringArray(valueSet);
225
226             ComboBoxCellEditor comboEditor;
227             if (type.mType == ValueType.ARRAY) {
228                 comboEditor = new ComboBoxCellEditor(viewer.getTree(), values);
229             } else {
230                 comboEditor = new ComboBoxCellEditor(viewer.getTree(), values,
231                         SWT.READ_ONLY);
232             }
233             comboBox = (CCombo) comboEditor.getControl();
234             comboBox.addModifyListener(new ModifyListener() {
235
236                 @Override
237                 public void modifyText(ModifyEvent event) {
238                     if (type.mType == ValueType.ARRAY) {
239                         return;
240                     }
241                     String oldValue = String.valueOf(Utility
242                             .getAttributeValueAsString(val));
243                     String newValue = comboBox.getText();
244
245                     attributeElement.setEditLock(true);
246                     compareAndUpdateAttribute(oldValue, newValue, element,
247                             attribute, type);
248                     attributeElement.setEditLock(false);
249
250                     comboBox.setVisible(false);
251                 }
252             });
253             return comboEditor;
254         }
255
256         @Override
257         protected Object getValue(Object element) {
258             int indexOfItem = 0;
259             SimulatorResourceAttribute att = null;
260
261             if (element instanceof AttributeElement) {
262                 att = ((AttributeElement) element)
263                         .getSimulatorResourceAttribute();
264             }
265
266             if (att == null) {
267                 return 0;
268             }
269
270             String valueString = Utility.getAttributeValueAsString(att.value());
271             List<String> valueSet = Activator.getDefault().getResourceManager()
272                     .getAllValuesOfAttribute(att);
273             if (null != valueSet) {
274                 indexOfItem = valueSet.indexOf(valueString);
275             }
276             if (indexOfItem == -1) {
277                 indexOfItem = 0;
278             }
279             return indexOfItem;
280         }
281
282         @Override
283         protected void setValue(Object element, Object value) {
284         }
285
286         public void compareAndUpdateAttribute(String oldValue, String newValue,
287                 Object element, SimulatorResourceAttribute att, TypeInfo type) {
288             if (null == oldValue || null == newValue || null == element
289                     || null == att || null == type) {
290                 return;
291             }
292             if (!oldValue.equals(newValue)) {
293                 // Get the AttriuteValue from the string
294                 AttributeValue attValue = AttributeValueBuilder.build(newValue,
295                         type.mBaseType);
296                 boolean invalid = false;
297                 if (null == attValue) {
298                     invalid = true;
299                 } else {
300                     TypeInfo resTypeInfo = attValue.typeInfo();
301                     if (type.mDepth != resTypeInfo.mDepth
302                             || type.mType != resTypeInfo.mType
303                             || type.mBaseType != resTypeInfo.mBaseType) {
304                         invalid = true;
305                     }
306                 }
307                 if (invalid) {
308                     MessageBox dialog = new MessageBox(viewer.getTree()
309                             .getShell(), SWT.ICON_ERROR | SWT.OK);
310                     dialog.setText("Invalid Value");
311                     dialog.setMessage("Given value is invalid");
312                     dialog.open();
313                 } else {
314                     MessageBox dialog = new MessageBox(viewer.getTree()
315                             .getShell(), SWT.ICON_QUESTION | SWT.OK
316                             | SWT.CANCEL);
317                     dialog.setText("Confirm action");
318                     dialog.setMessage("Do you want to modify the value?");
319                     int retval = dialog.open();
320                     if (retval != SWT.OK) {
321                         attValue = AttributeValueBuilder.build(oldValue,
322                                 type.mBaseType);
323                         updateAttributeValue(att, attValue);
324                     } else {
325                         updateAttributeValue(att, attValue);
326
327                         ResourceManager resourceManager;
328                         resourceManager = Activator.getDefault()
329                                 .getResourceManager();
330
331                         Resource resource = resourceManager
332                                 .getCurrentResourceInSelection();
333
334                         SimulatorResourceAttribute result = getResultantAttribute();
335
336                         boolean updated = resourceManager
337                                 .attributeValueUpdated(
338                                         (SingleResource) resource,
339                                         result.name(), result.value());
340                         if (!updated) {
341                             attValue = AttributeValueBuilder.build(oldValue,
342                                     type.mBaseType);
343                             updateAttributeValue(att, attValue);
344                             MessageDialog.openInformation(Display.getDefault()
345                                     .getActiveShell(), "Operation failed",
346                                     "Failed to update the attribute value.");
347                         }
348                     }
349                 }
350             }
351             viewer.update(element, null);
352         }
353
354         public void updateAttributeValue(SimulatorResourceAttribute att,
355                 AttributeValue value) {
356             IStructuredSelection selection = (IStructuredSelection) viewer
357                     .getSelection();
358             if (null == selection) {
359                 return;
360             }
361
362             Object obj = selection.getFirstElement();
363             if (null == obj) {
364                 return;
365             }
366
367             Tree t = viewer.getTree();
368             TreeItem item = t.getSelection()[0];
369             if (null == item) {
370                 return;
371             }
372
373             if (item.getData() instanceof AttributeElement) {
374                 AttributeElement attributeElement = (AttributeElement) item
375                         .getData();
376                 attributeElement.getSimulatorResourceAttribute()
377                         .setValue(value);
378
379                 TreeItem parent = item.getParentItem();
380                 if (null != parent) {
381                     Object data = parent.getData();
382                     try {
383                         ((AttributeElement) data).deepSetChildValue(att);
384                     } catch (InvalidArgsException e) {
385                         e.printStackTrace();
386                     }
387                 }
388             }
389         }
390
391         public SimulatorResourceAttribute getResultantAttribute() {
392             IStructuredSelection selection = (IStructuredSelection) viewer
393                     .getSelection();
394             if (null == selection) {
395                 return null;
396             }
397
398             Object obj = selection.getFirstElement();
399             if (null == obj) {
400                 return null;
401             }
402
403             Tree t = viewer.getTree();
404             TreeItem item = t.getSelection()[0];
405             if (null == item) {
406                 return null;
407             }
408
409             SimulatorResourceAttribute result = null;
410             TreeItem parent = item.getParentItem();
411             if (null == parent) {
412                 Object data = item.getData();
413                 result = ((AttributeElement) data)
414                         .getSimulatorResourceAttribute();
415             } else {
416                 while (parent.getParentItem() != null) {
417                     parent = parent.getParentItem();
418                 }
419
420                 // Parent will point to the top-level attribute of type
421                 Object data = parent.getData();
422                 result = ((AttributeElement) data)
423                         .getSimulatorResourceAttribute();
424             }
425
426             return result;
427         }
428     }
429
430     class AutomationEditor extends EditingSupport {
431
432         private final TreeViewer viewer;
433
434         public AutomationEditor(TreeViewer viewer) {
435             super(viewer);
436             this.viewer = viewer;
437         }
438
439         @Override
440         protected boolean canEdit(Object arg0) {
441             return true;
442         }
443
444         @Override
445         protected CellEditor getCellEditor(Object element) {
446             // CellEditor is not required as the automation is in progress.
447             ResourceManager resourceManager = Activator.getDefault()
448                     .getResourceManager();
449             Resource resource = resourceManager.getCurrentResourceInSelection();
450
451             if (null == resource) {
452                 return null;
453             }
454
455             if (!(resource instanceof SingleResource)) {
456                 return null;
457             }
458             if (((SingleResource) resource).isResourceAutomationInProgress()) {
459                 return null;
460             }
461
462             SimulatorResourceAttribute att = null;
463             if (element instanceof AttributeElement) {
464                 att = ((AttributeElement) element)
465                         .getSimulatorResourceAttribute();
466             }
467
468             if (null == att) {
469                 return null;
470             }
471
472             AttributeValue val = att.value();
473             if (null == val) {
474                 return null;
475             }
476
477             TypeInfo type = val.typeInfo();
478
479             if (type.mType == ValueType.RESOURCEMODEL
480                     || type.mType == ValueType.ARRAY) {
481                 return null;
482             }
483
484             Object parent = ((AttributeElement) element).getParent();
485             if (null != parent && !(parent instanceof ResourceRepresentation)) {
486                 return null;
487             }
488
489             if (((AttributeElement) element).isReadOnly()) {
490                 return null;
491             }
492
493             return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
494         }
495
496         @Override
497         protected Object getValue(Object element) {
498             if (element instanceof AttributeElement) {
499                 return ((AttributeElement) element).isAutoUpdateInProgress();
500             }
501
502             return false;
503         }
504
505         @Override
506         protected void setValue(Object element, Object value) {
507             if (!(element instanceof AttributeElement)) {
508                 return;
509             }
510
511             ResourceManager resourceManager = Activator.getDefault()
512                     .getResourceManager();
513             // As automation depends on the current resource in selection, its
514             // presence is being checked.
515             Resource resource = resourceManager.getCurrentResourceInSelection();
516             if (null == resource) {
517                 return;
518             }
519
520             AttributeElement att = (AttributeElement) element;
521             boolean checked = (Boolean) value;
522             if (checked) {
523                 // Start the automation
524                 // Fetch the settings data
525                 List<AutomationSettingHelper> automationSettings;
526                 automationSettings = AutomationSettingHelper
527                         .getAutomationSettings(att);
528
529                 // Open the settings dialog
530                 AutomationSettingDialog dialog = new AutomationSettingDialog(
531                         viewer.getTree().getShell(), automationSettings);
532                 dialog.create();
533                 if (dialog.open() == Window.OK) {
534                     String automationType = dialog.getAutomationType();
535                     String updateFreq = dialog.getUpdateFrequency();
536
537                     AutoUpdateType autoType = AutoUpdateType
538                             .valueOf(automationType);
539                     int updFreq = Utility
540                             .getUpdateIntervalFromString(updateFreq);
541                     int autoId = resourceManager.startAutomation(
542                             (SingleResource) resource, att, autoType, updFreq);
543                     if (autoId == -1) {
544                         MessageDialog.openInformation(Display.getDefault()
545                                 .getActiveShell(), "Automation Status",
546                                 "Automation start failed!!");
547                     }
548                 }
549             } else {
550                 // Stop the automation
551                 resourceManager.stopAutomation((SingleResource) resource, att,
552                         att.getAutoUpdateId());
553             }
554         }
555     }
556 }